code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.vector_ar.var_model.VARResults.cov_params — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar" href="statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARResults.acorr" href="statsmodels.tsa.vector_ar.var_model.VARResults.acorr.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.vector_ar.var_model.VARResults.cov_params" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.2</span>
<span class="md-header-nav__topic"> statsmodels.tsa.vector_ar.var_model.VARResults.cov_params </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../vector_ar.html" class="md-tabs__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.html" class="md-tabs__link">statsmodels.tsa.vector_ar.var_model.VARResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.2</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARResults.cov_params.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-vector-ar-var-model-varresults-cov-params--page-root">statsmodels.tsa.vector_ar.var_model.VARResults.cov_params<a class="headerlink" href="#generated-statsmodels-tsa-vector-ar-var-model-varresults-cov-params--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.tsa.vector_ar.var_model.VARResults.cov_params">
<code class="sig-prename descclassname">VARResults.</code><code class="sig-name descname">cov_params</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.cov_params"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.var_model.VARResults.cov_params" title="Permalink to this definition">¶</a></dt>
<dd><p>Estimated variance-covariance of model coefficients</p>
<p class="rubric">Notes</p>
<p>Covariance of vec(B), where B is the matrix
[params_for_deterministic_terms, A_1, …, A_p] with the shape
(K x (Kp + number_of_deterministic_terms))
Adjusted to be an unbiased estimator
Ref: Lütkepohl p.74-75</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.vector_ar.var_model.VARResults.acorr.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.acorr"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.vector_ar.var_model.VARResults.acorr </span>
</div>
</a>
<a href="statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 02, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
Java
|
{% extends "tournamentcontrol/competition/season.html" %}
{% load i18n tz %}
{% block content %}
<h1>{% trans "Daily Run Sheets" %}</h1>
<ul>
{% for date in dates %}
<li><a href="{% url application.name|add:":runsheet" competition=competition.slug season=season.slug datestr=date|date:"Ymd" %}">{{ date }}</a></li>
{% endfor %}
</ul>
{% endblock %}
|
Java
|
/*
* Copyright (C) 2017-present Frederic Meyer. All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "vt100.h"
#include <stddef.h>
struct vt100_term* vt100_init(struct vt100_term* this, int buffer_width, int buffer_height) {
this->state = VT100_INITIAL;
this->color = 7;
this->cursor_x = 0;
this->cursor_y = 0;
this->buffer_width = buffer_width;
this->buffer_height = buffer_height;
this->set_char = NULL;
this->set_cursor = NULL;
this->clear_from_to = NULL;
return this;
}
#define UPDATE_CURSOR \
if (this->set_cursor != NULL) { \
this->set_cursor(this->cursor_x, this->cursor_y); \
}
void vt100_write(struct vt100_term* this, char c) {
switch (this->state) {
// Last character was 0x1B (aka \e or ESC).
// This indicates an escape sequence that allows more complex
// instructions, e.g. setting terminal foreground & background color.
case VT100_ESCAPE:
switch (c) {
// CSI - Control Sequence Introducer
case '[': {
// Clear any left over CSI data
this->csi.num = 0;
for (int i = 0; i < VT100_MAX_PARAMS; i++) {
this->csi.params[i] = 0;
}
this->state = VT100_CONTROL_SEQ;
break;
}
// RIS – Reset to Initial State
case 'c':
this->cursor_x = 0;
this->cursor_y = 0;
this->color = 0x07;
this->state = VT100_INITIAL;
if (this->set_cursor != NULL) {
this->set_cursor(0, 0);
}
if (this->clear_from_to != NULL) {
this->clear_from_to(0, 0, this->buffer_width - 1, this->buffer_height - 1, this->color);
}
break;
}
break;
// Inside of control sequence.
// Starts optionally with a sequence of arguments/parameters
// then ends with one character indicating the command.
// TODO: prevent buffer overlows (csi.params)
case VT100_CONTROL_SEQ:
switch (c) {
// Digit, "append" to current parameter.
case '0': case '1':
case '2': case '3':
case '4': case '5':
case '6': case '7':
case '8': case '9':
this->csi.params[this->csi.num] *= 10;
this->csi.params[this->csi.num] += c - '0';
break;
// Ṕarameter delimiter
case ';':
this->csi.num++;
break;
// Set Display Attributes
case 'm': {
for (int i = 0; i <= this->csi.num; i++) {
int attribute = this->csi.params[i];
switch (attribute) {
// Reset state
case 0:
// TODO: implement more
this->color = 7;
break;
// Foreground color
case 30: case 31:
case 32: case 33:
case 34: case 35:
case 36: case 37:
this->color = (this->color & 0xF0) | (attribute - 30);
break;
// Background color
case 40: case 41:
case 42: case 43:
case 44: case 45:
case 46: case 47:
this->color = (this->color & 0x0F) | ((attribute - 40) << 4);
break;
}
}
this->state = VT100_INITIAL;
break;
}
/*// Erase Line
case 'K':
if (this->clear_from_to == NULL) {
break;
}
if (this->csi.num == 0) {
// Cursor to End of line
this->clear_from_to(this->cursor_x, this->cursor_y, this->buffer_width - 1, this->cursor_y, this->color);
} else {
switch (this->csi.params[0]) {
// Start of line to cursor
case 0:
this->clear_from_to(0, this->cursor_y, this->cursor_x, this->cursor_y, this->color);
break;
// Erase entire line
case 1:
this->clear_from_to(0, this->cursor_y, this->buffer_width - 1, this->buffer_height - 1, this->color);
break;
}
}
break;
// Erase Block
case 'J':
break;
*/
default:
// Possibly unknown command, or bad sequence. Ignore.
this->state = VT100_INITIAL;
break;
}
break;
// Default state
case VT100_INITIAL:
switch (c) {
// Non-control character. Print it.
default:
// TODO: implement line wrap flag
if (this->cursor_x == this->buffer_width) {
this->cursor_x = 0;
this->cursor_y++;
}
if (this->set_char != NULL) {
this->set_char(this->cursor_x, this->cursor_y, c, this->color);
}
this->cursor_x++;
UPDATE_CURSOR;
break;
// Carriage Return
case VT100_CR:
this->cursor_x = 0;
UPDATE_CURSOR;
break;
// New Line
case VT100_LF:
this->cursor_x = 0;
this->cursor_y++;
UPDATE_CURSOR;
break;
// Back Space
case VT100_BS:
// TODO: verify this behaviour
if (this->cursor_x == 0) {
this->cursor_x = this->buffer_width;
this->cursor_y--;
} else {
this->cursor_x--;
}
//if (this->set_char != NULL) {
// this->set_char(this->cursor_x, this->cursor_y, ' ', this->color);
//}
UPDATE_CURSOR;
break;
// Horizontal Tab
// Converting your precious TAB to spaces. Resistance is furtile.
case VT100_HT: {
int spaces;
if (this->cursor_x != 0) {
spaces = ((this->cursor_x - 1) & 7) ^ 7;
} else {
// TODO: verify this on other VTs
spaces = 9;
}
while (spaces--) vt100_write(this, ' ');
break;
}
// Vertical Tab
case VT100_VT:
// TODO: implement
break;
// Form Feed
case VT100_FF:
// TODO: implement
break;
// Complex escape sequence!
case VT100_ESC:
this->state = VT100_ESCAPE;
break;
}
break;
}
}
|
Java
|
<?php
namespace Application\ViewModel;
use Application\Domain\Factory\Factory;
use Zend\View\Model\ViewModel;
class MemberDetailViewModel extends ViewModel
{
private $userId;
public function __construct($userId)
{
parent::__construct();
$this->userId = $userId;
$this->setViewData();
}
public function setViewData()
{
$userService = Factory::getInstance()->getUserService();
$issues = $userService->getMemberDetailData($this->userId);
$user = Factory::getInstance()->getUserRepository()->getUserByPk($this->userId);
$this->setVariables(
[
'issues' => $issues,
'userName' => $user['name']
]
, true);
}
}
|
Java
|
/*
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/platform/graphics/image.h"
#include <math.h>
#include <tuple>
#include "base/numerics/checked_math.h"
#include "build/build_config.h"
#include "cc/tiles/software_image_decode_cache.h"
#include "third_party/blink/public/mojom/webpreferences/web_preferences.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_data.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_filter_helper.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_image_cache.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h"
#include "third_party/blink/renderer/platform/graphics/deferred_image_decoder.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_shader.h"
#include "third_party/blink/renderer/platform/graphics/scoped_interpolation_quality.h"
#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/skia_conversions.h"
namespace blink {
Image::Image(ImageObserver* observer, bool is_multipart)
: image_observer_disabled_(false),
image_observer_(observer),
stable_image_id_(PaintImage::GetNextId()),
is_multipart_(is_multipart) {}
Image::~Image() = default;
Image* Image::NullImage() {
DCHECK(IsMainThread());
DEFINE_STATIC_REF(Image, null_image, (BitmapImage::Create()));
return null_image;
}
// static
cc::ImageDecodeCache& Image::SharedCCDecodeCache(SkColorType color_type) {
// This denotes the allocated locked memory budget for the cache used for
// book-keeping. The cache indicates when the total memory locked exceeds this
// budget in cc::DecodedDrawImage.
DCHECK(color_type == kN32_SkColorType || color_type == kRGBA_F16_SkColorType);
static const size_t kLockedMemoryLimitBytes = 64 * 1024 * 1024;
if (color_type == kRGBA_F16_SkColorType) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
cc::SoftwareImageDecodeCache, image_decode_cache,
(kRGBA_F16_SkColorType, kLockedMemoryLimitBytes,
PaintImage::kDefaultGeneratorClientId));
return image_decode_cache;
}
DEFINE_THREAD_SAFE_STATIC_LOCAL(cc::SoftwareImageDecodeCache,
image_decode_cache,
(kN32_SkColorType, kLockedMemoryLimitBytes,
PaintImage::kDefaultGeneratorClientId));
return image_decode_cache;
}
scoped_refptr<Image> Image::LoadPlatformResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) {
const WebData& resource =
Platform::Current()->GetDataResource(resource_id, scale_factor);
if (resource.IsEmpty())
return Image::NullImage();
scoped_refptr<Image> image = BitmapImage::Create();
image->SetData(resource, true);
return image;
}
// static
PaintImage Image::ResizeAndOrientImage(
const PaintImage& image,
ImageOrientation orientation,
gfx::Vector2dF image_scale,
float opacity,
InterpolationQuality interpolation_quality) {
gfx::Size size(image.width(), image.height());
size = gfx::ScaleToFlooredSize(size, image_scale.x(), image_scale.y());
AffineTransform transform;
if (orientation != ImageOrientationEnum::kDefault) {
if (orientation.UsesWidthAsHeight())
size.Transpose();
transform *= orientation.TransformFromDefault(gfx::SizeF(size));
}
transform.ScaleNonUniform(image_scale.x(), image_scale.y());
if (size.IsEmpty())
return PaintImage();
if (transform.IsIdentity() && opacity == 1) {
// Nothing to adjust, just use the original.
DCHECK_EQ(image.width(), size.width());
DCHECK_EQ(image.height(), size.height());
return image;
}
const SkImageInfo info =
SkImageInfo::MakeN32(size.width(), size.height(), kPremul_SkAlphaType,
SkColorSpace::MakeSRGB());
sk_sp<SkSurface> surface = SkSurface::MakeRaster(info);
if (!surface)
return PaintImage();
SkPaint paint;
DCHECK_GE(opacity, 0);
DCHECK_LE(opacity, 1);
paint.setAlpha(opacity * 255);
SkSamplingOptions sampling;
if (interpolation_quality != kInterpolationNone)
sampling = SkSamplingOptions(SkCubicResampler::CatmullRom());
SkCanvas* canvas = surface->getCanvas();
canvas->concat(AffineTransformToSkMatrix(transform));
canvas->drawImage(image.GetSwSkImage(), 0, 0, sampling, &paint);
return PaintImageBuilder::WithProperties(std::move(image))
.set_image(surface->makeImageSnapshot(), PaintImage::GetNextContentId())
.TakePaintImage();
}
Image::SizeAvailability Image::SetData(scoped_refptr<SharedBuffer> data,
bool all_data_received) {
encoded_image_data_ = std::move(data);
if (!encoded_image_data_.get())
return kSizeAvailable;
size_t length = encoded_image_data_->size();
if (!length)
return kSizeAvailable;
return DataChanged(all_data_received);
}
String Image::FilenameExtension() const {
return String();
}
namespace {
sk_sp<PaintShader> CreatePatternShader(const PaintImage& image,
const SkMatrix& shader_matrix,
const SkSamplingOptions& sampling,
bool should_antialias,
const gfx::SizeF& spacing,
SkTileMode tmx,
SkTileMode tmy,
const gfx::Rect& subset_rect) {
if (spacing.IsZero() &&
subset_rect == gfx::Rect(image.width(), image.height())) {
return PaintShader::MakeImage(image, tmx, tmy, &shader_matrix);
}
// Arbitrary tiling is currently only supported for SkPictureShader, so we use
// that instead of a plain bitmap shader to implement spacing.
const SkRect tile_rect =
SkRect::MakeWH(subset_rect.width() + spacing.width(),
subset_rect.height() + spacing.height());
PaintRecorder recorder;
cc::PaintCanvas* canvas = recorder.beginRecording(tile_rect);
PaintFlags flags;
flags.setAntiAlias(should_antialias);
canvas->drawImageRect(
image, gfx::RectToSkRect(subset_rect),
SkRect::MakeWH(subset_rect.width(), subset_rect.height()), sampling,
&flags, SkCanvas::kStrict_SrcRectConstraint);
return PaintShader::MakePaintRecord(recorder.finishRecordingAsPicture(),
tile_rect, tmx, tmy, &shader_matrix);
}
SkTileMode ComputeTileMode(float left, float right, float min, float max) {
DCHECK(left < right);
return left >= min && right <= max ? SkTileMode::kClamp : SkTileMode::kRepeat;
}
} // anonymous namespace
void Image::DrawPattern(GraphicsContext& context,
const cc::PaintFlags& base_flags,
const gfx::RectF& dest_rect,
const ImageTilingInfo& tiling_info,
const ImageDrawOptions& draw_options) {
TRACE_EVENT0("skia", "Image::drawPattern");
if (dest_rect.IsEmpty())
return; // nothing to draw
PaintImage image = PaintImageForCurrentFrame();
if (!image)
return; // nothing to draw
// Fetch orientation data if needed.
ImageOrientation orientation = ImageOrientationEnum::kDefault;
if (draw_options.respect_orientation)
orientation = CurrentFrameOrientation();
// |tiling_info.image_rect| is in source image space, unscaled but oriented.
// image-resolution information is baked into |tiling_info.scale|,
// so we do not want to use it in computing the subset. That requires
// explicitly applying orientation here.
gfx::Rect subset_rect = gfx::ToEnclosingRect(tiling_info.image_rect);
gfx::Size oriented_image_size(image.width(), image.height());
if (orientation.UsesWidthAsHeight())
oriented_image_size.Transpose();
subset_rect.Intersect(gfx::Rect(oriented_image_size));
if (subset_rect.IsEmpty())
return; // nothing to draw
// Apply image orientation, if necessary
if (orientation != ImageOrientationEnum::kDefault)
image = ResizeAndOrientImage(image, orientation);
// We also need to translate it such that the origin of the pattern is the
// origin of the destination rect, which is what Blink expects. Skia uses
// the coordinate system origin as the base for the pattern. If Blink wants
// a shifted image, it will shift it from there using the localMatrix.
gfx::RectF tile_rect(subset_rect);
tile_rect.Scale(tiling_info.scale.x(), tiling_info.scale.y());
tile_rect.Offset(tiling_info.phase.OffsetFromOrigin());
tile_rect.Outset(0, 0, tiling_info.spacing.width(),
tiling_info.spacing.height());
SkMatrix local_matrix;
local_matrix.setTranslate(tile_rect.x(), tile_rect.y());
// Apply the scale to have the subset correctly fill the destination.
local_matrix.preScale(tiling_info.scale.x(), tiling_info.scale.y());
const auto tmx = ComputeTileMode(dest_rect.x(), dest_rect.right(),
tile_rect.x(), tile_rect.right());
const auto tmy = ComputeTileMode(dest_rect.y(), dest_rect.bottom(),
tile_rect.y(), tile_rect.bottom());
// Fetch this now as subsetting may swap the image.
auto image_id = image.stable_id();
SkSamplingOptions sampling_to_use =
context.ComputeSamplingOptions(this, dest_rect, gfx::RectF(subset_rect));
sk_sp<PaintShader> tile_shader = CreatePatternShader(
image, local_matrix, sampling_to_use, context.ShouldAntialias(),
gfx::SizeF(tiling_info.spacing.width() / tiling_info.scale.x(),
tiling_info.spacing.height() / tiling_info.scale.y()),
tmx, tmy, subset_rect);
// If the shader could not be instantiated (e.g. non-invertible matrix),
// draw transparent.
// Note: we can't simply bail, because of arbitrary blend mode.
PaintFlags flags(base_flags);
flags.setColor(tile_shader ? SK_ColorBLACK : SK_ColorTRANSPARENT);
flags.setShader(std::move(tile_shader));
if (draw_options.apply_dark_mode) {
DarkModeFilter* dark_mode_filter = draw_options.dark_mode_filter;
DarkModeFilterHelper::ApplyToImageIfNeeded(*dark_mode_filter, this, &flags,
gfx::RectToSkRect(subset_rect),
gfx::RectFToSkRect(dest_rect));
}
context.DrawRect(gfx::RectFToSkRect(dest_rect), flags,
AutoDarkMode::Disabled());
StartAnimation();
if (CurrentFrameIsLazyDecoded()) {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"Draw LazyPixelRef", TRACE_EVENT_SCOPE_THREAD,
"LazyPixelRef", image_id);
}
}
mojom::blink::ImageAnimationPolicy Image::AnimationPolicy() {
return mojom::blink::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
}
scoped_refptr<Image> Image::ImageForDefaultFrame() {
scoped_refptr<Image> image(this);
return image;
}
PaintImageBuilder Image::CreatePaintImageBuilder() {
auto animation_type = MaybeAnimated() ? PaintImage::AnimationType::ANIMATED
: PaintImage::AnimationType::STATIC;
return PaintImageBuilder::WithDefault()
.set_id(stable_image_id_)
.set_animation_type(animation_type)
.set_is_multipart(is_multipart_);
}
bool Image::ApplyShader(PaintFlags& flags,
const SkMatrix& local_matrix,
const gfx::RectF& dst_rect,
const gfx::RectF& src_rect,
const ImageDrawOptions& draw_options) {
// Default shader impl: attempt to build a shader based on the current frame
// SkImage.
PaintImage image = PaintImageForCurrentFrame();
if (!image)
return false;
if (draw_options.apply_dark_mode) {
DarkModeFilter* dark_mode_filter = draw_options.dark_mode_filter;
DarkModeFilterHelper::ApplyToImageIfNeeded(*dark_mode_filter, this, &flags,
gfx::RectFToSkRect(src_rect),
gfx::RectFToSkRect(dst_rect));
}
flags.setShader(PaintShader::MakeImage(image, SkTileMode::kClamp,
SkTileMode::kClamp, &local_matrix));
if (!flags.HasShader())
return false;
// Animation is normally refreshed in draw() impls, which we don't call when
// painting via shaders.
StartAnimation();
return true;
}
SkBitmap Image::AsSkBitmapForCurrentFrame(
RespectImageOrientationEnum respect_image_orientation) {
PaintImage paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return {};
if (auto* bitmap_image = DynamicTo<BitmapImage>(this)) {
const gfx::Size paint_image_size(paint_image.width(), paint_image.height());
const gfx::Size density_corrected_size =
bitmap_image->DensityCorrectedSize();
ImageOrientation orientation = ImageOrientationEnum::kDefault;
if (respect_image_orientation == kRespectImageOrientation)
orientation = bitmap_image->CurrentFrameOrientation();
gfx::Vector2dF image_scale(1, 1);
if (density_corrected_size != paint_image_size) {
image_scale = gfx::Vector2dF(
density_corrected_size.width() / paint_image_size.width(),
density_corrected_size.height() / paint_image_size.height());
}
paint_image = ResizeAndOrientImage(paint_image, orientation, image_scale);
if (!paint_image)
return {};
}
sk_sp<SkImage> sk_image = paint_image.GetSwSkImage();
if (!sk_image)
return {};
SkBitmap bitmap;
sk_image->asLegacyBitmap(&bitmap);
return bitmap;
}
DarkModeImageCache* Image::GetDarkModeImageCache() {
if (!dark_mode_image_cache_)
dark_mode_image_cache_ = std::make_unique<DarkModeImageCache>();
return dark_mode_image_cache_.get();
}
gfx::RectF Image::CorrectSrcRectForImageOrientation(gfx::SizeF image_size,
gfx::RectF src_rect) const {
ImageOrientation orientation = CurrentFrameOrientation();
DCHECK(orientation != ImageOrientationEnum::kDefault);
AffineTransform forward_map = orientation.TransformFromDefault(image_size);
AffineTransform inverse_map = forward_map.Inverse();
return inverse_map.MapRect(src_rect);
}
} // namespace blink
|
Java
|
<?php
/**
* CoolMS2 Twitter Bootstrap Module (http://www.coolms.com/)
*
* @link http://github.com/coolms/twbs for the canonical source repository
* @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
* @license http://www.coolms.com/license/new-bsd New BSD License
* @author Dmitry Popov <d.popov@altgraphic.com>
*/
namespace CmsTwbs\Form\View\Helper;
use Zend\Form\View\Helper\FormText as FormTextHelper,
CmsCommon\View\Helper\Decorator\DecoratorProviderInterface;
class FormText extends FormTextHelper implements DecoratorProviderInterface
{
/**
* @var array
*/
protected $decoratorSpecification = [
'element' => ['type' => 'formControl'],
'icon' => [
'placement' => false,
'decorators' => [
'inputGroupAddon',
],
],
'group' => ['type' => 'inputGroup'],
'label' => ['type' => 'controlLabel'],
'feedback' => ['type' => 'formControlFeedback'],
'help' => ['type' => 'helpBlock'],
'col' => ['type' => 'formGroupCol'],
'row' => ['type' => 'formGroup'],
];
/**
* {@inheritDoc}
*/
public function getDecoratorSpecification()
{
return $this->decoratorSpecification;
}
/**
* @param array $spec
* @return self
*/
public function setDecoratorSpecification(array $spec)
{
$this->decoratorSpecification = $spec;
return $this;
}
}
|
Java
|
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.magetab;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* A repository of controlled vocabulary terms. Must have a non-null, non-empty name
*/
public final class TermSource {
private String name;
private String file;
private String version;
/**
* Create new TermSource with given name.
* @param name the repository name; must not be blank or null
*/
public TermSource(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* Create new TermSource with given name, url and version.
* @param name the repository name
* @param file the url (called file in MAGE TAB terminology)
* @param version the version;
*/
public TermSource(String name, String file, String version) {
this(name);
this.file = file;
this.version = version;
}
/**
* @return the file
*/
public String getFile() {
return this.file;
}
/**
* @param file the file to set
*/
public void setFile(String file) {
this.file = file;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* @return the version
*/
public String getVersion() {
return this.version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TermSource)) {
return false;
}
if (obj == this) {
return true;
}
TermSource ts = (TermSource) obj;
return new EqualsBuilder().append(this.getName(), ts.getName()).append(this.getFile(), ts.getFile()).append(
this.getVersion(), ts.getVersion()).isEquals();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.getName()).append(this.getFile()).append(this.getVersion())
.toHashCode();
}
}
|
Java
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/engine/tonic/dart_dependency_catcher.h"
#include "sky/engine/tonic/dart_library_loader.h"
namespace blink {
DartDependencyCatcher::DartDependencyCatcher(DartLibraryLoader& loader)
: loader_(loader) {
loader_.set_dependency_catcher(this);
}
DartDependencyCatcher::~DartDependencyCatcher() {
loader_.set_dependency_catcher(nullptr);
}
void DartDependencyCatcher::AddDependency(DartDependency* dependency) {
dependencies_.add(dependency);
}
} // namespace blink
|
Java
|
/*============================================================================
WCSLIB 7.6 - an implementation of the FITS WCS standard.
Copyright (C) 1995-2021, Mark Calabretta
This file is part of WCSLIB.
WCSLIB is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
WCSLIB is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with WCSLIB. If not, see http://www.gnu.org/licenses.
Author: Mark Calabretta, Australia Telescope National Facility, CSIRO.
http://www.atnf.csiro.au/people/Mark.Calabretta
$Id: log.h,v 7.6 2021/04/13 12:57:01 mcalabre Exp $
*=============================================================================
*
* WCSLIB 7.6 - C routines that implement the FITS World Coordinate System
* (WCS) standard. Refer to the README file provided with WCSLIB for an
* overview of the library.
*
*
* Summary of the log routines
* ---------------------------
* Routines in this suite implement the part of the FITS World Coordinate
* System (WCS) standard that deals with logarithmic coordinates, as described
* in
*
* "Representations of world coordinates in FITS",
* Greisen, E.W., & Calabretta, M.R. 2002, A&A, 395, 1061 (WCS Paper I)
*
* "Representations of spectral coordinates in FITS",
* Greisen, E.W., Calabretta, M.R., Valdes, F.G., & Allen, S.L.
* 2006, A&A, 446, 747 (WCS Paper III)
*
* These routines define methods to be used for computing logarithmic world
* coordinates from intermediate world coordinates (a linear transformation of
* image pixel coordinates), and vice versa.
*
* logx2s() and logs2x() implement the WCS logarithmic coordinate
* transformations.
*
* Argument checking:
* ------------------
* The input log-coordinate values are only checked for values that would
* result in floating point exceptions and the same is true for the
* log-coordinate reference value.
*
* Accuracy:
* ---------
* No warranty is given for the accuracy of these routines (refer to the
* copyright notice); intending users must satisfy for themselves their
* adequacy for the intended purpose. However, closure effectively to within
* double precision rounding error was demonstrated by test routine tlog.c
* which accompanies this software.
*
*
* logx2s() - Transform to logarithmic coordinates
* -----------------------------------------------
* logx2s() transforms intermediate world coordinates to logarithmic
* coordinates.
*
* Given and returned:
* crval double Log-coordinate reference value (CRVALia).
*
* Given:
* nx int Vector length.
*
* sx int Vector stride.
*
* slogc int Vector stride.
*
* x const double[]
* Intermediate world coordinates, in SI units.
*
* Returned:
* logc double[] Logarithmic coordinates, in SI units.
*
* stat int[] Status return value status for each vector element:
* 0: Success.
*
* Function return value:
* int Status return value:
* 0: Success.
* 2: Invalid log-coordinate reference value.
*
*
* logs2x() - Transform logarithmic coordinates
* --------------------------------------------
* logs2x() transforms logarithmic world coordinates to intermediate world
* coordinates.
*
* Given and returned:
* crval double Log-coordinate reference value (CRVALia).
*
* Given:
* nlogc int Vector length.
*
* slogc int Vector stride.
*
* sx int Vector stride.
*
* logc const double[]
* Logarithmic coordinates, in SI units.
*
* Returned:
* x double[] Intermediate world coordinates, in SI units.
*
* stat int[] Status return value status for each vector element:
* 0: Success.
* 1: Invalid value of logc.
*
* Function return value:
* int Status return value:
* 0: Success.
* 2: Invalid log-coordinate reference value.
* 4: One or more of the world-coordinate values
* are incorrect, as indicated by the stat vector.
*
*
* Global variable: const char *log_errmsg[] - Status return messages
* ------------------------------------------------------------------
* Error messages to match the status value returned from each function.
*
*===========================================================================*/
#ifndef WCSLIB_LOG
#define WCSLIB_LOG
#ifdef __cplusplus
extern "C" {
#endif
extern const char *log_errmsg[];
enum log_errmsg_enum {
LOGERR_SUCCESS = 0, // Success.
LOGERR_NULL_POINTER = 1, // Null pointer passed.
LOGERR_BAD_LOG_REF_VAL = 2, // Invalid log-coordinate reference value.
LOGERR_BAD_X = 3, // One or more of the x coordinates were
// invalid.
LOGERR_BAD_WORLD = 4 // One or more of the world coordinates were
// invalid.
};
int logx2s(double crval, int nx, int sx, int slogc, const double x[],
double logc[], int stat[]);
int logs2x(double crval, int nlogc, int slogc, int sx, const double logc[],
double x[], int stat[]);
#ifdef __cplusplus
}
#endif
#endif // WCSLIB_LOG
|
Java
|
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package profiles
import (
"fmt"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
"v.io/x/lib/envvar"
)
// Target represents specification for the environment that the profile is
// to be built for. Targets include a version string to allow for upgrades and
// for the simultaneous existence of incompatible versions.
//
// Target and Environment implement flag.Getter so that they may be used
// with the flag package. Two flags are required, one to specify the target
// in <arch>-<os>@<version> format and a second to specify environment
// variables either as comma separated values or as repeated arguments.
type Target struct {
arch, opsys, version string
// The environment as specified on the command line
commandLineEnv Environment
// The environment as modified by a profile implementation
Env Environment
InstallationDir string // where this target is installed.
UpdateTime time.Time
isSet bool
}
// Arch returns the archiecture of this target.
func (pt *Target) Arch() string {
return pt.arch
}
// OS returns the operating system of this target.
func (pt *Target) OS() string {
return pt.opsys
}
// Version returns the version of this target.
func (pt *Target) Version() string {
return pt.version
}
// SetVersion sets the version for the target.
func (pt *Target) SetVersion(v string) {
pt.version = v
}
// CommandLineEnv returns the environment variables set on the
// command line for this target.
func (pt Target) CommandLineEnv() Environment {
r := Environment{Vars: make([]string, len(pt.commandLineEnv.Vars))}
copy(r.Vars, pt.commandLineEnv.Vars)
return r
}
// UseCommandLineEnv copies the command line supplied environment variables
// into the mutable environment of the Target. It should be called as soon
// as all command line parsing has been completed and before the target is
// otherwise used.
func (pt *Target) UseCommandLineEnv() {
pt.Env = pt.CommandLineEnv()
}
// TargetSpecificDirname returns a directory name that is specific
// to that target taking account the architecture, operating system and
// command line environment variables, if relevant, into account (e.g
// GOARM={5,6,7}).
func (pt *Target) TargetSpecificDirname() string {
env := envvar.SliceToMap(pt.commandLineEnv.Vars)
dir := pt.arch + "_" + pt.opsys
if pt.arch == "arm" {
if armv, present := env["GOARM"]; present {
dir += "_armv" + armv
}
}
return dir
}
type Environment struct {
Vars []string `xml:"var"`
}
// NewTarget creates a new target using the supplied target and environment
// parameters specified in command line format.
func NewTarget(target string, env ...string) (Target, error) {
t := &Target{}
err := t.Set(target)
for _, e := range env {
t.commandLineEnv.Set(e)
}
return *t, err
}
// Match returns true if pt and pt2 meet the following criteria in the
// order they are listed:
// - if the Arch and OS fields are exactly the same
// - if pt has a non-zero length Version field, then it must be
// the same as that in pt2
// Match is used by the various methods and functions in this package
// when looking up Targets unless otherwise specified.
func (pt Target) Match(pt2 *Target) bool {
if pt.arch != pt2.arch || pt.opsys != pt2.opsys {
return false
}
if (len(pt.version) > 0) && (pt.version != pt2.version) {
return false
}
return true
}
// Less returns true if pt2 is considered less than pt. The ordering
// takes into account only the architecture, operating system and version of
// the target. The architecture and operating system are ordered
// lexicographically in ascending order, then the version is ordered but in
// descending lexicographic order except that the empty string is considered
// the 'highest' value.
// Thus, (targets in <arch>-<os>[@<version>] format), are all true:
// b-c < c-c
// b-c@3 < b-c@2
func (pt *Target) Less(pt2 *Target) bool {
switch {
case pt.arch != pt2.arch:
return pt.arch < pt2.arch
case pt.opsys != pt2.opsys:
return pt.opsys < pt2.opsys
case len(pt.version) == 0 && len(pt2.version) > 0:
return true
case len(pt.version) > 0 && len(pt2.version) == 0:
return false
case pt.version != pt2.version:
return compareVersions(pt.version, pt2.version) > 0
default:
return false
}
}
// CrossCompiling returns true if the target differs from that of the runtime.
func (pt Target) CrossCompiling() bool {
arch, _ := goarch()
return (pt.arch != arch) || (pt.opsys != runtime.GOOS)
}
// Usage returns the usage string for Target.
func (pt *Target) Usage() string {
return "specifies a profile target in the following form: <arch>-<os>[@<version>]"
}
// Set implements flag.Value.
func (t *Target) Set(val string) error {
index := strings.IndexByte(val, '@')
if index > -1 {
t.version = val[index+1:]
val = val[:index]
}
parts := strings.Split(val, "-")
if len(parts) != 2 || (len(parts[0]) == 0 || len(parts[1]) == 0) {
return fmt.Errorf("%q doesn't look like <arch>-<os>[@<version>]", val)
}
t.arch = parts[0]
t.opsys = parts[1]
t.isSet = true
return nil
}
// Get implements flag.Getter.
func (t Target) Get() interface{} {
if !t.isSet {
// Default value.
arch, isSet := goarch()
return Target{
isSet: isSet,
arch: arch,
opsys: runtime.GOOS,
version: t.version,
Env: t.Env,
}
}
return t
}
func goarch() (string, bool) {
// GOARCH may be set to 386 for binaries compiled for amd64 - i.e.
// the same binary can be run in these two modes, but the compiled
// in value of runtime.GOARCH will only ever be the value that it
// was compiled with.
if a := os.Getenv("GOARCH"); len(a) > 0 {
return a, true
}
return runtime.GOARCH, false
}
// DefaultTarget returns a default value for a Target. Use this function to
// initialize Targets that are expected to set from the command line via
// the flags package.
func DefaultTarget() Target {
arch, isSet := goarch()
return Target{
isSet: isSet,
arch: arch,
opsys: runtime.GOOS,
}
}
// NativeTarget returns a value for Target for the host on which it is running.
// Use this function for Target values that are passed into other functions
// and libraries where a native target is specifically required.
func NativeTarget() Target {
arch, _ := goarch()
return Target{
isSet: true,
arch: arch,
opsys: runtime.GOOS,
}
}
// IsSet returns true if this target has had its value set.
func (pt Target) IsSet() bool {
return pt.isSet
}
// String implements flag.Getter.
func (pt Target) String() string {
v := pt.Get().(Target)
return fmt.Sprintf("%v-%v@%s", v.arch, v.opsys, v.version)
}
// Targets is a list of *Target's ordered by architecture,
// operating system and descending versions.
type Targets []*Target
// Implements sort.Len
func (tl Targets) Len() int {
return len(tl)
}
// Implements sort.Less
func (tl Targets) Less(i, j int) bool {
return tl[i].Less(tl[j])
}
// Implements sort.Swap
func (tl Targets) Swap(i, j int) {
tl[i], tl[j] = tl[i], tl[j]
}
func (tl Targets) Sort() {
sort.Sort(tl)
}
// DebugString returns a pretty-printed representation of pt.
func (pt Target) DebugString() string {
v := pt.Get().(Target)
return fmt.Sprintf("%v-%v@%s dir:%s --env=%s envvars:%v", v.arch, v.opsys, v.version, pt.InstallationDir, strings.Join(pt.commandLineEnv.Vars, ","), pt.Env.Vars)
}
// Set implements flag.Getter.
func (e *Environment) Get() interface{} {
return *e
}
// Set implements flag.Value.
func (e *Environment) Set(val string) error {
for _, v := range strings.Split(val, ",") {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 || (len(parts[0]) == 0) {
return fmt.Errorf("%q doesn't look like var=[val]", v)
}
e.Vars = append(e.Vars, v)
}
return nil
}
// String implements flag.Getter.
func (e Environment) String() string {
return strings.Join(e.Vars, ",")
}
// Usage returns the usage string for Environment.
func (e Environment) Usage() string {
return "specify an environment variable in the form: <var>=[<val>],..."
}
// InsertTarget inserts the given target into Targets if it's not
// already there and returns a new slice.
func InsertTarget(targets Targets, target *Target) Targets {
for i, t := range targets {
if !t.Less(target) {
targets = append(targets, nil)
copy(targets[i+1:], targets[i:])
targets[i] = target
return targets
}
}
return append(targets, target)
}
// RemoveTarget removes the given target from a slice of Target and returns
// a slice.
func RemoveTarget(targets Targets, target *Target) Targets {
for i, t := range targets {
if target.Match(t) {
targets, targets[len(targets)-1] = append(targets[:i], targets[i+1:]...), nil
return targets
}
}
return targets
}
// FindTarget returns the first target that matches the requested target from
// the slice of Targets. If target has not been explicitly set and there is
// only a single target available in targets then that one target is considered
// as matching.
func FindTarget(targets Targets, target *Target) *Target {
for _, t := range targets {
if target.Match(t) {
tmp := *t
return &tmp
}
}
return nil
}
// FindTargetWithDefault is like FindTarget except that if there is only one
// target in the slice and the requested target has not been explicitly set
// (IsSet is false) then that one target is returned by default.
func FindTargetWithDefault(targets Targets, target *Target) *Target {
if len(targets) == 1 && !target.IsSet() {
tmp := *targets[0]
return &tmp
}
return FindTarget(targets, target)
}
// compareVersions compares version numbers. It handles cases like:
// compareVersions("2", "11") => 1
// compareVersions("1.1", "1.2") => 1
// compareVersions("1.2", "1.2.1") => 1
// compareVersions("1.2.1.b", "1.2.1.c") => 1
func compareVersions(v1, v2 string) int {
v1parts := strings.Split(v1, ".")
v2parts := strings.Split(v2, ".")
maxLen := len(v1parts)
if len(v2parts) > maxLen {
maxLen = len(v2parts)
}
for i := 0; i < maxLen; i++ {
if i == len(v1parts) {
// v2 has more parts than v1, so v2 > v1.
return -1
}
if i == len(v2parts) {
// v1 has more parts than v2, so v1 > v2.
return 1
}
mustCompareStrings := false
v1part, err := strconv.Atoi(v1parts[i])
if err != nil {
mustCompareStrings = true
}
v2part, err := strconv.Atoi(v2parts[i])
if err != nil {
mustCompareStrings = true
}
if mustCompareStrings {
return strings.Compare(v1parts[i], v2parts[i])
}
if v1part > v2part {
return 1
}
if v2part > v1part {
return -1
}
}
return 0
}
|
Java
|
<?php
namespace Avaliacao\Controller;
use Avaliacao\Entity\Debito;
use Avaliacao\Entity\Veiculo;
use Avaliacao\Service\VeiculoService;
use Zend\Hydrator\ClassMethods;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
/**
* Class ApiVeiculoController
* @package Avaliacao\Controller
*/
class ApiVeiculoController extends AbstractRestfulController
{
/**
* @var VeiculoService
*/
private $veiculoService;
public function __construct(VeiculoService $veiculoService)
{
$this->veiculoService = $veiculoService;
}
public function update($id, $data)
{
$veiculo = $this->veiculoService->findOneBy(Veiculo::class, ['id' => $id]);
/** @var Veiculo $veiculo */
if (! $veiculo ) {
return new JsonModel(['status' => 'erro', 'menssage'=>'Veiculo não localizado']);
}
$veiculo->hydrate($data['data']);
$veiculo = $this->veiculoService->update($veiculo);
// \Zend\Debug\Debug::dump($veiculo->getIdBot());exit;
$hydrator = new ClassMethods();
$data = $hydrator->extract($veiculo);
return new JsonModel(['status' => 'ok', 'data' => $data]);
}
}
|
Java
|
{% extends "layout.html" %}
{% block main %}
<input type="hidden" id="surveyRedirectURL" value="{{redirect_url}}" />
<div class="modal fade" id="confirmIdentityModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="modal-header-title">{{_("Identity verification")}}</div>
</div>
<div class="modal-body">
<div class="body-content">
<div>{{_("I confirm that I am a participant in the IRONMAN Registry Study and am completing this questionnaire myself.")}}</div>
</div>
<div id="confirmationErrorMessage" class="error-message"></div>
</div>
<div class="modal-footer">
<button id="btnConfirmIdentity" class="btn btn-default">{{_("Yes")}}</button>
<a href="{{url_for('eproms.home')}}" class="btn btn-default">{{_("No")}}</a>
</div>
</div>
</div>
</div>
{% endblock %}
{%- block additional_scripts %}<script src="{{ url_for('static', filename='js/flask_user/ConfirmIdentity.js') }}"></script>{% endblock -%}
{%- from "flask_user/_macros.html" import footer -%}
{%- block footer %}{% endblock -%}
|
Java
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreArnold/ParameterAlgo.h"
#include "IECoreImage/DisplayDriver.h"
#include "IECore/BoxAlgo.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "ai_drivers.h"
#include "ai_metadata.h"
#include "ai_plugins.h"
#include "ai_universe.h"
#include "ai_version.h"
#include <stdio.h>
using namespace Imath;
using namespace IECore;
using namespace IECoreImage;
using namespace IECoreArnold;
namespace
{
const AtString g_driverTypeArnoldString("driverType");
const AtString g_pixelAspectRatioArnoldString("pixel_aspect_ratio");
// Stores a Cortex DisplayDriver and the parameters
// used to create it. This forms the private data
// accessed via AiNodeGetLocalData.
struct LocalData
{
LocalData()
: numOutputs( 0 )
{
}
DisplayDriverPtr displayDriver;
ConstCompoundDataPtr displayDriverParameters;
int numOutputs;
void imageClose()
{
if( !displayDriver )
{
return;
}
try
{
displayDriver->imageClose();
}
catch( const std::exception &e )
{
// We have to catch and report exceptions because letting them out into pure c land
// just causes aborts.
msg( Msg::Error, "ieOutputDriver:driverClose", e.what() );
}
displayDriver = nullptr;
}
};
void driverParameters( AtList *params, AtNodeEntry *nentry )
{
AiParameterStr( g_driverTypeArnoldString, "" );
// we need to specify this metadata to keep MtoA happy.
AiMetaDataSetStr( nentry, nullptr, "maya.attr_prefix", "" );
AiMetaDataSetStr( nentry, nullptr, "maya.translator", "ie" );
}
void driverInitialize( AtNode *node )
{
AiDriverInitialize( node, true );
AiNodeSetLocalData( node, new LocalData );
}
void driverUpdate( AtNode *node )
{
}
bool driverSupportsPixelType( const AtNode *node, uint8_t pixelType )
{
switch( pixelType )
{
case AI_TYPE_RGB :
case AI_TYPE_RGBA :
case AI_TYPE_FLOAT :
case AI_TYPE_VECTOR :
return true;
default:
return false;
}
}
const char **driverExtension()
{
return nullptr;
}
void driverOpen( AtNode *node, struct AtOutputIterator *iterator, AtBBox2 displayWindow, AtBBox2 dataWindow, int bucketSize )
{
LocalData *localData = (LocalData *)AiNodeGetLocalData( node );
localData->numOutputs = 0;
std::vector<std::string> channelNames;
CompoundDataPtr parameters = new CompoundData();
ParameterAlgo::getParameters( node, parameters->writable() );
#if ARNOLD_VERSION_NUM >= 70000
AtString name;
#else
const char *name;
#endif
int pixelType = 0;
while( AiOutputIteratorGetNext( iterator, &name, &pixelType, nullptr ) )
{
std::string namePrefix;
if( strcmp( name, "RGB" ) && strcmp( name, "RGBA" ) )
{
namePrefix = std::string( name ) + ".";
}
const StringData *layerName = parameters->member< StringData >( "layerName" );
if( layerName && layerName->readable() != "" )
{
namePrefix = layerName->readable() + ".";
}
switch( pixelType )
{
case AI_TYPE_RGB :
case AI_TYPE_VECTOR :
channelNames.push_back( namePrefix + "R" );
channelNames.push_back( namePrefix + "G" );
channelNames.push_back( namePrefix + "B" );
break;
case AI_TYPE_RGBA :
channelNames.push_back( namePrefix + "R" );
channelNames.push_back( namePrefix + "G" );
channelNames.push_back( namePrefix + "B" );
channelNames.push_back( namePrefix + "A" );
break;
case AI_TYPE_FLOAT :
// no need for prefix because it's not a compound type
#if ARNOLD_VERSION_NUM >= 70000
channelNames.push_back( name.c_str() );
#else
channelNames.push_back( name );
#endif
break;
}
localData->numOutputs += 1;
}
/// \todo Make Convert.h
Box2i cortexDisplayWindow(
V2i( displayWindow.minx, displayWindow.miny ),
V2i( displayWindow.maxx, displayWindow.maxy )
);
Box2i cortexDataWindow(
V2i( dataWindow.minx, dataWindow.miny ),
V2i( dataWindow.maxx, dataWindow.maxy )
);
// IECore::DisplayDriver lacks any official mechanism for passing
// the pixel aspect ratio, so for now we just pass it via the
// parameters. We should probably move GafferImage::Format to
// IECoreImage::Format and then use that in place of the display
// window.
parameters->writable()["pixelAspect"] = new FloatData(
AiNodeGetFlt( AiUniverseGetOptions( AiNodeGetUniverse( node ) ), g_pixelAspectRatioArnoldString )
);
const std::string driverType = AiNodeGetStr( node, g_driverTypeArnoldString ).c_str();
// We reuse the previous driver if we can - this allows us to use
// the same driver for every stage of a progressive render.
if( localData->displayDriver )
{
if(
localData->displayDriver->typeName() == driverType &&
localData->displayDriver->displayWindow() == cortexDisplayWindow &&
localData->displayDriver->dataWindow() == cortexDataWindow &&
localData->displayDriver->channelNames() == channelNames &&
localData->displayDriverParameters->isEqualTo( parameters.get() )
)
{
// Can reuse
return;
}
else
{
// Can't reuse, so must close before making a new one.
localData->imageClose();
}
}
// Couldn't reuse a driver, so create one from scratch.
try
{
localData->displayDriver = IECoreImage::DisplayDriver::create( driverType, cortexDisplayWindow, cortexDataWindow, channelNames, parameters );
localData->displayDriverParameters = parameters;
}
catch( const std::exception &e )
{
// We have to catch and report exceptions because letting them out into pure c land
// just causes aborts.
msg( Msg::Error, "ieOutputDriver:driverOpen", e.what() );
}
}
bool driverNeedsBucket( AtNode *node, int x, int y, int sx, int sy, uint16_t tId )
{
return true;
}
void driverPrepareBucket( AtNode *node, int x, int y, int sx, int sy, uint16_t tId )
{
}
void driverProcessBucket( AtNode *node, struct AtOutputIterator *iterator, struct AtAOVSampleIterator *sample_iterator, int x, int y, int sx, int sy, uint16_t tId )
{
}
void driverWriteBucket( AtNode *node, struct AtOutputIterator *iterator, struct AtAOVSampleIterator *sampleIterator, int x, int y, int sx, int sy )
{
LocalData *localData = (LocalData *)AiNodeGetLocalData( node );
if( !localData->displayDriver )
{
return;
}
const int numOutputChannels = localData->displayDriver->channelNames().size();
const float *imageData;
std::vector<float> interleavedData;
if( localData->numOutputs == 1 )
{
// Data already has the layout we need.
const void *bucketData;
AiOutputIteratorGetNext( iterator, nullptr, nullptr, &bucketData );
imageData = (float *)bucketData;
}
else
{
// We need to interleave multiple outputs
// into a single block for the display driver.
interleavedData.resize( sx * sy * numOutputChannels );
int pixelType = 0;
const void *bucketData;
int outChannelOffset = 0;
while( AiOutputIteratorGetNext( iterator, nullptr, &pixelType, &bucketData ) )
{
int numChannels = 0;
switch( pixelType )
{
case AI_TYPE_RGB :
case AI_TYPE_VECTOR :
numChannels = 3;
break;
case AI_TYPE_RGBA :
numChannels = 4;
break;
case AI_TYPE_FLOAT :
numChannels = 1;
break;
}
for( int c = 0; c < numChannels; c++ )
{
float *in = (float *)(bucketData) + c;
float *out = &(interleavedData[0]) + outChannelOffset;
for( int j = 0; j < sy; j++ )
{
for( int i = 0; i < sx; i++ )
{
*out = *in;
out += numOutputChannels;
in += numChannels;
}
}
outChannelOffset += 1;
}
}
imageData = &interleavedData[0];
}
Box2i bucketBox(
V2i( x, y ),
V2i( x + sx - 1, y + sy - 1 )
);
try
{
localData->displayDriver->imageData( bucketBox, imageData, sx * sy * numOutputChannels );
}
catch( const std::exception &e )
{
// we have to catch and report exceptions because letting them out into pure c land
// just causes aborts.
msg( Msg::Error, "ieOutputDriver:driverWriteBucket", e.what() );
}
}
void driverClose( AtNode *node, struct AtOutputIterator *iterator )
{
LocalData *localData = (LocalData *)AiNodeGetLocalData( node );
// We only close the display immediately if it doesn't accept
// repeated data (progressive renders). This is so we can reuse it in
// driverOpen if it appears that a progressive render is taking place.
if( localData->displayDriver && !localData->displayDriver->acceptsRepeatedData() )
{
localData->imageClose();
}
}
void driverFinish( AtNode *node )
{
LocalData *localData = (LocalData *)AiNodeGetLocalData( node );
// Perform any pending close we may have deferred in driverClose().
localData->imageClose();
delete localData;
}
} // namespace
AI_EXPORT_LIB bool NodeLoader( int i, AtNodeLib *node )
{
if( i==0 )
{
static AtCommonMethods commonMethods = {
nullptr, // Whole plugin init
nullptr, // Whole plugin cleanup
driverParameters,
driverInitialize,
driverUpdate,
driverFinish
};
static AtDriverNodeMethods driverMethods = {
driverSupportsPixelType,
driverExtension,
driverOpen,
driverNeedsBucket,
driverPrepareBucket,
driverProcessBucket,
driverWriteBucket,
driverClose
};
static AtNodeMethods nodeMethods = {
&commonMethods,
&driverMethods
};
node->node_type = AI_NODE_DRIVER;
node->output_type = AI_TYPE_NONE;
node->name = "ieDisplay";
node->methods = &nodeMethods;
sprintf( node->version, AI_VERSION );
return true;
}
return false;
}
|
Java
|
extern zend_class_entry *ice_mvc_service_ce;
ZEPHIR_INIT_CLASS(Ice_Mvc_Service);
PHP_METHOD(Ice_Mvc_Service, setModel);
PHP_METHOD(Ice_Mvc_Service, getModel);
PHP_METHOD(Ice_Mvc_Service, __call);
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service_setmodel, 0, 0, 1)
ZEND_ARG_INFO(0, model)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service_getmodel, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service___call, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, method, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, method)
#endif
ZEND_ARG_INFO(0, arguments)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(ice_mvc_service_method_entry) {
PHP_ME(Ice_Mvc_Service, setModel, arginfo_ice_mvc_service_setmodel, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Mvc_Service, getModel, arginfo_ice_mvc_service_getmodel, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Mvc_Service, __call, arginfo_ice_mvc_service___call, ZEND_ACC_PUBLIC)
PHP_FE_END
};
|
Java
|
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande 'scripting alerte info'."""
from primaires.interpreteur.masque.parametre import Parametre
from primaires.format.fonctions import echapper_accolades
from primaires.format.date import get_date
class PrmInfo(Parametre):
"""Commande 'scripting alerte info'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, "info", "info")
self.schema = "<nombre>"
self.aide_courte = "affiche des informations sur l'alerte"
self.aide_longue = \
"Affiche des informations sur l'alerte permettant de la corriger."
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
nombre = dic_masques["nombre"].nombre
try:
alerte = type(self).importeur.scripting.alertes[nombre]
except KeyError:
personnage << "|err|Ce numéro d'alerte est invalide.|ff|"
else:
msg = "Informations sur l'alerte {} :".format(alerte.no)
msg += "\n S'est produit sur {} {}".format(alerte.type,
alerte.objet) + " " + get_date(alerte.date.timetuple())
msg += "\n Evenement {}, test {}, ligne {}".format(
alerte.evenement, echapper_accolades(alerte.test),
alerte.no_ligne)
msg += "\n {}\n".format(echapper_accolades(alerte.ligne))
msg += "\n Message d'erreur : |err|{}|ff|".format(
echapper_accolades(alerte.message))
if personnage.nom_groupe == "administrateur":
msg += "\n Traceback Python :\n {}".format(
echapper_accolades(alerte.traceback))
personnage << msg
|
Java
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def helloworld():
"""
Hello world routine !
"""
print("Hello world!")
|
Java
|
#include "allocv/al_VideoCapture.hpp"
/*
From opencv2/highgui/highgui.hpp:
class CV_EXPORTS_W VideoCapture
{
public:
CV_WRAP VideoCapture();
CV_WRAP VideoCapture(const string& filename);
CV_WRAP VideoCapture(int device);
virtual ~VideoCapture();
CV_WRAP virtual bool open(const string& filename);
CV_WRAP virtual bool open(int device);
CV_WRAP virtual bool isOpened() const;
CV_WRAP virtual void release();
// Grabs the next frame from video file or capturing device.
CV_WRAP virtual bool grab();
// Decodes and returns the grabbed video frame.
CV_WRAP virtual bool retrieve(CV_OUT Mat& image, int channel=0);
// Alias of read()
virtual VideoCapture& operator >> (CV_OUT Mat& image);
// Grabs, decodes and returns the next video frame.
CV_WRAP virtual bool read(CV_OUT Mat& image);
CV_WRAP virtual bool set(int propId, double value);
CV_WRAP virtual double get(int propId);
protected:
Ptr<CvCapture> cap;
};
*/
namespace al{
VideoCapture::VideoCapture()
: mFPS(1.), mRate(1.), mBadFrame(-1), mIsFile(false), mValid(true)
{}
VideoCapture::~VideoCapture(){
mValid = false;
cvVideoCapture.release();
}
bool VideoCapture::open(const std::string& filename){
if(cvVideoCapture.open(filename)){
mIsFile = true;
mFPS = get(CV_CAP_PROP_FPS);
return true;
}
return false;
}
bool VideoCapture::open(int device){
if(cvVideoCapture.open(device)){
mIsFile = false;
mFPS = get(CV_CAP_PROP_FPS);
if(mFPS == 0.) mFPS = 30.;
return true;
}
return false;
}
void VideoCapture::release(){
cvVideoCapture.release();
}
bool VideoCapture::grab(){
bool didGrab = cvVideoCapture.grab();
// Attempt to advance past bad frames in video files
if(isFile()){
if(!didGrab){
if(mBadFrame == -1){ // last frame wasn't bad
mBadFrame = posFrames()+1;
}
printf("VideoCapture::grab: bad frame %g\n", mBadFrame);
if(mBadFrame < numFrames()){
posFrames(mBadFrame);
++mBadFrame;
}
}
else{
mBadFrame = -1;
}
}
return didGrab;
}
bool VideoCapture::retrieve(cv::Mat& dst, int chan){
return cvVideoCapture.retrieve(dst, chan);
}
bool VideoCapture::retrieve(int chan){
return cvVideoCapture.retrieve(cvFrame, chan);
}
bool VideoCapture::retrieve(Array& dst, int chan, int copyPolicy){
bool res = retrieve(chan);
fromCV(dst, cvFrame, copyPolicy);
return res;
}
bool VideoCapture::retrieveFlip(Array& dst, int chan){
return retrieve(dst, chan, -1);
}
bool VideoCapture::read(Array& dst, int copyPolicy){
bool res = cvVideoCapture.read(cvFrame);
fromCV(dst, cvFrame, copyPolicy);
return res;
}
bool VideoCapture::set(int cvCapProp, double val){
return cvVideoCapture.set(cvCapProp,val);
}
VideoCapture& VideoCapture::width(double pixels){
set(CV_CAP_PROP_FRAME_WIDTH, pixels);
return *this;
}
VideoCapture& VideoCapture::height(double pixels){
set(CV_CAP_PROP_FRAME_HEIGHT, pixels);
return *this;
}
VideoCapture& VideoCapture::resize(double w, double h){
return width(w).height(h);
}
VideoCapture& VideoCapture::posMsec(double msec){
set(CV_CAP_PROP_POS_MSEC, msec);
return *this;
}
VideoCapture& VideoCapture::posFrames(double frame){
set(CV_CAP_PROP_POS_FRAMES, frame);
return *this;
}
VideoCapture& VideoCapture::posFrac(double frac){
//set(CV_CAP_PROP_POS_AVI_RATIO, frac); // broken for many file types
posFrames(frac*numFrames());
return *this;
}
VideoCapture& VideoCapture::fps(double val){
mFPS = val;
return *this;
}
VideoCapture& VideoCapture::rate(double fpsMul){
mRate = fpsMul;
return *this;
}
bool VideoCapture::isOpened() const {
return cvVideoCapture.isOpened();
}
double VideoCapture::get(int cvCapProp) const {
return cvVideoCapture.get(cvCapProp);
}
double VideoCapture::fps() const {
return mFPS;
}
double VideoCapture::numFrames() const {
return get(CV_CAP_PROP_FRAME_COUNT);
}
double VideoCapture::rate() const {
return mRate;
}
double VideoCapture::width() const {
return get(CV_CAP_PROP_FRAME_WIDTH);
}
double VideoCapture::height() const {
return get(CV_CAP_PROP_FRAME_HEIGHT);
}
double VideoCapture::aspect() const {
double w = width();
double h = height();
return (h!=0. && w!=0.) ? w/h : 1.;
}
bool VideoCapture::rgb() const {
return get(CV_CAP_PROP_CONVERT_RGB);
}
int VideoCapture::fourcc() const {
return int(get(CV_CAP_PROP_FOURCC));
}
std::string VideoCapture::fourccString() const {
union{ int i; char c[4]; } x = { fourcc() };
return std::string(x.c, 4);
}
double VideoCapture::posMsec() const {
return get(CV_CAP_PROP_POS_MSEC);
}
double VideoCapture::posFrames() const {
return get(CV_CAP_PROP_POS_FRAMES);
}
double VideoCapture::posFrac() const {
//return get(CV_CAP_PROP_POS_AVI_RATIO); // broken for many file types
return double(posFrames())/numFrames();
}
bool VideoCapture::loop(double minFrame, double maxFrame){
double Nf = numFrames();
if(maxFrame < 0) maxFrame += Nf + 1.;
else if(maxFrame > Nf) maxFrame = Nf;
double pos = posFrames();
if(pos >= maxFrame){
posFrames(minFrame);
return true;
}
return false;
}
bool VideoCapture::isFile() const {
return mIsFile;
}
void VideoCapture::print(FILE * fp){
fprintf(fp, "%g x %g %s %s, %g fps",
width(), height(), rgb()?"RGB":"BGR", fourccString().c_str(), fps());
if(isFile()){
fprintf(fp, ", %g frames (%g sec)", numFrames(), numFrames()/fps());
}
fprintf(fp, "\n");
}
VideoCaptureHandler::VideoThreadFunction::VideoThreadFunction()
: videoCapture(NULL), handler(NULL), streamIdx(-1)
{}
VideoCaptureHandler::VideoThreadFunction::~VideoThreadFunction()
{
videoCapture = NULL;
}
void VideoCaptureHandler::VideoThreadFunction::operator()(){
//printf("VideoThreadFunc called\n");
if(NULL != videoCapture && videoCapture->mValid && videoCapture->cvVideoCapture.isOpened()){
handler->onPregrab(*videoCapture, streamIdx);
if(videoCapture->grab()){
handler->onVideo(*videoCapture, streamIdx);
double fps = videoCapture->fps() * videoCapture->rate();
handler->mWorkThreads[streamIdx].thread.period(1./fps);
}
}
}
VideoCaptureHandler::WorkThread::~WorkThread(){
stop();
}
void VideoCaptureHandler::WorkThread::start(){
//printf("WorkThread::start(): %p %p\n", func.videoCapture, func.handler);
thread.start(func);
}
void VideoCaptureHandler::WorkThread::stop(){
thread.stop();
}
VideoCaptureHandler::VideoCaptureHandler(int numStreams){
numVideoStreams(numStreams);
}
VideoCaptureHandler::~VideoCaptureHandler(){
stopVideo();
}
VideoCaptureHandler& VideoCaptureHandler::numVideoStreams(int num){
mWorkThreads.resize(num);
return *this;
}
int VideoCaptureHandler::numVideoStreams() const {
return int(mWorkThreads.size());
}
VideoCaptureHandler& VideoCaptureHandler::attach(VideoCapture& vid, int streamIdx){
if(streamIdx>=0 && streamIdx<numVideoStreams()){
WorkThread& t = mWorkThreads[streamIdx];
t.func.handler = this;
t.func.videoCapture = &vid;
t.func.streamIdx = streamIdx;
}
return *this;
}
void VideoCaptureHandler::startVideo(){
for(
WorkThreads::iterator it = mWorkThreads.begin();
it != mWorkThreads.end();
++it
){
(*it).start();
}
}
void VideoCaptureHandler::stopVideo(){
for(
WorkThreads::iterator it = mWorkThreads.begin();
it != mWorkThreads.end();
++it
){
(*it).stop();
}
}
} // al::
|
Java
|
package com.github.dandelion.gua.core.field;
public enum EventTrackingField implements AnalyticsField, AnalyticsCreateField {
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventCategory,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventAction,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventLabel,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.INTEGER) eventValue,
}
|
Java
|
/*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.wustl.cab2b.server.analyticalservice;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.common.analyticalservice.ServiceDetailsInterface;
import edu.wustl.cab2b.common.exception.RuntimeException;
/**
* This is a singleton class which parses the EntityToAnalyticalServiceMapping.xml file and stores the mapping information into an internal map.
* This class provieds the methods to get the service interface and the service invoker interface.
* @author chetan_patil
*/
public class EntityToAnalyticalServiceMapper {
/**
* Self reference
*/
private static EntityToAnalyticalServiceMapper entityServiceMapper = null;
/**
* Map to store the entity to service mapping
*/
private Map<String, List<String>> entityServiceNameMap = new HashMap<String, List<String>>();
/**
* Map to store the service to method mapping
*/
private Map<String, List<String>> serviceNameDetailClassNameMap = new HashMap<String, List<String>>();
/**
* Map to store the service detail class and the corresponding service invoker class.
*/
private Map<String, String> serviceDetailInvokerMap = new HashMap<String, String>();
/**
* Name of the Entity Service Mapper file
*/
private static final String ENTITY_SERVICE_MAPPER_FILENAME = "EntityToAnalyticalServiceMapping.xml";
/**
* Entity tag
*/
private static final String ENTITY = "entity";
/**
* Service tag
*/
private static final String SERVICE = "service";
/**
* Method tag
*/
private static final String METHOD = "method";
/**
* Name attribute
*/
private static final String ATTRIBUTE_NAME = "name";
/**
* Service Detail Class attribute
*/
private static final String ATTRIBUTE_SERVICE_DETAIL_CLASS = "serviceDetailClass";
/**
* Service Invoker Class attribute
*/
private static final String ATTRIBUTE_SERVICE_INVOKER_CLASS = "serviceInvokerClass";
/**
* Service name attribute
*/
private static final String ATTRIBUTE_SERVICE_NAME = "serviceName";
/**
* Private constructor
*/
private EntityToAnalyticalServiceMapper() {
parseEntityServiceMapperXMLFile();
}
/**
* This method returns an instance of this class
* @return an instance of this class
*/
public static synchronized EntityToAnalyticalServiceMapper getInstance() {
if (entityServiceMapper == null) {
entityServiceMapper = new EntityToAnalyticalServiceMapper();
}
return entityServiceMapper;
}
/**
* This method parses the EntityServiceMapper.XML file and stores the parsed data into an internally maintained Maps.
*/
private void parseEntityServiceMapperXMLFile() {
//Read the xml file
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(
ENTITY_SERVICE_MAPPER_FILENAME);
if (inputStream == null) {
throw new RuntimeException("File not found: " + ENTITY_SERVICE_MAPPER_FILENAME);
}
//Parse xml into the Document
Document document = null;
try {
document = new SAXReader().read(inputStream);
} catch (DocumentException e) {
throw new RuntimeException("Unable to parse XML file: " + ENTITY_SERVICE_MAPPER_FILENAME, e);
}
//Traverse and fetch the data from the Document
Element entityServiceMapperElement = document.getRootElement();
if (entityServiceMapperElement != null) {
List<Element> serviceElementList = entityServiceMapperElement.elements(SERVICE);
if (serviceElementList == null || serviceElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Service entries not found.");
}
registerServiceElements(serviceElementList);
List<Element> entityElementList = entityServiceMapperElement.elements(ENTITY);
if (entityElementList == null || entityElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Entity entries not found.");
}
registerEntityElements(entityElementList);
} else {
throw new RuntimeException("Invalid XML file: Root element not found.");
}
}
/**
* This method stores the data of all the service tags into serviceMethodMap
* @param serviceElementList the root element of the XML document
*/
private void registerServiceElements(List<Element> serviceElementList) {
for (Element serviceElement : serviceElementList) {
List<String> serviceDetailClassList = new ArrayList<String>();
List<Element> methodElementList = serviceElement.elements(METHOD);
for (Element methodElement : methodElementList) {
String serviceDetailClassName = methodElement.attributeValue(ATTRIBUTE_SERVICE_DETAIL_CLASS);
String serviceInvokerClassName = methodElement.attributeValue(ATTRIBUTE_SERVICE_INVOKER_CLASS);
if (!serviceDetailClassList.contains(serviceDetailClassName)) {
serviceDetailClassList.add(serviceDetailClassName);
}
if (serviceDetailInvokerMap.get(serviceDetailClassName) == null) {
serviceDetailInvokerMap.put(serviceDetailClassName, serviceInvokerClassName);
}
}
String serviceName = serviceElement.attributeValue(ATTRIBUTE_NAME);
if (serviceNameDetailClassNameMap.get(serviceName) == null) {
serviceNameDetailClassNameMap.put(serviceName, serviceDetailClassList);
}
}
}
/**
* This method stores the data of all the entity tags into entityServiceMap
* @param entityElementList the root element of the XML document
*/
private void registerEntityElements(List<Element> entityElementList) {
for (Element entityElement : entityElementList) {
String entityName = entityElement.attributeValue(ATTRIBUTE_NAME);
String serviceName = entityElement.attributeValue(ATTRIBUTE_SERVICE_NAME);
List<String> serviceList = entityServiceNameMap.get(entityName);
if (serviceList == null) {
serviceList = new ArrayList<String>();
entityServiceNameMap.put(entityName, serviceList);
}
serviceList.add(serviceName);
}
}
/**
* This method returns the instance given the respective class name.
* @param className name of the class
* @return an instance of the given class name
*/
private <E> E getInstance(String className, Class<E> clazz) {
Object instance = null;
try {
Class classDefinition = Class.forName(className);
instance = classDefinition.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
}
Class<?> instanceClass = instance.getClass();
if (!clazz.isAssignableFrom(instanceClass)) {
throw new RuntimeException(instanceClass.getName() + " does not implement the interface "
+ clazz.getName());
}
return (E) instance;
}
/**
* This method returns the List of the service names of the respective givne entity name.
* @param entityName the name of the entity
* @return the List of the service names
*/
private List<String> getServiceDetailClassNames(String entityName) {
List<String> serviceDetailClassList = new ArrayList<String>();
List<String> serviceNameList = entityServiceNameMap.get(entityName);
if (serviceNameList != null) {
for (String serviceName : serviceNameList) {
List<String> serviceDetailClassNameList = serviceNameDetailClassNameMap.get(serviceName);
if (serviceDetailClassNameList != null) {
serviceDetailClassList.addAll(serviceDetailClassNameList);
}
}
}
return serviceDetailClassList;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
/**
* Clones this object
* @return Cloned object
* @throws CloneNotSupportedException
*/
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
/**
* This method returns the List of all the corresponding ServiceDetailsClass given the Entity.
* @param entity an instance of Entity
* @return List of all the ServiceDetailClass corresponding to the given Entity
*/
public List<ServiceDetailsInterface> getServices(EntityInterface entity) {
List<ServiceDetailsInterface> serviceDetailsInstanceList = new ArrayList<ServiceDetailsInterface>();
List<String> serviceDetailClassList = getServiceDetailClassNames(entity.getName());
//TODO This is a hack. To be deleted after testing.
//List<String> serviceDetailClassList = getServiceDetailClassNames("gov.nih.nci.mageom.domain.BioAssay.BioAssay");
for (String serviceDetailClassName : serviceDetailClassList) {
ServiceDetailsInterface serviceDetails = getInstance(serviceDetailClassName,
ServiceDetailsInterface.class);
serviceDetailsInstanceList.add(serviceDetails);
}
return serviceDetailsInstanceList;
}
/**
* This method returns an instance of the Service Invoker Class given the respective Service Details Class.
* @param serviceDetails the instance of the Service Details class
* @return an instance of the Service Invoker Class
*/
public ServiceInvokerInterface getServiceInvoker(ServiceDetailsInterface serviceDetails) {
String serviceDetailClassName = serviceDetails.getClass().getName();
String serviceInvokerClassName = serviceDetailInvokerMap.get(serviceDetailClassName);
ServiceInvokerInterface serviceInvoker = null;
if (serviceInvokerClassName != null) {
serviceInvoker = getInstance(serviceInvokerClassName, ServiceInvokerInterface.class);
}
return serviceInvoker;
}
// public static void main(String[] args) {
// EntityInterface entity = new Entity();
// entity.setName("Entity1");
//
// EntityToAnalyticalServiceMapper entityServiceMapper = EntityToAnalyticalServiceMapper.getInstance();
// List<ServiceDetailsInterface> serviceList = entityServiceMapper.getServices(entity);
// ServiceInvokerInterface serviceInvoker1 = entityServiceMapper.getServiceInvoker(serviceList.get(0));
// ServiceInvokerInterface serviceInvoker2 = entityServiceMapper.getServiceInvoker(serviceList.get(1));
// }
}
|
Java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jtex.plot;
/**
*
* @author hios
*/
public interface ScatterCanvas {
public ScatterOptions getScatterOptions();
public void setScatterOptions(ScatterOptions options);
}
|
Java
|
/* $NetBSD: rpc_soc.c,v 1.6 2000/07/06 03:10:35 christos Exp $ */
/*
* Sun RPC is a product of Sun Microsystems, Inc. and is provided for
* unrestricted use provided that this legend is included on all tape
* media and as a part of the software program in whole or part. Users
* may copy or modify Sun RPC without charge, but are not authorized
* to license or distribute it to anyone else except as part of a product or
* program developed by the user.
*
* SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
* WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
*
* Sun RPC is provided with no support and without any obligation on the
* part of Sun Microsystems, Inc. to assist in its use, correction,
* modification or enhancement.
*
* SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
* INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
* OR ANY PART THEREOF.
*
* In no event will Sun Microsystems, Inc. be liable for any lost revenue
* or profits or other special, indirect and consequential damages, even if
* Sun has been advised of the possibility of such damages.
*
* Sun Microsystems, Inc.
* 2550 Garcia Avenue
* Mountain View, California 94043
*/
/* #ident "@(#)rpc_soc.c 1.17 94/04/24 SMI" */
/*
* Copyright (c) 1986-1991 by Sun Microsystems Inc.
* In addition, portions of such source code were derived from Berkeley
* 4.3 BSD under license from the Regents of the University of
* California.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)rpc_soc.c 1.41 89/05/02 Copyr 1988 Sun Micro";
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#ifdef PORTMAP
/*
* rpc_soc.c
*
* The backward compatibility routines for the earlier implementation
* of RPC, where the only transports supported were tcp/ip and udp/ip.
* Based on berkeley socket abstraction, now implemented on the top
* of TLI/Streams
*/
#include "namespace.h"
#include "reentrant.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include <rpc/pmap_prot.h>
#include <rpc/nettype.h>
#include <syslog.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "un-namespace.h"
#include "rpc_com.h"
#include "mt_misc.h"
static CLIENT *clnt_com_create(struct sockaddr_in *, rpcprog_t, rpcvers_t,
int *, u_int, u_int, char *);
static SVCXPRT *svc_com_create(int, u_int, u_int, char *);
static bool_t rpc_wrap_bcast(char *, struct netbuf *, struct netconfig *);
/* XXX */
#define IN4_LOCALHOST_STRING "127.0.0.1"
#define IN6_LOCALHOST_STRING "::1"
/*
* A common clnt create routine
*/
static CLIENT *
clnt_com_create(raddr, prog, vers, sockp, sendsz, recvsz, tp)
struct sockaddr_in *raddr;
rpcprog_t prog;
rpcvers_t vers;
int *sockp;
u_int sendsz;
u_int recvsz;
char *tp;
{
CLIENT *cl;
int madefd = FALSE;
int fd = *sockp;
struct netconfig *nconf;
struct netbuf bindaddr;
mutex_lock(&rpcsoc_lock);
if ((nconf = __rpc_getconfip(tp)) == NULL) {
rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
mutex_unlock(&rpcsoc_lock);
return (NULL);
}
if (fd == RPC_ANYSOCK) {
fd = __rpc_nconf2fd(nconf);
if (fd == -1)
goto syserror;
madefd = TRUE;
}
if (raddr->sin_port == 0) {
u_int proto;
u_short sport;
mutex_unlock(&rpcsoc_lock); /* pmap_getport is recursive */
proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP;
sport = pmap_getport(raddr, (u_long)prog, (u_long)vers,
proto);
if (sport == 0) {
goto err;
}
raddr->sin_port = htons(sport);
mutex_lock(&rpcsoc_lock); /* pmap_getport is recursive */
}
/* Transform sockaddr_in to netbuf */
bindaddr.maxlen = bindaddr.len = sizeof (struct sockaddr_in);
bindaddr.buf = raddr;
bindresvport(fd, NULL);
cl = clnt_tli_create(fd, nconf, &bindaddr, prog, vers,
sendsz, recvsz);
if (cl) {
if (madefd == TRUE) {
/*
* The fd should be closed while destroying the handle.
*/
(void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL);
*sockp = fd;
}
(void) freenetconfigent(nconf);
mutex_unlock(&rpcsoc_lock);
return (cl);
}
goto err;
syserror:
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
err: if (madefd == TRUE)
(void)_close(fd);
(void) freenetconfigent(nconf);
mutex_unlock(&rpcsoc_lock);
return (NULL);
}
CLIENT *
clntudp_bufcreate(raddr, prog, vers, wait, sockp, sendsz, recvsz)
struct sockaddr_in *raddr;
u_long prog;
u_long vers;
struct timeval wait;
int *sockp;
u_int sendsz;
u_int recvsz;
{
CLIENT *cl;
cl = clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
sendsz, recvsz, "udp");
if (cl == NULL) {
return (NULL);
}
(void) CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait);
return (cl);
}
CLIENT *
clntudp_create(raddr, program, version, wait, sockp)
struct sockaddr_in *raddr;
u_long program;
u_long version;
struct timeval wait;
int *sockp;
{
return clntudp_bufcreate(raddr, program, version, wait, sockp,
UDPMSGSIZE, UDPMSGSIZE);
}
CLIENT *
clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz)
struct sockaddr_in *raddr;
u_long prog;
u_long vers;
int *sockp;
u_int sendsz;
u_int recvsz;
{
return clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
sendsz, recvsz, "tcp");
}
CLIENT *
clntraw_create(prog, vers)
u_long prog;
u_long vers;
{
return clnt_raw_create((rpcprog_t)prog, (rpcvers_t)vers);
}
/*
* A common server create routine
*/
static SVCXPRT *
svc_com_create(fd, sendsize, recvsize, netid)
int fd;
u_int sendsize;
u_int recvsize;
char *netid;
{
struct netconfig *nconf;
SVCXPRT *svc;
int madefd = FALSE;
int port;
struct sockaddr_in sin;
if ((nconf = __rpc_getconfip(netid)) == NULL) {
(void) syslog(LOG_ERR, "Could not get %s transport", netid);
return (NULL);
}
if (fd == RPC_ANYSOCK) {
fd = __rpc_nconf2fd(nconf);
if (fd == -1) {
(void) freenetconfigent(nconf);
(void) syslog(LOG_ERR,
"svc%s_create: could not open connection", netid);
return (NULL);
}
madefd = TRUE;
}
memset(&sin, 0, sizeof sin);
sin.sin_family = AF_INET;
bindresvport(fd, &sin);
_listen(fd, SOMAXCONN);
svc = svc_tli_create(fd, nconf, NULL, sendsize, recvsize);
(void) freenetconfigent(nconf);
if (svc == NULL) {
if (madefd)
(void)_close(fd);
return (NULL);
}
port = (((struct sockaddr_in *)svc->xp_ltaddr.buf)->sin_port);
svc->xp_port = ntohs(port);
return (svc);
}
SVCXPRT *
svctcp_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return svc_com_create(fd, sendsize, recvsize, "tcp");
}
SVCXPRT *
svcudp_bufcreate(fd, sendsz, recvsz)
int fd;
u_int sendsz, recvsz;
{
return svc_com_create(fd, sendsz, recvsz, "udp");
}
SVCXPRT *
svcfd_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return svc_fd_create(fd, sendsize, recvsize);
}
SVCXPRT *
svcudp_create(fd)
int fd;
{
return svc_com_create(fd, UDPMSGSIZE, UDPMSGSIZE, "udp");
}
SVCXPRT *
svcraw_create()
{
return svc_raw_create();
}
int
get_myaddress(addr)
struct sockaddr_in *addr;
{
memset((void *) addr, 0, sizeof(*addr));
addr->sin_family = AF_INET;
addr->sin_port = htons(PMAPPORT);
addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
return (0);
}
/*
* For connectionless "udp" transport. Obsoleted by rpc_call().
*/
int
callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out)
const char *host;
int prognum, versnum, procnum;
xdrproc_t inproc, outproc;
void *in, *out;
{
return (int)rpc_call(host, (rpcprog_t)prognum, (rpcvers_t)versnum,
(rpcproc_t)procnum, inproc, in, outproc, out, "udp");
}
/*
* For connectionless kind of transport. Obsoleted by rpc_reg()
*/
int
registerrpc(prognum, versnum, procnum, progname, inproc, outproc)
int prognum, versnum, procnum;
char *(*progname)(char [UDPMSGSIZE]);
xdrproc_t inproc, outproc;
{
return rpc_reg((rpcprog_t)prognum, (rpcvers_t)versnum,
(rpcproc_t)procnum, progname, inproc, outproc, "udp");
}
/*
* All the following clnt_broadcast stuff is convulated; it supports
* the earlier calling style of the callback function
*/
static thread_key_t clnt_broadcast_key;
static resultproc_t clnt_broadcast_result_main;
static once_t clnt_broadcast_once = ONCE_INITIALIZER;
static void
clnt_broadcast_key_init(void)
{
thr_keycreate(&clnt_broadcast_key, free);
}
/*
* Need to translate the netbuf address into sockaddr_in address.
* Dont care about netid here.
*/
/* ARGSUSED */
static bool_t
rpc_wrap_bcast(resultp, addr, nconf)
char *resultp; /* results of the call */
struct netbuf *addr; /* address of the guy who responded */
struct netconfig *nconf; /* Netconf of the transport */
{
resultproc_t clnt_broadcast_result;
if (strcmp(nconf->nc_netid, "udp"))
return (FALSE);
if (thr_main())
clnt_broadcast_result = clnt_broadcast_result_main;
else
clnt_broadcast_result = (resultproc_t)thr_getspecific(clnt_broadcast_key);
return (*clnt_broadcast_result)(resultp,
(struct sockaddr_in *)addr->buf);
}
/*
* Broadcasts on UDP transport. Obsoleted by rpc_broadcast().
*/
enum clnt_stat
clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult)
u_long prog; /* program number */
u_long vers; /* version number */
u_long proc; /* procedure number */
xdrproc_t xargs; /* xdr routine for args */
void *argsp; /* pointer to args */
xdrproc_t xresults; /* xdr routine for results */
void *resultsp; /* pointer to results */
resultproc_t eachresult; /* call with each result obtained */
{
if (thr_main())
clnt_broadcast_result_main = eachresult;
else {
thr_once(&clnt_broadcast_once, clnt_broadcast_key_init);
thr_setspecific(clnt_broadcast_key, (void *) eachresult);
}
return rpc_broadcast((rpcprog_t)prog, (rpcvers_t)vers,
(rpcproc_t)proc, xargs, argsp, xresults, resultsp,
(resultproc_t) rpc_wrap_bcast, "udp");
}
/*
* Create the client des authentication object. Obsoleted by
* authdes_seccreate().
*/
AUTH *
authdes_create(servername, window, syncaddr, ckey)
char *servername; /* network name of server */
u_int window; /* time to live */
struct sockaddr *syncaddr; /* optional hostaddr to sync with */
des_block *ckey; /* optional conversation key to use */
{
AUTH *dummy;
AUTH *nauth;
char hostname[NI_MAXHOST];
if (syncaddr) {
/*
* Change addr to hostname, because that is the way
* new interface takes it.
*/
if (getnameinfo(syncaddr, syncaddr->sa_len, hostname,
sizeof hostname, NULL, 0, 0) != 0)
goto fallback;
nauth = authdes_seccreate(servername, window, hostname, ckey);
return (nauth);
}
fallback:
dummy = authdes_seccreate(servername, window, NULL, ckey);
return (dummy);
}
/*
* Create a client handle for a unix connection. Obsoleted by clnt_vc_create()
*/
CLIENT *
clntunix_create(raddr, prog, vers, sockp, sendsz, recvsz)
struct sockaddr_un *raddr;
u_long prog;
u_long vers;
int *sockp;
u_int sendsz;
u_int recvsz;
{
struct netbuf *svcaddr;
struct netconfig *nconf;
CLIENT *cl;
int len;
cl = NULL;
nconf = NULL;
svcaddr = NULL;
if ((raddr->sun_len == 0) ||
((svcaddr = malloc(sizeof(struct netbuf))) == NULL ) ||
((svcaddr->buf = malloc(sizeof(struct sockaddr_un))) == NULL)) {
if (svcaddr != NULL)
free(svcaddr);
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
return(cl);
}
if (*sockp < 0) {
*sockp = _socket(AF_LOCAL, SOCK_STREAM, 0);
len = raddr->sun_len = SUN_LEN(raddr);
if ((*sockp < 0) || (_connect(*sockp,
(struct sockaddr *)raddr, len) < 0)) {
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
if (*sockp != -1)
(void)_close(*sockp);
goto done;
}
}
svcaddr->buf = raddr;
svcaddr->len = raddr->sun_len;
svcaddr->maxlen = sizeof (struct sockaddr_un);
cl = clnt_vc_create(*sockp, svcaddr, prog,
vers, sendsz, recvsz);
done:
free(svcaddr->buf);
free(svcaddr);
return(cl);
}
/*
* Creates, registers, and returns a (rpc) unix based transporter.
* Obsoleted by svc_vc_create().
*/
SVCXPRT *
svcunix_create(sock, sendsize, recvsize, path)
int sock;
u_int sendsize;
u_int recvsize;
char *path;
{
struct netconfig *nconf;
void *localhandle;
struct sockaddr_un sun;
struct sockaddr *sa;
struct t_bind taddr;
SVCXPRT *xprt;
int addrlen;
xprt = (SVCXPRT *)NULL;
localhandle = setnetconfig();
while ((nconf = getnetconfig(localhandle)) != NULL) {
if (nconf->nc_protofmly != NULL &&
strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0)
break;
}
if (nconf == NULL)
return(xprt);
if ((sock = __rpc_nconf2fd(nconf)) < 0)
goto done;
memset(&sun, 0, sizeof sun);
sun.sun_family = AF_LOCAL;
if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
sizeof(sun.sun_path))
goto done;
sun.sun_len = SUN_LEN(&sun);
addrlen = sizeof (struct sockaddr_un);
sa = (struct sockaddr *)&sun;
if (_bind(sock, sa, addrlen) < 0)
goto done;
taddr.addr.len = taddr.addr.maxlen = addrlen;
taddr.addr.buf = malloc(addrlen);
if (taddr.addr.buf == NULL)
goto done;
memcpy(taddr.addr.buf, sa, addrlen);
if (nconf->nc_semantics != NC_TPI_CLTS) {
if (_listen(sock, SOMAXCONN) < 0) {
free(taddr.addr.buf);
goto done;
}
}
xprt = (SVCXPRT *)svc_tli_create(sock, nconf, &taddr, sendsize, recvsize);
done:
endnetconfig(localhandle);
return(xprt);
}
/*
* Like svunix_create(), except the routine takes any *open* UNIX file
* descriptor as its first input. Obsoleted by svc_fd_create();
*/
SVCXPRT *
svcunixfd_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return (svc_fd_create(fd, sendsize, recvsize));
}
#endif /* PORTMAP */
|
Java
|
/*
* Copyright 2004-2009, IM Kit Team. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _LOGGER_H
#define _LOGGER_H
void logmsg(const char* message, ...);
#endif // _LOGGER_H
|
Java
|
<?php
/**
* osCommerce Website
*
* @copyright (c) 2019 osCommerce; https://www.oscommerce.com
* @license MIT; https://www.oscommerce.com/license/mit.txt
*/
namespace osCommerce\OM\Core\Site\Website\SQL\Partner;
use osCommerce\OM\Core\Registry;
class GetCategories
{
public static function execute(array $data): array
{
$OSCOM_PDO = Registry::get('PDO');
if (isset($data['language_id'])) {
$sql = <<<EOD
select
coalesce(lang_user.title, lang_en.title) as title,
c.code
from
:table_website_partner_category c
left join
:table_website_partner_category_lang lang_user
on
(c.id = lang_user.id and lang_user.languages_id = :languages_id)
left join
:table_website_partner_category_lang lang_en
on
(c.id = lang_en.id and lang_en.languages_id = :default_language_id),
:table_website_partner_transaction t,
:table_website_partner p
left join
:table_website_partner_info pi_lang_user
on
(p.id = pi_lang_user.partner_id and pi_lang_user.languages_id = :languages_id)
left join
:table_website_partner_info pi_lang_en
on
(p.id = pi_lang_en.partner_id and pi_lang_en.languages_id = :default_language_id),
:table_website_partner_package pp
where
t.date_start <= now() and
t.date_end >= now() and
t.package_id = pp.id and
pp.status = 1 and
t.partner_id = p.id and
p.category_id = c.id and
coalesce(pi_lang_user.image_small, pi_lang_en.image_small) != '' and
coalesce(pi_lang_user.desc_short, pi_lang_en.desc_short) != '' and
coalesce(pi_lang_user.desc_long, pi_lang_en.desc_long) != ''
group by
c.id
order by
c.sort_order,
title
EOD;
} else {
$sql = <<<EOD
select
cl.title,
c.code
from
:table_website_partner_category c,
:table_website_partner_category_lang cl,
:table_website_partner_transaction t,
:table_website_partner p,
:table_website_partner_info pi,
:table_website_partner_package pp
where
t.date_start <= now() and
t.date_end >= now() and
t.package_id = pp.id and
pp.status = 1 and
t.partner_id = p.id and
p.category_id = c.id and
c.id = cl.id and
cl.languages_id = :default_language_id and
p.id = pi.partner_id and
pi.languages_id = cl.languages_id and
pi.image_small != '' and
pi.desc_short != '' and
pi.desc_long != ''
group by
c.id
order by
c.sort_order,
cl.title
EOD;
}
$Qgroups = $OSCOM_PDO->prepare($sql);
if (isset($data['language_id'])) {
$Qgroups->bindInt(':languages_id', $data['language_id']);
}
$Qgroups->bindInt(':default_language_id', $data['default_language_id']);
$Qgroups->setCache('website_partner_categories-lang' . ($data['language_id'] ?? $data['default_language_id']), 720);
$Qgroups->execute();
return $Qgroups->fetchAll();
}
}
|
Java
|
#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/future.hpp>
#include <agency/execution/executor/executor_traits/executor_future.hpp>
#include <agency/execution/executor/executor_traits/is_executor.hpp>
#include <utility>
#include <type_traits>
namespace agency
{
namespace detail
{
template<class Executor, class T, class... Args>
struct has_make_ready_future_impl
{
template<
class Executor2,
typename = decltype(
std::declval<Executor2&>().template make_ready_future<T>(
std::declval<Args>()...
)
)
>
static std::true_type test(int);
template<class>
static std::false_type test(...);
using type = decltype(test<Executor>(0));
};
template<class Executor, class T, class... Args>
using has_make_ready_future = typename has_make_ready_future_impl<Executor,T,Args...>::type;
// this overload handles the case of executors which have the member function .make_ready_future()
__agency_exec_check_disable__
template<class T, class Executor, class... Args>
__AGENCY_ANNOTATION
executor_future_t<Executor,T>
make_ready_future_impl(std::true_type, Executor& exec, Args&&... args)
{
return exec.template make_ready_future<T>(std::forward<Args>(args)...);
} // end make_ready_future_impl()
// this overload handles the case of executors which do not have the member function .make_ready_future()
template<class T, class Executor, class... Args>
__AGENCY_ANNOTATION
executor_future_t<Executor,T>
make_ready_future_impl(std::false_type, Executor&, Args&&... args)
{
using future_type = executor_future_t<Executor,T>;
return future_traits<future_type>::template make_ready<T>(std::forward<Args>(args)...);
} // end make_ready_future_impl()
} // end detail
template<class T, class E, class... Args,
__AGENCY_REQUIRES(detail::Executor<E>())
>
__AGENCY_ANNOTATION
executor_future_t<E,T> make_ready_future(E& exec, Args&&... args)
{
using check_for_member_function = detail::has_make_ready_future<
E,
T,
Args&&...
>;
return detail::make_ready_future_impl<T>(check_for_member_function(), exec, std::forward<Args>(args)...);
} // end make_ready_future()
} // end agency
|
Java
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Test.Hspec.Snap (
-- * Running blocks of hspec-snap tests
snap
, modifySite
, modifySite'
, afterEval
, beforeEval
-- * Core data types
, TestResponse(..)
, SnapHspecM
-- * Factory style test data generation
, Factory(..)
-- * Requests
, delete
, get
, get'
, post
, postJson
, put
, put'
, params
-- * Helpers for dealing with TestResponses
, restrictResponse
-- * Dealing with session state (EXPERIMENTAL)
, recordSession
, HasSession(..)
, sessionShouldContain
, sessionShouldNotContain
-- * Evaluating application code
, eval
-- * Unit test assertions
, shouldChange
, shouldEqual
, shouldNotEqual
, shouldBeTrue
, shouldNotBeTrue
-- * Response assertions
, should200
, shouldNot200
, should404
, shouldNot404
, should300
, shouldNot300
, should300To
, shouldNot300To
, shouldHaveSelector
, shouldNotHaveSelector
, shouldHaveText
, shouldNotHaveText
-- * Form tests
, FormExpectations(..)
, form
-- * Internal types and helpers
, SnapHspecState(..)
, setResult
, runRequest
, runHandlerSafe
, evalHandlerSafe
) where
import Control.Applicative ((<$>))
import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar
,putMVar, readMVar, takeMVar)
import Control.Exception (SomeException, catch)
import Control.Monad (void)
import Control.Monad.State (StateT (..), runStateT)
import qualified Control.Monad.State as S (get, put)
import Control.Monad.Trans (liftIO)
import Data.Aeson (encode, ToJSON)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS (ByteString)
import Data.ByteString.Lazy (fromStrict, toStrict)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Snap.Core (Response (..), getHeader)
import qualified Snap.Core as Snap
import Snap.Snaplet (Handler, Snaplet, SnapletInit,
SnapletLens, with)
import Snap.Snaplet.Session (SessionManager, commitSession,
sessionToList, setInSession)
import Snap.Snaplet.Test (InitializerState, closeSnaplet,
evalHandler', getSnaplet, runHandler')
import Snap.Test (RequestBuilder, getResponseBody)
import qualified Snap.Test as Test
import Test.Hspec
import Test.Hspec.Core.Spec
import qualified Text.Digestive as DF
import qualified Text.HandsomeSoup as HS
import qualified Text.XML.HXT.Core as HXT
-- | The result of making requests against your application. Most
-- assertions act against these types (for example, `should200`,
-- `shouldHaveSelector`, etc).
data TestResponse = Html Text
| Json LBS.ByteString
| NotFound
| Redirect Int Text
| Other Int
| Empty
deriving (Show, Eq)
-- | The main monad that tests run inside of. This allows both access
-- to the application (via requests and `eval`) and to running
-- assertions (like `should404` or `shouldHaveText`).
type SnapHspecM b = StateT (SnapHspecState b) IO
-- | Internal state used to share site initialization across tests, and to propogate failures.
-- Understanding it is completely unnecessary to use the library.
--
-- The fields it contains, in order, are:
--
-- > Result
-- > Main handler
-- > Startup state
-- > Startup state
-- > Session state
-- > Before handler (runs before each eval)
-- > After handler (runs after each eval).
data SnapHspecState b = SnapHspecState Result
(Handler b b ())
(Snaplet b)
(InitializerState b)
(MVar [(Text, Text)])
(Handler b b ())
(Handler b b ())
instance Example (SnapHspecM b ()) where
type Arg (SnapHspecM b ()) = SnapHspecState b
evaluateExample s _ cb _ =
do mv <- newEmptyMVar
cb $ \st -> do ((),SnapHspecState r' _ _ _ _ _ _) <- runStateT s st
putMVar mv r'
takeMVar mv
-- | Factory instances allow you to easily generate test data.
--
-- Essentially, you specify a default way of constructing a
-- data type, and allow certain parts of it to be modified (via
-- the 'fields' data structure).
--
-- An example follows:
--
-- > data Foo = Foo Int
-- > newtype FooFields = FooFields (IO Int)
-- > instance Factory App Foo FooFields where
-- > fields = FooFields randomIO
-- > save f = liftIO f >>= saveFoo . Foo1
-- >
-- > main = do create id :: SnapHspecM App Foo
-- > create (const $ FooFields (return 1)) :: SnapHspecM App Foo
class Factory b a d | a -> b, a -> d, d -> a where
fields :: d
save :: d -> SnapHspecM b a
create :: (d -> d) -> SnapHspecM b a
create transform = save $ transform fields
reload :: a -> SnapHspecM b a
reload = return
-- | The way to run a block of `SnapHspecM` tests within an `hspec`
-- test suite. This takes both the top level handler (usually `route
-- routes`, where `routes` are all the routes for your site) and the
-- site initializer (often named `app`), and a block of tests. A test
-- suite can have multiple calls to `snap`, though each one will cause
-- the site initializer to run, which is often a slow operation (and
-- will slow down test suites).
snap :: Handler b b () -> SnapletInit b b -> SpecWith (SnapHspecState b) -> Spec
snap site app spec = do
snapinit <- runIO $ getSnaplet (Just "test") app
mv <- runIO (newMVar [])
case snapinit of
Left err -> error $ show err
Right (snaplet, initstate) ->
afterAll (const $ closeSnaplet initstate) $
before (return (SnapHspecState Success site snaplet initstate mv (return ()) (return ()))) spec
-- | This allows you to change the default handler you are running
-- requests against within a block. This is most likely useful for
-- setting request state (for example, logging a user in).
modifySite :: (Handler b b () -> Handler b b ())
-> SpecWith (SnapHspecState b)
-> SpecWith (SnapHspecState b)
modifySite f = beforeWith (\(SnapHspecState r site snaplet initst sess bef aft) ->
return (SnapHspecState r (f site) snaplet initst sess bef aft))
-- | This performs a similar operation to `modifySite` but in the context
-- of `SnapHspecM` (which is needed if you need to `eval`, produce values, and
-- hand them somewhere else (so they can't be created within `f`).
modifySite' :: (Handler b b () -> Handler b b ())
-> SnapHspecM b a
-> SnapHspecM b a
modifySite' f a = do (SnapHspecState r site s i sess bef aft) <- S.get
S.put (SnapHspecState r (f site) s i sess bef aft)
a
-- | Evaluate a Handler action after each test.
afterEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
afterEval h = after (\(SnapHspecState _r _site s i _ _ _) ->
do res <- evalHandlerSafe h s i
case res of
Right _ -> return ()
Left msg -> liftIO $ print msg)
-- | Evaluate a Handler action before each test.
beforeEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
beforeEval h = beforeWith (\state@(SnapHspecState _r _site s i _ _ _) -> do void $ evalHandlerSafe h s i
return state)
class HasSession b where
getSessionLens :: SnapletLens b SessionManager
recordSession :: HasSession b => SnapHspecM b a -> SnapHspecM b a
recordSession a =
do (SnapHspecState r site s i mv bef aft) <- S.get
S.put (SnapHspecState r site s i mv
(do ps <- liftIO $ readMVar mv
with getSessionLens $ mapM_ (uncurry setInSession) ps
with getSessionLens commitSession)
(do ps' <- with getSessionLens sessionToList
void . liftIO $ takeMVar mv
liftIO $ putMVar mv ps'))
res <- a
(SnapHspecState r' _ _ _ _ _ _) <- S.get
void . liftIO $ takeMVar mv
liftIO $ putMVar mv []
S.put (SnapHspecState r' site s i mv bef aft)
return res
sessContents :: SnapHspecM b Text
sessContents = do
(SnapHspecState _ _ _ _ mv _ _) <- S.get
ps <- liftIO $ readMVar mv
return $ T.concat (map (uncurry T.append) ps)
sessionShouldContain :: Text -> SnapHspecM b ()
sessionShouldContain t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult Success
else setResult (Fail $ "Session did not contain: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
sessionShouldNotContain :: Text -> SnapHspecM b ()
sessionShouldNotContain t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult (Fail $ "Session should not have contained: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
else setResult Success
-- | Runs a DELETE request
delete :: Text -> SnapHspecM b TestResponse
delete path = runRequest (Test.delete (T.encodeUtf8 path) M.empty)
-- | Runs a GET request.
get :: Text -> SnapHspecM b TestResponse
get path = get' path M.empty
-- | Runs a GET request, with a set of parameters.
get' :: Text -> Snap.Params -> SnapHspecM b TestResponse
get' path ps = runRequest (Test.get (T.encodeUtf8 path) ps)
-- | A helper to construct parameters.
params :: [(ByteString, ByteString)] -- ^ Pairs of parameter and value.
-> Snap.Params
params = M.fromList . map (\x -> (fst x, [snd x]))
-- | Creates a new POST request, with a set of parameters.
post :: Text -> Snap.Params -> SnapHspecM b TestResponse
post path ps = runRequest (Test.postUrlEncoded (T.encodeUtf8 path) ps)
-- | Creates a new POST request with a given JSON value as the request body.
postJson :: ToJSON tj => Text -> tj -> SnapHspecM b TestResponse
postJson path json = runRequest $ Test.postRaw (T.encodeUtf8 path)
"application/json"
(toStrict $ encode json)
-- | Creates a new PUT request, with a set of parameters, with a default type of "application/x-www-form-urlencoded"
put :: Text -> Snap.Params -> SnapHspecM b TestResponse
put path params' = put' path "application/x-www-form-urlencoded" params'
-- | Creates a new PUT request with a configurable MIME/type
put' :: Text -> Text -> Snap.Params -> SnapHspecM b TestResponse
put' path mime params' = runRequest $ do
Test.put (T.encodeUtf8 path) (T.encodeUtf8 mime) ""
Test.setQueryString params'
-- | Restricts a response to matches for a given CSS selector.
-- Does nothing to non-Html responses.
restrictResponse :: Text -> TestResponse -> TestResponse
restrictResponse selector (Html body) =
case HXT.runLA (HXT.xshow $ HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> Html ""
matches -> Html (T.concat (map T.pack matches))
restrictResponse _ r = r
-- | Runs an arbitrary stateful action from your application.
eval :: Handler b b a -> SnapHspecM b a
eval act = do (SnapHspecState _ _site app is _mv bef aft) <- S.get
liftIO $ either (error . T.unpack) id <$> evalHandlerSafe (do bef
r <- act
aft
return r) app is
-- | Records a test Success or Fail. Only the first Fail will be
-- recorded (and will cause the whole block to Fail).
setResult :: Result -> SnapHspecM b ()
setResult r = do (SnapHspecState r' s a i sess bef aft) <- S.get
case r' of
Success -> S.put (SnapHspecState r s a i sess bef aft)
_ -> return ()
-- | Asserts that a given stateful action will produce a specific different result after
-- an action has been run.
shouldChange :: (Show a, Eq a)
=> (a -> a)
-> Handler b b a
-> SnapHspecM b c
-> SnapHspecM b ()
shouldChange f v act = do before' <- eval v
void act
after' <- eval v
shouldEqual (f before') after'
-- | Asserts that two values are equal.
shouldEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldEqual a b = if a == b
then setResult Success
else setResult (Fail ("Should have held: " ++ show a ++ " == " ++ show b))
-- | Asserts that two values are not equal.
shouldNotEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldNotEqual a b = if a == b
then setResult (Fail ("Should not have held: " ++ show a ++ " == " ++ show b))
else setResult Success
-- | Asserts that the value is True.
shouldBeTrue :: Bool
-> SnapHspecM b ()
shouldBeTrue True = setResult Success
shouldBeTrue False = setResult (Fail "Value should have been True.")
-- | Asserts that the value is not True (otherwise known as False).
shouldNotBeTrue :: Bool
-> SnapHspecM b ()
shouldNotBeTrue False = setResult Success
shouldNotBeTrue True = setResult (Fail "Value should have been True.")
-- | Asserts that the response is a success (either Html, or Other with status 200).
should200 :: TestResponse -> SnapHspecM b ()
should200 (Html _) = setResult Success
should200 (Other 200) = setResult Success
should200 r = setResult (Fail (show r))
-- | Asserts that the response is not a normal 200.
shouldNot200 :: TestResponse -> SnapHspecM b ()
shouldNot200 (Html _) = setResult (Fail "Got Html back.")
shouldNot200 (Other 200) = setResult (Fail "Got Other with 200 back.")
shouldNot200 _ = setResult Success
-- | Asserts that the response is a NotFound.
should404 :: TestResponse -> SnapHspecM b ()
should404 NotFound = setResult Success
should404 r = setResult (Fail (show r))
-- | Asserts that the response is not a NotFound.
shouldNot404 :: TestResponse -> SnapHspecM b ()
shouldNot404 NotFound = setResult (Fail "Got NotFound back.")
shouldNot404 _ = setResult Success
-- | Asserts that the response is a redirect.
should300 :: TestResponse -> SnapHspecM b ()
should300 (Redirect _ _) = setResult Success
should300 r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect.
shouldNot300 :: TestResponse -> SnapHspecM b ()
shouldNot300 (Redirect _ _) = setResult (Fail "Got Redirect back.")
shouldNot300 _ = setResult Success
-- | Asserts that the response is a redirect, and thet the url it
-- redirects to starts with the given path.
should300To :: Text -> TestResponse -> SnapHspecM b ()
should300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult Success
should300To _ r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect to a given path. Note
-- that it can still be a redirect for this assertion to succeed, the
-- path it redirects to just can't start with the given path.
shouldNot300To :: Text -> TestResponse -> SnapHspecM b ()
shouldNot300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult (Fail "Got Redirect back.")
shouldNot300To _ _ = setResult Success
-- | Assert that a response (which should be Html) has a given selector.
shouldHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveSelector selector r@(Html body) =
setResult $ if haveSelector' selector r
then Success
else Fail msg
where msg = T.unpack $ T.concat ["Html should have contained selector: ", selector, "\n\n", body]
shouldHaveSelector match _ = setResult (Fail (T.unpack $ T.concat ["Non-HTML body should have contained css selector: ", match]))
-- | Assert that a response (which should be Html) doesn't have a given selector.
shouldNotHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveSelector selector r@(Html body) =
setResult $ if haveSelector' selector r
then Fail msg
else Success
where msg = T.unpack $ T.concat ["Html should not have contained selector: ", selector, "\n\n", body]
shouldNotHaveSelector _ _ = setResult Success
haveSelector' :: Text -> TestResponse -> Bool
haveSelector' selector (Html body) =
case HXT.runLA (HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> False
_ -> True
haveSelector' _ _ = False
-- | Asserts that the response (which should be Html) contains the given text.
shouldHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveText match (Html body) =
if T.isInfixOf match body
then setResult Success
else setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
shouldHaveText match _ = setResult (Fail (T.unpack $ T.concat ["Body contains: ", match]))
-- | Asserts that the response (which should be Html) does not contain the given text.
shouldNotHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveText match (Html body) =
if T.isInfixOf match body
then setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
else setResult Success
shouldNotHaveText _ _ = setResult Success
-- | A data type for tests against forms.
data FormExpectations a = Value a -- ^ The value the form should take (and should be valid)
| Predicate (a -> Bool)
| ErrorPaths [Text] -- ^ The error paths that should be populated
-- | Tests against digestive-functors forms.
form :: (Eq a, Show a)
=> FormExpectations a -- ^ If the form should succeed, Value a is what it should produce.
-- If failing, ErrorPaths should be all the errors that are triggered.
-> DF.Form Text (Handler b b) a -- ^ The form to run
-> M.Map Text Text -- ^ The parameters to pass
-> SnapHspecM b ()
form expected theForm theParams =
do r <- eval $ DF.postForm "form" theForm (const $ return lookupParam)
case expected of
Value a -> shouldEqual (snd r) (Just a)
Predicate f ->
case snd r of
Nothing -> setResult (Fail $ T.unpack $
T.append "Expected form to validate. Resulted in errors: "
(T.pack (show $ DF.viewErrors $ fst r)))
Just v -> if f v
then setResult Success
else setResult (Fail $ T.unpack $
T.append "Expected predicate to pass on value: "
(T.pack (show v)))
ErrorPaths expectedPaths ->
do let viewErrorPaths = map (DF.fromPath . fst) $ DF.viewErrors $ fst r
if all (`elem` viewErrorPaths) expectedPaths
then if length viewErrorPaths == length expectedPaths
then setResult Success
else setResult (Fail $ "Number of errors did not match test. Got:\n\n "
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
else setResult (Fail $ "Did not have all errors specified. Got:\n\n"
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
where lookupParam pth = case M.lookup (DF.fromPath pth) fixedParams of
Nothing -> return []
Just v -> return [DF.TextInput v]
fixedParams = M.mapKeys (T.append "form.") theParams
-- | Runs a request (built with helpers from Snap.Test), resulting in a response.
runRequest :: RequestBuilder IO () -> SnapHspecM b TestResponse
runRequest req = do
(SnapHspecState _ site app is _ bef aft) <- S.get
res <- liftIO $ runHandlerSafe req (bef >> site >> aft) app is
case res of
Left err ->
error $ T.unpack err
Right response ->
case rspStatus response of
404 -> return NotFound
200 ->
liftIO $ parse200 response
_ -> if rspStatus response >= 300 && rspStatus response < 400
then do let url = fromMaybe "" $ getHeader "Location" response
return (Redirect (rspStatus response) (T.decodeUtf8 url))
else return (Other (rspStatus response))
parse200 :: Response -> IO TestResponse
parse200 resp =
let body = getResponseBody resp
contentType = getHeader "content-type" resp in
case contentType of
Just "application/json" -> Json . fromStrict <$> body
_ -> Html . T.decodeUtf8 <$> body
-- | Runs a request against a given handler (often the whole site),
-- with the given state. Returns any triggered exception, or the response.
runHandlerSafe :: RequestBuilder IO ()
-> Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text Response)
runHandlerSafe req site s is =
catch (runHandler' s is req site) (\(e::SomeException) -> return $ Left (T.pack $ show e))
-- | Evaluates a given handler with the given state. Returns any
-- triggered exception, or the value produced.
evalHandlerSafe :: Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text v)
evalHandlerSafe act s is =
catch (evalHandler' s is (Test.get "" M.empty) act) (\(e::SomeException) -> return $ Left (T.pack $ show e))
{-# ANN put ("HLint: ignore Eta reduce"::String) #-}
|
Java
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.sandbox.stats.multicomp.set_remove_subs — statsmodels v0.10.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.stats.multicomp.tiecorrect" href="statsmodels.sandbox.stats.multicomp.tiecorrect.html" />
<link rel="prev" title="statsmodels.sandbox.stats.multicomp.set_partition" href="statsmodels.sandbox.stats.multicomp.set_partition.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.stats.multicomp.tiecorrect.html" title="statsmodels.sandbox.stats.multicomp.tiecorrect"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.stats.multicomp.set_partition.html" title="statsmodels.sandbox.stats.multicomp.set_partition"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../stats.html" accesskey="U">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-sandbox-stats-multicomp-set-remove-subs">
<h1>statsmodels.sandbox.stats.multicomp.set_remove_subs<a class="headerlink" href="#statsmodels-sandbox-stats-multicomp-set-remove-subs" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="statsmodels.sandbox.stats.multicomp.set_remove_subs">
<code class="sig-prename descclassname">statsmodels.sandbox.stats.multicomp.</code><code class="sig-name descname">set_remove_subs</code><span class="sig-paren">(</span><em class="sig-param">ssli</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/stats/multicomp.html#set_remove_subs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.sandbox.stats.multicomp.set_remove_subs" title="Permalink to this definition">¶</a></dt>
<dd><p>remove sets that are subsets of another set from a list of tuples</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl class="simple">
<dt><strong>ssli</strong><span class="classifier">list of tuples</span></dt><dd><p>each tuple is considered as a set</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl class="simple">
<dt><strong>part</strong><span class="classifier">list of tuples</span></dt><dd><p>new list with subset tuples removed, it is sorted by set-length of tuples. The
list contains original tuples, duplicate elements are not removed.</p>
</dd>
</dl>
</dd>
</dl>
<p class="rubric">Examples</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">set_remove_subs</span><span class="p">([(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">0</span><span class="p">,)])</span>
<span class="go">[(1, 2, 3), (0, 1)]</span>
<span class="gp">>>> </span><span class="n">set_remove_subs</span><span class="p">([(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">0</span><span class="p">,)])</span>
<span class="go">[(1, 1, 1, 2, 3), (0, 1)]</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.sandbox.stats.multicomp.set_partition.html"
title="previous chapter">statsmodels.sandbox.stats.multicomp.set_partition</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.sandbox.stats.multicomp.tiecorrect.html"
title="next chapter">statsmodels.sandbox.stats.multicomp.tiecorrect</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.sandbox.stats.multicomp.set_remove_subs.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html>
|
Java
|
/*
* This file is part of the Soletta Project
*
* Copyright (C) 2015 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
* 2010, 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All
* Rights Reserved. This file has code excerpts (string module)
* extracted from cpython project (https://hg.python.org/cpython/),
* that comes under the PSFL license. The string formatting code was
* adapted here to Soletta data types. The entire text for that
* license is present in this directory */
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unicode/ustring.h>
#include <unicode/utypes.h>
#include <unicode/uchar.h>
#include "string.h"
#define FAST_COUNT 0
#define FAST_SEARCH 1
#define STRINGLIB_BLOOM_WIDTH sizeof(UChar)
#define STRINGLIB_BLOOM_ADD(mask, ch) \
((mask |= (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH - 1)))))
#define STRINGLIB_BLOOM(mask, ch) \
((mask & (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH - 1)))))
static inline ssize_t
fast_search(const UChar *str,
size_t str_len,
const UChar *pattern,
size_t pattern_len,
size_t max_count,
int mode)
{
const UChar *str_ptr;
const UChar *pattern_ptr;
unsigned long mask;
size_t i, j, mlast;
size_t skip, count = 0;
ssize_t w;
w = str_len - pattern_len;
if (w < 0 || (mode == FAST_COUNT && max_count == 0))
return -1;
/* look for special cases */
if (pattern_len <= 1) {
if (pattern_len <= 0)
return -1;
/* use special case for 1-character strings */
if (str_len > 10 && (mode == FAST_SEARCH)) {
/* use memchr if we can choose a needle without too many
likely false positives */
UChar *ptr = u_memchr(str, pattern[0], str_len);
if (!ptr)
return -1;
return ptr - str;
}
if (mode == FAST_COUNT) {
for (i = 0; i < str_len; i++)
if (str[i] == pattern[0]) {
count++;
if (count == max_count)
return max_count;
}
return count;
} else { /* (mode == FAST_SEARCH) */
for (i = 0; i < str_len; i++)
if (str[i] == pattern[0])
return i;
}
return -1;
}
mlast = pattern_len - 1;
skip = mlast - 1;
mask = 0;
str_ptr = str + pattern_len - 1;
pattern_ptr = pattern + pattern_len - 1;
/* create compressed boyer-moore delta 1 table */
/* process pattern[:-1] */
for (i = 0; i < mlast; i++) {
STRINGLIB_BLOOM_ADD(mask, pattern[i]);
if (pattern[i] == pattern[mlast])
skip = mlast - i - 1;
}
/* process pattern[-1] outside the loop */
STRINGLIB_BLOOM_ADD(mask, pattern[mlast]);
for (i = 0; i <= (size_t)w; i++) {
/* note: using mlast in the skip path slows things down on x86 */
if (str_ptr[i] == pattern_ptr[0]) {
/* candidate match */
for (j = 0; j < mlast; j++)
if (str[i + j] != pattern[j])
break;
if (j == mlast) {
/* got a match! */
if (mode != FAST_COUNT)
return i;
count++;
if (count == max_count)
return max_count;
i = i + mlast;
continue;
}
/* miss: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1]))
i = i + pattern_len;
else
i = i + skip;
} else {
/* skip: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1]))
i = i + pattern_len;
}
}
if (mode != FAST_COUNT)
return -1;
return count;
}
static inline ssize_t
sub_str_count(const UChar *str,
size_t str_len,
const UChar *sub,
size_t sub_len,
size_t max_count)
{
ssize_t count;
if (sub_len == 0)
return (str_len < max_count) ? str_len + 1 : max_count;
count = fast_search(str, str_len, sub, sub_len, max_count, FAST_COUNT);
if (count < 0)
return 0; /* no match */
return count;
}
static inline ssize_t
sub_str_find(const UChar *str,
ssize_t str_len,
const UChar *sub,
ssize_t sub_len,
ssize_t offset)
{
ssize_t pos;
if (sub_len == 0)
return offset;
pos = fast_search(str, str_len, sub, sub_len, -1, FAST_SEARCH);
if (pos >= 0)
pos += offset;
return pos;
}
#define ICU_STR_FROM_UTF8_GOTO(_icu_str, _icu_sz, _icu_err_val, \
_utf_str, _icu_size_calc_goto, _no_mem_goto, _icu_conv_goto) \
do { \
_icu_err_val = U_ZERO_ERROR; \
u_strFromUTF8(NULL, 0, &_icu_sz, _utf_str, -1, &_icu_err_val); \
if (U_FAILURE(_icu_err_val) && \
_icu_err_val != U_BUFFER_OVERFLOW_ERROR) \
goto _icu_size_calc_goto; \
_icu_str = calloc(_icu_sz + 1, sizeof(*_icu_str)); \
if (!_icu_str) \
goto _no_mem_goto; \
_icu_err_val = U_ZERO_ERROR; \
u_strFromUTF8(_icu_str, _icu_sz + 1, &_icu_sz, _utf_str, \
-1, &_icu_err_val); \
if (U_FAILURE(_icu_err_val)) { \
goto _icu_conv_goto; \
} \
} while (0)
static UChar *
u_strdup(UChar *in)
{
uint32_t len = u_strlen(in) + 1;
UChar *result = malloc(sizeof(UChar) * len);
SOL_NULL_CHECK(result, NULL);
u_memcpy(result, in, len);
return result;
}
static inline void
replace_1_char_in_place(UChar *s, UChar *end,
UChar u1, UChar u2, ssize_t max_count)
{
*s = u2;
while (--max_count && ++s != end) {
/* Find the next character to be replaced. If it occurs often,
* it is faster to scan for it using an inline loop. If it
* occurs seldom, it is faster to scan for it using a function
* call; the overhead of the function call is amortized across
* the many characters that call covers. We start with an
* inline loop and use a heuristic to determine whether to
* fall back to a function call.
*/
if (*s != u1) {
int attempts = 10;
while (true) {
if (++s == end)
return;
if (*s == u1)
break;
if (!--attempts) {
s++;
s = u_memchr(s, u1, end - s);
if (s == NULL)
return;
/* restart the dummy loop */
break;
}
}
}
*s = u2;
}
}
UChar *
string_replace(struct sol_flow_node *node,
UChar *value,
UChar *change_from,
UChar *change_to,
size_t max_count)
{
UChar *ret;
size_t value_len = u_strlen(value);
size_t change_to_len = u_strlen(change_to);
size_t change_from_len = u_strlen(change_from);
if (max_count == 0) {
ret = u_strdup(value);
goto nothing;
}
if (u_strcmp(change_from, change_to) == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len == change_to_len) {
/* same length */
if (change_from_len == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len == 1) {
/* replace characters */
ret = u_strdup(value);
replace_1_char_in_place(ret, ret + value_len, change_from[0],
change_to[0], max_count);
} else {
UChar *token;
ssize_t i;
ret = u_strdup(value);
token = u_strFindFirst(value, value_len, change_from,
change_from_len);
if (!token)
goto nothing;
i = token - value;
u_memcpy(ret, value, value_len);
/* change everything in-place, starting with this one */
u_memcpy(ret + i, change_to, change_to_len);
i += change_from_len;
while (--max_count > 0) {
token = u_strFindFirst(value + i, value_len - i, change_from,
change_from_len);
if (!token)
break;
u_memcpy(ret + i, change_to, change_to_len);
i += change_from_len;
}
}
} else {
ssize_t count, i, j, ires, new_size;
int r;
count = sub_str_count(value, value_len,
change_from, change_from_len, max_count);
if (count == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len < change_to_len &&
change_to_len - change_from_len >
(INT32_MAX - value_len) / count) {
sol_flow_send_error_packet(node, -EINVAL,
"replace string is too long");
goto error;
}
r = sol_util_ssize_mul(count,
(ssize_t)(change_to_len - change_from_len), &new_size);
if (r < 0 ||
(new_size > 0 && SSIZE_MAX - new_size < (ssize_t)value_len)) {
sol_flow_send_error_packet(node, -EINVAL,
"replace string is too long");
goto error;
}
new_size += value_len;
if (new_size == 0) {
UErrorCode err;
r = icu_str_from_utf8("", &ret, &err);
SOL_INT_CHECK_GOTO(r, < 0, error);
goto done;
}
ret = calloc(new_size + 1, sizeof(*ret));
if (!ret)
goto error;
ires = i = 0;
if (change_from_len > 0) {
while (count-- > 0) {
UChar *token;
/* look for next match */
token = u_strFindFirst(value + i, value_len - i, change_from,
change_from_len);
if (!token) {
free(ret);
ret = u_strdup(value);
goto nothing;
}
j = sub_str_find(value + i, value_len - i,
change_from, change_from_len, i);
if (j == -1)
break;
else if (j > i) {
/* copy unchanged part [i:j] */
u_memcpy(ret + ires, value + i, (j - i));
ires += j - i;
}
/* copy substitution string */
if (change_to_len > 0) {
u_memcpy(ret + ires, change_to, change_to_len);
ires += change_to_len;
}
i = j + change_from_len;
}
if (i < (ssize_t)value_len)
/* copy tail [i:] */
u_memcpy(ret + ires, value + i, (value_len - i));
} else {
/* interleave */
while (count > 0) {
u_memcpy(ret + ires, change_to, change_to_len);
ires += change_to_len;
if (--count <= 0)
break;
u_memcpy(ret + ires, value + i, 1);
ires++;
i++;
}
u_memcpy(ret + ires, value + i, (value_len - i));
}
}
done:
nothing:
return ret;
error:
return NULL;
}
|
Java
|
/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include "server.h"
#include "../util/strings.h"
#include "../util/file.h"
#include "../util/config.h"
#include "../util/log.h"
#include "../util/ip_filter.h"
#include "link.h"
#include <vector>
static DEF_PROC(ping);
static DEF_PROC(info);
static DEF_PROC(auth);
#define TICK_INTERVAL 100 // ms
#define STATUS_REPORT_TICKS (300 * 1000/TICK_INTERVAL) // second
volatile bool quit = false;
volatile uint32_t g_ticks = 0;
void signal_handler(int sig){
switch(sig){
case SIGTERM:
case SIGINT:{
quit = true;
break;
}
case SIGALRM:{
g_ticks ++;
break;
}
}
}
NetworkServer::NetworkServer(){
tick_interval = TICK_INTERVAL;
status_report_ticks = STATUS_REPORT_TICKS;
conf = NULL;
serv_link = NULL;
link_count = 0;
fdes = new Fdevents();
ip_filter = new IpFilter();
// add built-in procs, can be overridden
proc_map.set_proc("ping", "r", proc_ping);
proc_map.set_proc("info", "r", proc_info);
proc_map.set_proc("auth", "r", proc_auth);
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifndef __CYGWIN__
signal(SIGALRM, signal_handler);
{
struct itimerval tv;
tv.it_interval.tv_sec = (TICK_INTERVAL / 1000);
tv.it_interval.tv_usec = (TICK_INTERVAL % 1000) * 1000;
tv.it_value.tv_sec = 1;
tv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tv, NULL);
}
#endif
}
NetworkServer::~NetworkServer(){
delete conf;
delete serv_link;
delete fdes;
delete ip_filter;
writer->stop();
delete writer;
reader->stop();
delete reader;
}
void NetworkServer::init(const char *conf_file){
if(!is_file(conf_file)){
fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
exit(1);
}
conf = Config::load(conf_file);
if(!conf){
fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
exit(1);
}
{
std::string conf_dir = real_dirname(conf_file);
if(chdir(conf_dir.c_str()) == -1){
fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
exit(1);
}
}
this->init(*conf);
}
void NetworkServer::init(const Config &conf){
// init ip_filter
{
Config *cc = (Config *)conf.get("server");
if(cc != NULL){
std::vector<Config *> *children = &cc->children;
std::vector<Config *>::iterator it;
for(it = children->begin(); it != children->end(); it++){
if((*it)->key == "allow"){
const char *ip = (*it)->str();
log_info(" allow %s", ip);
ip_filter->add_allow(ip);
}
if((*it)->key == "deny"){
const char *ip = (*it)->str();
log_info(" deny %s", ip);
ip_filter->add_deny(ip);
}
}
}
}
{ // server
const char *ip = conf.get_str("server.ip");
int port = conf.get_num("server.port");
if(ip == NULL || ip[0] == '\0'){
ip = "127.0.0.1";
}
serv_link = Link::listen(ip, port);
if(serv_link == NULL){
log_fatal("error opening server socket! %s", strerror(errno));
fprintf(stderr, "error opening server socket! %s\n", strerror(errno));
exit(1);
}
log_info("server listen on %s:%d", ip, port);
std::string password;
password = conf.get_str("server.auth");
if(password.size() && (password.size() < 32 || password == "very-strong-password")){
log_fatal("weak password is not allowed!");
fprintf(stderr, "WARNING! Weak password is not allowed!\n");
exit(1);
}
if(password.empty()){
log_info("auth: off");
}else{
log_info("auth: on");
}
this->need_auth = false;
if(!password.empty()){
this->need_auth = true;
this->password = password;
}
}
}
void NetworkServer::serve(){
writer = new ProcWorkerPool("writer");
writer->start(WRITER_THREADS);
reader = new ProcWorkerPool("reader");
reader->start(READER_THREADS);
ready_list_t ready_list;
ready_list_t ready_list_2;
ready_list_t::iterator it;
const Fdevents::events_t *events;
fdes->set(serv_link->fd(), FDEVENT_IN, 0, serv_link);
fdes->set(this->reader->fd(), FDEVENT_IN, 0, this->reader);
fdes->set(this->writer->fd(), FDEVENT_IN, 0, this->writer);
uint32_t last_ticks = g_ticks;
while(!quit){
// status report
if((uint32_t)(g_ticks - last_ticks) >= STATUS_REPORT_TICKS){
last_ticks = g_ticks;
log_info("server running, links: %d", this->link_count);
}
ready_list.swap(ready_list_2);
ready_list_2.clear();
if(!ready_list.empty()){
// ready_list not empty, so we should return immediately
events = fdes->wait(0);
}else{
events = fdes->wait(50);
}
if(events == NULL){
log_fatal("events.wait error: %s", strerror(errno));
break;
}
for(int i=0; i<(int)events->size(); i++){
const Fdevent *fde = events->at(i);
if(fde->data.ptr == serv_link){
Link *link = accept_link();
if(link){
this->link_count ++;
log_debug("new link from %s:%d, fd: %d, links: %d",
link->remote_ip, link->remote_port, link->fd(), this->link_count);
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}
}else if(fde->data.ptr == this->reader || fde->data.ptr == this->writer){
ProcWorkerPool *worker = (ProcWorkerPool *)fde->data.ptr;
ProcJob job;
if(worker->pop(&job) == 0){
log_fatal("reading result from workers error!");
exit(0);
}
if(proc_result(&job, &ready_list) == PROC_ERROR){
//
}
}else{
proc_client_event(fde, &ready_list);
}
}
for(it = ready_list.begin(); it != ready_list.end(); it ++){
Link *link = *it;
if(link->error()){
this->link_count --;
fdes->del(link->fd());
delete link;
continue;
}
const Request *req = link->recv();
if(req == NULL){
log_warn("fd: %d, link parse error, delete link", link->fd());
this->link_count --;
fdes->del(link->fd());
delete link;
continue;
}
if(req->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
continue;
}
link->active_time = millitime();
ProcJob job;
job.link = link;
this->proc(&job);
if(job.result == PROC_THREAD){
fdes->del(link->fd());
continue;
}
if(job.result == PROC_BACKEND){
fdes->del(link->fd());
this->link_count --;
continue;
}
if(proc_result(&job, &ready_list_2) == PROC_ERROR){
//
}
} // end foreach ready link
}
}
Link* NetworkServer::accept_link(){
Link *link = serv_link->accept();
if(link == NULL){
log_error("accept failed! %s", strerror(errno));
return NULL;
}
if(!ip_filter->check_pass(link->remote_ip)){
log_debug("ip_filter deny link from %s:%d", link->remote_ip, link->remote_port);
delete link;
return NULL;
}
link->nodelay();
link->noblock();
link->create_time = millitime();
link->active_time = link->create_time;
return link;
}
int NetworkServer::proc_result(ProcJob *job, ready_list_t *ready_list){
Link *link = job->link;
int len;
if(job->cmd){
job->cmd->calls += 1;
job->cmd->time_wait += job->time_wait;
job->cmd->time_proc += job->time_proc;
}
if(job->result == PROC_ERROR){
log_info("fd: %d, proc error, delete link", link->fd());
goto proc_err;
}
len = link->write();
//log_debug("write: %d", len);
if(len < 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
goto proc_err;
}
if(!link->output->empty()){
fdes->set(link->fd(), FDEVENT_OUT, 1, link);
}
if(link->input->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}else{
fdes->clr(link->fd(), FDEVENT_IN);
ready_list->push_back(link);
}
return PROC_OK;
proc_err:
this->link_count --;
fdes->del(link->fd());
delete link;
return PROC_ERROR;
}
/*
event:
read => ready_list OR close
write => NONE
proc =>
done: write & (read OR ready_list)
async: stop (read & write)
1. When writing to a link, it may happen to be in the ready_list,
so we cannot close that link in write process, we could only
just mark it as closed.
2. When reading from a link, it is never in the ready_list, so it
is safe to close it in read process, also safe to put it into
ready_list.
3. Ignore FDEVENT_ERR
A link is in either one of these places:
1. ready list
2. async worker queue
So it safe to delete link when processing ready list and async worker result.
*/
int NetworkServer::proc_client_event(const Fdevent *fde, ready_list_t *ready_list){
Link *link = (Link *)fde->data.ptr;
if(fde->events & FDEVENT_IN){
ready_list->push_back(link);
if(link->error()){
return 0;
}
int len = link->read();
//log_debug("fd: %d read: %d", link->fd(), len);
if(len <= 0){
log_debug("fd: %d, read: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
}
if(fde->events & FDEVENT_OUT){
if(link->error()){
return 0;
}
int len = link->write();
if(len <= 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
if(link->output->empty()){
fdes->clr(link->fd(), FDEVENT_OUT);
}
}
return 0;
}
void NetworkServer::proc(ProcJob *job){
job->serv = this;
job->result = PROC_OK;
job->stime = millitime();
const Request *req = job->link->last_recv();
Response resp;
do{
// AUTH
if(this->need_auth && job->link->auth == false && req->at(0) != "auth"){
resp.push_back("noauth");
resp.push_back("authentication required");
break;
}
Command *cmd = proc_map.get_proc(req->at(0));
if(!cmd){
resp.push_back("client_error");
resp.push_back("Unknown Command: " + req->at(0).String());
break;
}
job->cmd = cmd;
if(cmd->flags & Command::FLAG_THREAD){
if(cmd->flags & Command::FLAG_WRITE){
job->result = PROC_THREAD;
writer->push(*job);
}else{
job->result = PROC_THREAD;
reader->push(*job);
}
return;
}
proc_t p = cmd->proc;
job->time_wait = 1000 * (millitime() - job->stime);
job->result = (*p)(this, job->link, *req, &resp);
job->time_proc = 1000 * (millitime() - job->stime) - job->time_wait;
}while(0);
if(job->link->send(resp.resp) == -1){
job->result = PROC_ERROR;
}else{
if(log_level() >= Logger::LEVEL_DEBUG){
log_debug("w:%.3f,p:%.3f, req: %s, resp: %s",
job->time_wait, job->time_proc,
serialize_req(*req).c_str(),
serialize_req(resp.resp).c_str());
}
}
}
/* built-in procs */
static int proc_ping(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
return 0;
}
static int proc_info(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
resp->push_back("ideawu's network server framework");
resp->push_back("version");
resp->push_back("1.0");
resp->push_back("links");
resp->add(net->link_count);
{
int64_t calls = 0;
proc_map_t::iterator it;
for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){
Command *cmd = it->second;
calls += cmd->calls;
}
resp->push_back("total_calls");
resp->add(calls);
}
return 0;
}
static int proc_auth(NetworkServer *net, Link *link, const Request &req, Response *resp){
if(req.size() != 2){
resp->push_back("client_error");
}else{
if(!net->need_auth || req[1] == net->password){
link->auth = true;
resp->push_back("ok");
resp->push_back("1");
}else{
resp->push_back("error");
resp->push_back("invalid password");
}
}
return 0;
}
|
Java
|
import { Page } from 'puppeteer';
import Textbox from 'app/element/textbox';
import AuthenticatedPage from 'app/page/authenticated-page';
import { waitForDocumentTitle, waitForUrl, waitWhileLoading } from 'utils/waits-utils';
import Button from 'app/element/button';
import Textarea from 'app/element/textarea';
import { PageUrl } from 'app/text-labels';
import Link from 'app/element/link';
export const PageTitle = 'Profile';
const LabelAlias = {
ResearchBackground: 'Your research background, experience and research interests',
SaveProfile: 'Save Profile',
NeedsConfirmation: 'Please update or verify your profile.',
LooksGood: 'Looks Good'
};
const DataTestIdAlias = {
FirstName: 'givenName',
LastName: 'familyName',
ProfessionalUrl: 'professionalUrl',
Address1: 'streetAddress1',
Address2: 'streetAddress2',
City: 'city',
State: 'state',
Zip: 'zipCode',
Country: 'country'
};
export const MissingErrorAlias = {
FirstName: 'First Name',
LastName: 'Last Name',
ResearchBackground: 'Current Research',
Address1: 'Street address1',
City: 'City',
State: 'State',
Zip: 'Zip code',
Country: 'Country'
};
export default class ProfilePage extends AuthenticatedPage {
constructor(page: Page) {
super(page);
}
/**
* Load 'Profile' page and ensure page load is completed.
*/
async load(): Promise<this> {
await this.loadPage({ url: PageUrl.Profile });
await waitWhileLoading(this.page);
return this;
}
async isLoaded(): Promise<boolean> {
await Promise.all([waitForUrl(this.page, '/profile'), waitForDocumentTitle(this.page, PageTitle)]);
await waitWhileLoading(this.page);
return true;
}
getFirstNameInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.FirstName });
}
getLastNameInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.LastName });
}
getProfessionalUrlInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.ProfessionalUrl });
}
getResearchBackgroundTextarea(): Textarea {
return Textarea.findByName(this.page, { normalizeSpace: LabelAlias.ResearchBackground });
}
getAddress1Input(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Address1 });
}
getAddress2Input(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Address2 });
}
getCityInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.City });
}
getStateInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.State });
}
getZipCodeInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Zip });
}
getCountryInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Country });
}
getSaveProfileButton(): Button {
return Button.findByName(this.page, { name: LabelAlias.SaveProfile });
}
async needsConfirmation(): Promise<boolean> {
return await this.containsText(LabelAlias.NeedsConfirmation);
}
getLooksGoodLink(): Link {
return Link.findByName(this.page, { name: LabelAlias.LooksGood });
}
}
|
Java
|
// This program sends logging records directly to the server, rather
// than going through the client logging daemon.
#include "ace/SOCK_Connector.h"
#include "ace/Log_Record.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_time.h"
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_unistd.h"
#include "ace/CDR_Stream.h"
static u_short LOGGER_PORT = ACE_DEFAULT_SERVER_PORT;
static const ACE_TCHAR *const LOGGER_HOST = ACE_DEFAULT_SERVER_HOST;
static const ACE_TCHAR *const DATA = ACE_TEXT ("hello world\n");
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
u_short logger_port = argc > 1 ? ACE_OS::atoi (argv[1]) : LOGGER_PORT;
const ACE_TCHAR *logger_host = argc > 2 ? argv[2] : LOGGER_HOST;
ACE_SOCK_Stream logger;
ACE_SOCK_Connector connector;
ACE_INET_Addr addr (logger_port, logger_host);
ACE_Log_Record log_record (LM_DEBUG,
ACE_OS::time ((time_t *) 0),
ACE_OS::getpid ());
if (connector.connect (logger, addr) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "open"), -1);
log_record.msg_data (DATA);
const size_t max_payload_size =
4 // type()
+ 8 // timestamp
+ 4 // process id
+ 4 // data length
+ ACE_Log_Record::MAXLOGMSGLEN // data
+ ACE_CDR::MAX_ALIGNMENT; // padding;
// Insert contents of <log_record> into payload stream.
ACE_OutputCDR payload (max_payload_size);
payload << log_record;
// Get the number of bytes used by the CDR stream.
ACE_CDR::ULong length = payload.total_length ();
// Send a header so the receiver can determine the byte order and
// size of the incoming CDR stream.
ACE_OutputCDR header (ACE_CDR::MAX_ALIGNMENT + 8);
header << ACE_OutputCDR::from_boolean (ACE_CDR_BYTE_ORDER);
// Store the size of the payload that follows
header << ACE_CDR::ULong (length);
// Use an iovec to send both buffer and payload simultaneously.
iovec iov[2];
iov[0].iov_base = header.begin ()->rd_ptr ();
iov[0].iov_len = 8;
iov[1].iov_base = payload.begin ()->rd_ptr ();
iov[1].iov_len = length;
if (logger.sendv_n (iov, 2) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "send"), -1);
else if (logger.close () == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "close"), -1);
#if defined (ACE_WIN32)
// !!Important, Winsock is broken in that if you don't close
// down the connection before exiting main, you'll lose data.
// More over, your server might get "Access Violation" from
// within Winsock functions.
// Here we close down the connection to Logger by redirecting
// the logging destination back to stderr.
ACE_LOG_MSG->open (0, ACE_Log_Msg::STDERR, 0);
#endif /* ACE_WIN32 */
return 0;
}
|
Java
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef SOURCE_HPP
#define SOURCE_HPP
#include <QSpinBox>
#include <QProgressBar>
#include "entity.hpp"
#include "mainwindow.hpp"
class source : virtual public entity {
public:
source(environment* env, QWidget* parent, QString name);
~source() override;
void start() override;
void add_consumer(caf::actor consumer);
protected:
// Pointer to the next stage in the pipeline.
std::vector<caf::actor> consumers_;
// Pointer to the CAF stream handler to advance the stream manually.
caf::stream_manager_ptr stream_manager_;
};
#endif // SOURCE_HPP
|
Java
|
<?php
namespace app\controllers;
use app\models\User;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\LoginForm;
use app\models\PasswordResetRequestForm;
use app\models\ResetPasswordForm;
use app\models\SignupForm;
use app\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => false,
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* @return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* @return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* @return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
public function actionControl()
{
return $this->render('control');
}
/**
* Signs user up.
*
* @return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Requests password reset.
*
* @return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* @param string $token
* @return mixed
* @throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
public function actionTest()
{
// echo 'text';
/**
* where
* ['name'=>'value'] => WHERE name = value
* 'name = :value',[':value'=>'value'] => WHERE name = value
* [[], [] ...]
* []
*
* Yii::$app->db->createCommand('')
*/
// var_dump(User::find()->where(['id'=>'2'])->asArray()->one());
// var_dump(Yii::$app->db->createCommand('SELECT * FROM user WHERE id=:id')
// ->bindValue(':id',$_GET['id'])
// ->queryOne());
$bannedUsers=User::find()->where('id>=:value and id<:value1',[':value'=>2,':value1'=>4])->asArray()->all();
foreach($bannedUsers as $user){
echo $user['username'];
echo $user['email'].'<br>';
}
}
}
|
Java
|
var $ = require('jquery');
var CoreView = require('backbone/core-view');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var REQUIRED_OPTS = [
'el'
];
module.exports = CoreView.extend({
events: {
'click .js-foo': '_fooHandler'
},
initialize: function (opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this);
this._onWindowScroll = this._onWindowScroll.bind(this);
this._topBoundary = this.$el.offset().top;
this._initBinds();
},
_initBinds: function () {
this._bindScroll();
},
_onWindowScroll: function () {
this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary);
},
_unbindScroll: function () {
$(window).unbind('scroll', this._onWindowScroll);
},
_bindScroll: function () {
this._unbindScroll();
$(window).bind('scroll', this._onWindowScroll);
},
clean: function () {
this._unbindScroll();
}
});
|
Java
|
import os
import os.path as op
import pytest
import numpy as np
from numpy.testing import (assert_array_equal, assert_equal, assert_allclose,
assert_array_less, assert_almost_equal)
import itertools
import mne
from mne.datasets import testing
from mne.fixes import _get_img_fdata
from mne import read_trans, write_trans
from mne.io import read_info
from mne.transforms import (invert_transform, _get_trans,
rotation, rotation3d, rotation_angles, _find_trans,
combine_transforms, apply_trans, translation,
get_ras_to_neuromag_trans, _pol_to_cart,
quat_to_rot, rot_to_quat, _angle_between_quats,
_find_vector_rotation, _sph_to_cart, _cart_to_sph,
_topo_to_sph, _average_quats,
_SphericalSurfaceWarp as SphericalSurfaceWarp,
rotation3d_align_z_axis, _read_fs_xfm,
_write_fs_xfm, _quat_real, _fit_matched_points,
_quat_to_euler, _euler_to_quat,
_quat_to_affine, _compute_r2, _validate_pipeline)
from mne.utils import requires_nibabel, requires_dipy
data_path = testing.data_path(download=False)
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-trans.fif')
fname_eve = op.join(data_path, 'MEG', 'sample',
'sample_audvis_trunc_raw-eve.fif')
subjects_dir = op.join(data_path, 'subjects')
fname_t1 = op.join(subjects_dir, 'fsaverage', 'mri', 'T1.mgz')
base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')
fname_trans = op.join(base_dir, 'sample-audvis-raw-trans.txt')
test_fif_fname = op.join(base_dir, 'test_raw.fif')
ctf_fname = op.join(base_dir, 'test_ctf_raw.fif')
hp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')
def test_tps():
"""Test TPS warping."""
az = np.linspace(0., 2 * np.pi, 20, endpoint=False)
pol = np.linspace(0, np.pi, 12)[1:-1]
sph = np.array(np.meshgrid(1, az, pol, indexing='ij'))
sph.shape = (3, -1)
assert_equal(sph.shape[1], 200)
source = _sph_to_cart(sph.T)
destination = source.copy()
destination *= 2
destination[:, 0] += 1
# fit with 100 points
warp = SphericalSurfaceWarp()
assert 'no ' in repr(warp)
warp.fit(source[::3], destination[::2])
assert 'oct5' in repr(warp)
destination_est = warp.transform(source)
assert_allclose(destination_est, destination, atol=1e-3)
@testing.requires_testing_data
def test_get_trans():
"""Test converting '-trans.txt' to '-trans.fif'."""
trans = read_trans(fname)
trans = invert_transform(trans) # starts out as head->MRI, so invert
trans_2 = _get_trans(fname_trans)[0]
assert trans.__eq__(trans_2, atol=1e-5)
@testing.requires_testing_data
def test_io_trans(tmpdir):
"""Test reading and writing of trans files."""
tempdir = str(tmpdir)
os.mkdir(op.join(tempdir, 'sample'))
pytest.raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
trans0 = read_trans(fname)
fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
trans0.save(fname1)
assert fname1 == _find_trans('sample', subjects_dir=tempdir)
trans1 = read_trans(fname1)
# check all properties
assert trans0 == trans1
# check reading non -trans.fif files
pytest.raises(IOError, read_trans, fname_eve)
# check warning on bad filenames
fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
with pytest.warns(RuntimeWarning, match='-trans.fif'):
write_trans(fname2, trans0)
def test_get_ras_to_neuromag_trans():
"""Test the coordinate transformation from ras to neuromag."""
# create model points in neuromag-like space
rng = np.random.RandomState(0)
anterior = [0, 1, 0]
left = [-1, 0, 0]
right = [.8, 0, 0]
up = [0, 0, 1]
rand_pts = rng.uniform(-1, 1, (3, 3))
pts = np.vstack((anterior, left, right, up, rand_pts))
# change coord system
rx, ry, rz, tx, ty, tz = rng.uniform(-2 * np.pi, 2 * np.pi, 6)
trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz))
pts_changed = apply_trans(trans, pts)
# transform back into original space
nas, lpa, rpa = pts_changed[:3]
hsp_trans = get_ras_to_neuromag_trans(nas, lpa, rpa)
pts_restored = apply_trans(hsp_trans, pts_changed)
err = "Neuromag transformation failed"
assert_allclose(pts_restored, pts, atol=1e-6, err_msg=err)
def _cartesian_to_sphere(x, y, z):
"""Convert using old function."""
hypotxy = np.hypot(x, y)
r = np.hypot(hypotxy, z)
elev = np.arctan2(z, hypotxy)
az = np.arctan2(y, x)
return az, elev, r
def _sphere_to_cartesian(theta, phi, r):
"""Convert using old function."""
z = r * np.sin(phi)
rcos_phi = r * np.cos(phi)
x = rcos_phi * np.cos(theta)
y = rcos_phi * np.sin(theta)
return x, y, z
def test_sph_to_cart():
"""Test conversion between sphere and cartesian."""
# Simple test, expected value (11, 0, 0)
r, theta, phi = 11., 0., np.pi / 2.
z = r * np.cos(phi)
rsin_phi = r * np.sin(phi)
x = rsin_phi * np.cos(theta)
y = rsin_phi * np.sin(theta)
coord = _sph_to_cart(np.array([[r, theta, phi]]))[0]
assert_allclose(coord, (x, y, z), atol=1e-7)
assert_allclose(coord, (r, 0, 0), atol=1e-7)
rng = np.random.RandomState(0)
# round-trip test
coords = rng.randn(10, 3)
assert_allclose(_sph_to_cart(_cart_to_sph(coords)), coords, atol=1e-5)
# equivalence tests to old versions
for coord in coords:
sph = _cart_to_sph(coord[np.newaxis])
cart = _sph_to_cart(sph)
sph_old = np.array(_cartesian_to_sphere(*coord))
cart_old = _sphere_to_cartesian(*sph_old)
sph_old[1] = np.pi / 2. - sph_old[1] # new convention
assert_allclose(sph[0], sph_old[[2, 0, 1]], atol=1e-7)
assert_allclose(cart[0], cart_old, atol=1e-7)
assert_allclose(cart[0], coord, atol=1e-7)
def _polar_to_cartesian(theta, r):
"""Transform polar coordinates to cartesian."""
x = r * np.cos(theta)
y = r * np.sin(theta)
return x, y
def test_polar_to_cartesian():
"""Test helper transform function from polar to cartesian."""
r = 1
theta = np.pi
# expected values are (-1, 0)
x = r * np.cos(theta)
y = r * np.sin(theta)
coord = _pol_to_cart(np.array([[r, theta]]))[0]
# np.pi is an approx since pi is irrational
assert_allclose(coord, (x, y), atol=1e-7)
assert_allclose(coord, (-1, 0), atol=1e-7)
assert_allclose(coord, _polar_to_cartesian(theta, r), atol=1e-7)
rng = np.random.RandomState(0)
r = rng.randn(10)
theta = rng.rand(10) * (2 * np.pi)
polar = np.array((r, theta)).T
assert_allclose([_polar_to_cartesian(p[1], p[0]) for p in polar],
_pol_to_cart(polar), atol=1e-7)
def _topo_to_phi_theta(theta, radius):
"""Convert using old function."""
sph_phi = (0.5 - radius) * 180
sph_theta = -theta
return sph_phi, sph_theta
def test_topo_to_sph():
"""Test topo to sphere conversion."""
rng = np.random.RandomState(0)
angles = rng.rand(10) * 360
radii = rng.rand(10)
angles[0] = 30
radii[0] = 0.25
# new way
sph = _topo_to_sph(np.array([angles, radii]).T)
new = _sph_to_cart(sph)
new[:, [0, 1]] = new[:, [1, 0]] * [-1, 1]
# old way
for ii, (angle, radius) in enumerate(zip(angles, radii)):
sph_phi, sph_theta = _topo_to_phi_theta(angle, radius)
if ii == 0:
assert_allclose(_topo_to_phi_theta(angle, radius), [45, -30])
azimuth = sph_theta / 180.0 * np.pi
elevation = sph_phi / 180.0 * np.pi
assert_allclose(sph[ii], [1., azimuth, np.pi / 2. - elevation],
atol=1e-7)
r = np.ones_like(radius)
x, y, z = _sphere_to_cartesian(azimuth, elevation, r)
pos = [-y, x, z]
if ii == 0:
expected = np.array([1. / 2., np.sqrt(3) / 2., 1.])
expected /= np.sqrt(2)
assert_allclose(pos, expected, atol=1e-7)
assert_allclose(pos, new[ii], atol=1e-7)
def test_rotation():
"""Test conversion between rotation angles and transformation matrix."""
tests = [(0, 0, 1), (.5, .5, .5), (np.pi, 0, -1.5)]
for rot in tests:
x, y, z = rot
m = rotation3d(x, y, z)
m4 = rotation(x, y, z)
assert_array_equal(m, m4[:3, :3])
back = rotation_angles(m)
assert_almost_equal(actual=back, desired=rot, decimal=12)
back4 = rotation_angles(m4)
assert_almost_equal(actual=back4, desired=rot, decimal=12)
def test_rotation3d_align_z_axis():
"""Test rotation3d_align_z_axis."""
# The more complex z axis fails the assert presumably due to tolerance
#
inp_zs = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, -1],
[-0.75071668, -0.62183808, 0.22302888]]
exp_res = [[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
[[1., 0., 0.], [0., 0., 1.], [0., -1., 0.]],
[[0., 0., 1.], [0., 1., 0.], [-1., 0., 0.]],
[[1., 0., 0.], [0., -1., 0.], [0., 0., -1.]],
[[0.53919688, -0.38169517, -0.75071668],
[-0.38169517, 0.683832, -0.62183808],
[0.75071668, 0.62183808, 0.22302888]]]
for res, z in zip(exp_res, inp_zs):
assert_allclose(res, rotation3d_align_z_axis(z), atol=1e-7)
@testing.requires_testing_data
def test_combine():
"""Test combining transforms."""
trans = read_trans(fname)
inv = invert_transform(trans)
combine_transforms(trans, inv, trans['from'], trans['from'])
pytest.raises(RuntimeError, combine_transforms, trans, inv,
trans['to'], trans['from'])
pytest.raises(RuntimeError, combine_transforms, trans, inv,
trans['from'], trans['to'])
pytest.raises(RuntimeError, combine_transforms, trans, trans,
trans['from'], trans['to'])
def test_quaternions():
"""Test quaternion calculations."""
rots = [np.eye(3)]
for fname in [test_fif_fname, ctf_fname, hp_fif_fname]:
rots += [read_info(fname)['dev_head_t']['trans'][:3, :3]]
# nasty numerical cases
rots += [np.array([
[-0.99978541, -0.01873462, -0.00898756],
[-0.01873462, 0.62565561, 0.77987608],
[-0.00898756, 0.77987608, -0.62587152],
])]
rots += [np.array([
[0.62565561, -0.01873462, 0.77987608],
[-0.01873462, -0.99978541, -0.00898756],
[0.77987608, -0.00898756, -0.62587152],
])]
rots += [np.array([
[-0.99978541, -0.00898756, -0.01873462],
[-0.00898756, -0.62587152, 0.77987608],
[-0.01873462, 0.77987608, 0.62565561],
])]
for rot in rots:
assert_allclose(rot, quat_to_rot(rot_to_quat(rot)),
rtol=1e-5, atol=1e-5)
rot = rot[np.newaxis, np.newaxis, :, :]
assert_allclose(rot, quat_to_rot(rot_to_quat(rot)),
rtol=1e-5, atol=1e-5)
# let's make sure our angle function works in some reasonable way
for ii in range(3):
for jj in range(3):
a = np.zeros(3)
b = np.zeros(3)
a[ii] = 1.
b[jj] = 1.
expected = np.pi if ii != jj else 0.
assert_allclose(_angle_between_quats(a, b), expected, atol=1e-5)
y_180 = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1.]])
assert_allclose(_angle_between_quats(rot_to_quat(y_180),
np.zeros(3)), np.pi)
h_180_attitude_90 = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1.]])
assert_allclose(_angle_between_quats(rot_to_quat(h_180_attitude_90),
np.zeros(3)), np.pi)
def test_vector_rotation():
"""Test basic rotation matrix math."""
x = np.array([1., 0., 0.])
y = np.array([0., 1., 0.])
rot = _find_vector_rotation(x, y)
assert_array_equal(rot,
[[0, -1, 0], [1, 0, 0], [0, 0, 1]])
quat_1 = rot_to_quat(rot)
quat_2 = rot_to_quat(np.eye(3))
assert_allclose(_angle_between_quats(quat_1, quat_2), np.pi / 2.)
def test_average_quats():
"""Test averaging of quaternions."""
sq2 = 1. / np.sqrt(2.)
quats = np.array([[0, sq2, sq2],
[0, sq2, sq2],
[0, sq2, 0],
[0, 0, sq2],
[sq2, 0, 0]], float)
# In MATLAB:
# quats = [[0, sq2, sq2, 0]; [0, sq2, sq2, 0];
# [0, sq2, 0, sq2]; [0, 0, sq2, sq2]; [sq2, 0, 0, sq2]];
expected = [quats[0],
quats[0],
[0, 0.788675134594813, 0.577350269189626],
[0, 0.657192299694123, 0.657192299694123],
[0.100406058540540, 0.616329446922803, 0.616329446922803]]
# Averaging the first two should give the same thing:
for lim, ex in enumerate(expected):
assert_allclose(_average_quats(quats[:lim + 1]), ex, atol=1e-7)
quats[1] *= -1 # same quaternion (hidden value is zero here)!
rot_0, rot_1 = quat_to_rot(quats[:2])
assert_allclose(rot_0, rot_1, atol=1e-7)
for lim, ex in enumerate(expected):
assert_allclose(_average_quats(quats[:lim + 1]), ex, atol=1e-7)
# Assert some symmetry
count = 0
extras = [[sq2, sq2, 0]] + list(np.eye(3))
for quat in np.concatenate((quats, expected, extras)):
if np.isclose(_quat_real(quat), 0., atol=1e-7): # can flip sign
count += 1
angle = _angle_between_quats(quat, -quat)
assert_allclose(angle, 0., atol=1e-7)
rot_0, rot_1 = quat_to_rot(np.array((quat, -quat)))
assert_allclose(rot_0, rot_1, atol=1e-7)
assert count == 4 + len(extras)
@testing.requires_testing_data
@pytest.mark.parametrize('subject', ('fsaverage', 'sample'))
def test_fs_xfm(subject, tmpdir):
"""Test reading and writing of Freesurfer transforms."""
fname = op.join(data_path, 'subjects', subject, 'mri', 'transforms',
'talairach.xfm')
xfm, kind = _read_fs_xfm(fname)
if subject == 'fsaverage':
assert_allclose(xfm, np.eye(4), atol=1e-5) # fsaverage is in MNI
assert kind == 'MNI Transform File'
tempdir = str(tmpdir)
fname_out = op.join(tempdir, 'out.xfm')
_write_fs_xfm(fname_out, xfm, kind)
xfm_read, kind_read = _read_fs_xfm(fname_out)
assert kind_read == kind
assert_allclose(xfm, xfm_read, rtol=1e-5, atol=1e-5)
# Some wacky one
xfm[:3] = np.random.RandomState(0).randn(3, 4)
_write_fs_xfm(fname_out, xfm, 'foo')
xfm_read, kind_read = _read_fs_xfm(fname_out)
assert kind_read == 'foo'
assert_allclose(xfm, xfm_read, rtol=1e-5, atol=1e-5)
# degenerate conditions
with open(fname_out, 'w') as fid:
fid.write('foo')
with pytest.raises(ValueError, match='Failed to find'):
_read_fs_xfm(fname_out)
_write_fs_xfm(fname_out, xfm[:2], 'foo')
with pytest.raises(ValueError, match='Could not find'):
_read_fs_xfm(fname_out)
@pytest.fixture()
def quats():
"""Make some unit quats."""
quats = np.random.RandomState(0).randn(5, 3)
quats[:, 0] = 0 # identity
quats /= 2 * np.linalg.norm(quats, axis=1, keepdims=True) # some real part
return quats
def _check_fit_matched_points(
p, x, weights, do_scale, angtol=1e-5, dtol=1e-5, stol=1e-7):
__tracebackhide__ = True
mne.coreg._ALLOW_ANALITICAL = False
try:
params = mne.coreg.fit_matched_points(
p, x, weights=weights, scale=do_scale, out='params')
finally:
mne.coreg._ALLOW_ANALITICAL = True
quat_an, scale_an = _fit_matched_points(p, x, weights, scale=do_scale)
assert len(params) == 6 + int(do_scale)
q_co = _euler_to_quat(params[:3])
translate_co = params[3:6]
angle = np.rad2deg(_angle_between_quats(quat_an[:3], q_co))
dist = np.linalg.norm(quat_an[3:] - translate_co)
assert 0 <= angle < angtol, 'angle'
assert 0 <= dist < dtol, 'dist'
if do_scale:
scale_co = params[6]
assert_allclose(scale_an, scale_co, rtol=stol, err_msg='scale')
# errs
trans = _quat_to_affine(quat_an)
trans[:3, :3] *= scale_an
weights = np.ones(1) if weights is None else weights
err_an = np.linalg.norm(
weights[:, np.newaxis] * apply_trans(trans, p) - x)
trans = mne.coreg._trans_from_params((True, True, do_scale), params)
err_co = np.linalg.norm(
weights[:, np.newaxis] * apply_trans(trans, p) - x)
if err_an > 1e-14:
assert err_an < err_co * 1.5
return quat_an, scale_an
@pytest.mark.parametrize('scaling', [0.25, 1])
@pytest.mark.parametrize('do_scale', (True, False))
def test_fit_matched_points(quats, scaling, do_scale):
"""Test analytical least-squares matched point fitting."""
if scaling != 1 and not do_scale:
return # no need to test this, it will not be good
rng = np.random.RandomState(0)
fro = rng.randn(10, 3)
translation = rng.randn(3)
for qi, quat in enumerate(quats):
to = scaling * np.dot(quat_to_rot(quat), fro.T).T + translation
for corrupted in (False, True):
# mess up a point
if corrupted:
to[0, 2] += 100
weights = np.ones(len(to))
weights[0] = 0
else:
weights = None
est, scale_est = _check_fit_matched_points(
fro, to, weights=weights, do_scale=do_scale)
assert_allclose(scale_est, scaling, rtol=1e-5)
assert_allclose(est[:3], quat, atol=1e-14)
assert_allclose(est[3:], translation, atol=1e-14)
# if we don't adjust for the corruption above, it should get worse
angle = dist = None
for weighted in (False, True):
if not weighted:
weights = None
dist_bounds = (5, 20)
if scaling == 1:
angle_bounds = (5, 95)
angtol, dtol, stol = 1, 15, 3
else:
angle_bounds = (5, 105)
angtol, dtol, stol = 20, 15, 3
else:
weights = np.ones(len(to))
weights[0] = 10 # weighted=True here means "make it worse"
angle_bounds = (angle, 180) # unweighted values as new min
dist_bounds = (dist, 100)
if scaling == 1:
# XXX this angtol is not great but there is a hard to
# identify linalg/angle calculation bug on Travis...
angtol, dtol, stol = 180, 70, 3
else:
angtol, dtol, stol = 50, 70, 3
est, scale_est = _check_fit_matched_points(
fro, to, weights=weights, do_scale=do_scale,
angtol=angtol, dtol=dtol, stol=stol)
assert not np.allclose(est[:3], quat, atol=1e-5)
assert not np.allclose(est[3:], translation, atol=1e-5)
angle = np.rad2deg(_angle_between_quats(est[:3], quat))
assert_array_less(angle_bounds[0], angle)
assert_array_less(angle, angle_bounds[1])
dist = np.linalg.norm(est[3:] - translation)
assert_array_less(dist_bounds[0], dist)
assert_array_less(dist, dist_bounds[1])
def test_euler(quats):
"""Test euler transformations."""
euler = _quat_to_euler(quats)
quats_2 = _euler_to_quat(euler)
assert_allclose(quats, quats_2, atol=1e-14)
quat_rot = quat_to_rot(quats)
euler_rot = np.array([rotation(*e)[:3, :3] for e in euler])
assert_allclose(quat_rot, euler_rot, atol=1e-14)
@requires_nibabel()
@requires_dipy()
@pytest.mark.slowtest
@testing.requires_testing_data
def test_volume_registration():
"""Test volume registration."""
import nibabel as nib
from dipy.align import resample
T1 = nib.load(fname_t1)
affine = np.eye(4)
affine[0, 3] = 10
T1_resampled = resample(moving=T1.get_fdata(),
static=T1.get_fdata(),
moving_affine=T1.affine,
static_affine=T1.affine,
between_affine=np.linalg.inv(affine))
for pipeline in ('rigids', ('translation', 'sdr')):
reg_affine, sdr_morph = mne.transforms.compute_volume_registration(
T1_resampled, T1, pipeline=pipeline, zooms=10, niter=[5])
assert_allclose(affine, reg_affine, atol=0.25)
T1_aligned = mne.transforms.apply_volume_registration(
T1_resampled, T1, reg_affine, sdr_morph)
r2 = _compute_r2(_get_img_fdata(T1_aligned), _get_img_fdata(T1))
assert 99.9 < r2
# check that all orders of the pipeline work
for pipeline_len in range(1, 5):
for pipeline in itertools.combinations(
('translation', 'rigid', 'affine', 'sdr'), pipeline_len):
_validate_pipeline(pipeline)
_validate_pipeline(list(pipeline))
with pytest.raises(ValueError, match='Steps in pipeline are out of order'):
_validate_pipeline(('sdr', 'affine'))
with pytest.raises(ValueError,
match='Steps in pipeline should not be repeated'):
_validate_pipeline(('affine', 'affine'))
|
Java
|
/**
* CArtAgO - DEIS, University of Bologna
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package cartago;
/**
* Unique identifier of an operation (instance)
* executed by an artifact
*
* @author aricci
*
*/
public class OpId implements java.io.Serializable {
private int id;
private ArtifactId aid;
private AgentId agentId;
private String opName;
OpId(ArtifactId aid, String opName, int id, AgentId ctxId){
this.id = id;
this.aid = aid;
this.agentId = ctxId;
this.opName = opName;
}
/**
* Get the numeric identifier of the operation id
*
* @return
*/
public int getId(){
return id;
}
/**
* Get the operation name.
*
* @return
*/
public String getOpName(){
return opName;
}
/**
* Get the id of the artifact where the operation has been executed
*
* @return
*/
public ArtifactId getArtifactId(){
return aid;
}
/**
* Get the identifier of the agent performer of the operation
*
* @return
*/
public AgentId getAgentBodyId(){
return agentId;
}
AgentId getContextId(){
return agentId;
}
public boolean equals(Object obj){
return aid.equals(((OpId)obj).aid) && ((OpId)obj).id==id;
}
public String toString(){
return "opId("+id+","+opName+","+aid+","+agentId+")";
}
}
|
Java
|
<!DOCTYPE html>
<html lang="en" itemscope itemtype="https://schema.org/WebPage">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vitess / GitHub Workflow</title>
<!-- Webfont -->
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<!--<link rel="shortcut icon" type="image/png" href="/favicon.png">-->
<!-- Bootstrap -->
<link href="/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/css/site.css" />
<!-- Font Awesome icons -->
<link href="/libs/font-awesome-4.4.0/css/font-awesome.min.css"
rel="stylesheet"
type="text/css">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/libs/bootstrap/js/bootstrap.min.js"></script>
<!-- metadata -->
<meta name="og:title" content="Vitess / GitHub Workflow"/>
<meta name="og:image" content="/images/vitess_logomark_cropped.svg"/>
<meta name="og:description" content="Vitess is a database clustering system for horizontal scaling of MySQL."/>
<link rel="icon" href="/images/vitess_icon.png" type="image/png">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-60219601-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body class="docs" id="top_of_page">
<span id="toc-depth" data-toc-depth="h2,h3"></span>
<nav id="common-nav" class="navbar navbar-fixed-top inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">
<img class="logo" src="/images/vitess_logomark_cropped.svg" alt="Vitess">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav navbar-right" id="standard-menu-links">
<li><a href="/overview/">Overview</a></li>
<li><a href="/user-guide/introduction.html">Guides</a></li>
<li><a href="/reference/vitess-api.html">Reference</a></li>
<li><a href="http://blog.vitess.io">Blog</a></li>
<li><a href="https://github.com/youtube/vitess"><i class="fa fa-github"></i> GitHub</a></li>
<!-- Hide link to blog unless we have actual posts -->
<!-- <li><a href="/blog/" title="">Blog</a></li> -->
</ul>
<ul class="nav nav-stacked mobile-left-nav-menu" id="collapsed-left-menu">
<li class="submenu">
<h4 class="arrow-r no-top-margin">Overview</h4>
<ul style="display: none">
<li><a href="/overview/">What is Vitess</a></li>
<li><a href="/overview/scaling-mysql.html">Scaling MySQL with Vitess</a></li>
<li><a href="/overview/concepts.html">Key Concepts</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Getting Started</h4>
<ul style="display: none">
<li style="padding-bottom: 0"><a href="/getting-started/">Run Vitess on Kubernetes</a>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/getting-started/docker-build.html">Custom Docker Build</a></li>
</ul>
</li>
<li><a href="/getting-started/local-instance.html">Run Vitess Locally</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">User Guide</h4>
<ul style="display: none">
<li><a href="/user-guide/introduction.html">Introduction</a>
<li><a href="/user-guide/client-libraries.html">Client Libraries</a>
<li><a href="/user-guide/backup-and-restore.html">Backing Up Data</a>
<li><a href="/user-guide/reparenting.html">Reparenting</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/schema-management.html">Schema Management</a></li>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/user-guide/pivot-schema-changes.html">Pivot Schema Changes (Tutorial)</a></li>
</ul>
<li style="padding-bottom: 0"><a href="/user-guide/sharding.html">Sharding</a>
<ul style="display: block">
<li><a href="/user-guide/horizontal-sharding.html">Horizontal Sharding (Codelab)</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/sharding-kubernetes.html">Sharding in Kubernetes (Codelab)</a></li>
</ul>
</li>
<li><a href="/user-guide/vitess-replication.html">Vitess and Replication</a></li>
<li><a href="/user-guide/topology-service.html">Topology Service</a></li>
<li><a href="/user-guide/transport-security-model.html">Transport Security Model</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/launching.html">Launching</a>
<ul style="display: block">
<li><a href="/user-guide/scalability-philosophy.html">Scalability Philosophy</a></li>
<li><a href="/user-guide/production-planning.html">Production Planning</a></li>
<li><a href="/user-guide/server-configuration.html">Server Configuration</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/troubleshooting.html">Troubleshooting</a></li>
</ul>
</li>
<li><a href="/user-guide/upgrading.html">Upgrading</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Reference Guides</h4>
<ul style="display: none">
<li><a href="/reference/vitess-api.html">Vitess API</a>
<li><a href="/reference/vtctl.html">vtctl Commands</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Other Resources</h4>
<ul style="display: none">
<li><a href="/resources/presentations.html">Presentations</a>
<li><a href="http://blog.vitess.io/">Blog</a>
<li><a href="/resources/roadmap.html">Roadmap</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Contributing</h4>
<ul style="display: none">
<li><a href="/contributing/">Contributing to Vitess</a>
<li><a href="/contributing/github-workflow.html">GitHub Workflow</a>
<li><a href="/contributing/code-reviews.html">Code Reviews</a>
</ul>
</li>
<div>
<form method="get" action="/search/">
<input id="search-form" name="q" type="text" placeholder="Search">
</form>
</div>
<li><a href="https://github.com/youtube/vitess" id="collapsed-left-menu-repo-link"><i class="fa fa-github"></i> GitHub</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div id="masthead">
<div class="container">
<div class="row">
<div class="col-md-9">
<h1>GitHub Workflow</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row scroll-margin" id="toc-content-row">
<div class="col-md-2" id="leftCol">
<ul class="nav nav-stacked mobile-left-nav-menu" id="sidebar">
<li class="submenu">
<h4 class="arrow-r no-top-margin">Overview</h4>
<ul style="display: none">
<li><a href="/overview/">What is Vitess</a></li>
<li><a href="/overview/scaling-mysql.html">Scaling MySQL with Vitess</a></li>
<li><a href="/overview/concepts.html">Key Concepts</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Getting Started</h4>
<ul style="display: none">
<li style="padding-bottom: 0"><a href="/getting-started/">Run Vitess on Kubernetes</a>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/getting-started/docker-build.html">Custom Docker Build</a></li>
</ul>
</li>
<li><a href="/getting-started/local-instance.html">Run Vitess Locally</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">User Guide</h4>
<ul style="display: none">
<li><a href="/user-guide/introduction.html">Introduction</a>
<li><a href="/user-guide/client-libraries.html">Client Libraries</a>
<li><a href="/user-guide/backup-and-restore.html">Backing Up Data</a>
<li><a href="/user-guide/reparenting.html">Reparenting</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/schema-management.html">Schema Management</a></li>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/user-guide/pivot-schema-changes.html">Pivot Schema Changes (Tutorial)</a></li>
</ul>
<li style="padding-bottom: 0"><a href="/user-guide/sharding.html">Sharding</a>
<ul style="display: block">
<li><a href="/user-guide/horizontal-sharding.html">Horizontal Sharding (Codelab)</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/sharding-kubernetes.html">Sharding in Kubernetes (Codelab)</a></li>
</ul>
</li>
<li><a href="/user-guide/vitess-replication.html">Vitess and Replication</a></li>
<li><a href="/user-guide/topology-service.html">Topology Service</a></li>
<li><a href="/user-guide/transport-security-model.html">Transport Security Model</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/launching.html">Launching</a>
<ul style="display: block">
<li><a href="/user-guide/scalability-philosophy.html">Scalability Philosophy</a></li>
<li><a href="/user-guide/production-planning.html">Production Planning</a></li>
<li><a href="/user-guide/server-configuration.html">Server Configuration</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/troubleshooting.html">Troubleshooting</a></li>
</ul>
</li>
<li><a href="/user-guide/upgrading.html">Upgrading</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Reference Guides</h4>
<ul style="display: none">
<li><a href="/reference/vitess-api.html">Vitess API</a>
<li><a href="/reference/vtctl.html">vtctl Commands</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Other Resources</h4>
<ul style="display: none">
<li><a href="/resources/presentations.html">Presentations</a>
<li><a href="http://blog.vitess.io/">Blog</a>
<li><a href="/resources/roadmap.html">Roadmap</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Contributing</h4>
<ul style="display: none">
<li><a href="/contributing/">Contributing to Vitess</a>
<li><a href="/contributing/github-workflow.html">GitHub Workflow</a>
<li><a href="/contributing/code-reviews.html">Code Reviews</a>
</ul>
</li>
<div>
<form method="get" action="/search/">
<input id="search-form" name="q" type="text" placeholder="Search">
</form>
</div>
</ul>
</div>
<div class="col-md-3" id="rightCol">
<div class="nav nav-stacked" id="tocSidebar">
<div id="toc"></div>
</div>
</div>
<div class="col-md-7" id="centerCol">
<div id="centerTextCol">
<h1 id="github-workflow">GitHub Workflow</h1>
<p>If you are new to Git and GitHub, we recommend to read this page. Otherwise, you may skip it.</p>
<p>Our GitHub workflow is a so called triangular workflow:</p>
<p><img src="https://cloud.githubusercontent.com/assets/1319791/8943755/5dcdcae4-354a-11e5-9f82-915914fad4f7.png" alt="visualization of the GitHub triangular workflow" style="width: 100%;"/></p>
<p><em>Image Source:</em> <a href="https://github.com/blog/2042-git-2-5-including-multiple-worktrees-and-triangular-workflows">https://github.com/blog/2042-git-2-5-including-multiple-worktrees-and-triangular-workflows</a></p>
<p>You develop and commit your changes in a clone of our upstream repository
(<code class="prettyprint">local</code>). Then you push your changes to your forked repository (<code class="prettyprint">origin</code>) and
send us a pull request. Eventually, we will merge your pull request back into
the <code class="prettyprint">upstream</code> repository.</p>
<h2 id="remotes">Remotes</h2>
<p>Since you should have cloned the repository from your fork, the <code class="prettyprint">origin</code> remote
should look like this:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git remote -v
origin git@github.com:<yourname>/vitess.git (fetch)
origin git@github.com:<yourname>/vitess.git (push)
</code></pre></div>
<p>To help you keep your fork in sync with the main repo, add an <code class="prettyprint">upstream</code> remote:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git remote add upstream git@github.com:youtube/vitess.git
$ git remote -v
origin git@github.com:<yourname>/vitess.git (fetch)
origin git@github.com:<yourname>/vitess.git (push)
upstream git@github.com:youtube/vitess.git (fetch)
upstream git@github.com:youtube/vitess.git (push)
</code></pre></div>
<p>Now to sync your local <code class="prettyprint">master</code> branch, do this:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout master
(master) $ git pull upstream master
</code></pre></div>
<p>Note: In the example output above we prefixed the prompt with <code class="prettyprint">(master)</code> to
stress the fact that the command must be run from the branch <code class="prettyprint">master</code>.</p>
<p>You can omit the <code class="prettyprint">upstream master</code> from the <code class="prettyprint">git pull</code> command when you let your
<code class="prettyprint">master</code> branch always track the main <code class="prettyprint">youtube/vitess</code> repository. To achieve
this, run this command once:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(master) $ git branch --set-upstream-to=upstream/master
</code></pre></div>
<p>Now the following command syncs your local <code class="prettyprint">master</code> branch as well:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(master) $ git pull
</code></pre></div>
<h2 id="topic-branches">Topic Branches</h2>
<p>Before you start working on changes, create a topic branch:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout master
(master) $ git pull
(master) $ git checkout -b new-feature
(new-feature) $ # You are now in the new-feature branch.
</code></pre></div>
<p>Try to commit small pieces along the way as you finish them, with an explanation
of the changes in the commit message. As you work in a package, you can run just
the unit tests for that package by running <code class="prettyprint">go test</code> from within that package.</p>
<p>When you're ready to test the whole system, run the full test suite with <code class="prettyprint">make
test</code> from the root of the Git tree.
If you haven't installed all dependencies for <code class="prettyprint">make test</code>, you can rely on the Travis CI test results as well.
These results will be linked on your pull request.</p>
<h2 id="sending-pull-requests">Sending Pull Requests</h2>
<p>Push your branch to the repository (and set it to track with <code class="prettyprint">-u</code>):</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(new-feature) $ git push -u origin new-feature
</code></pre></div>
<p>You can omit <code class="prettyprint">origin</code> and <code class="prettyprint">-u new-feature</code> parameters from the <code class="prettyprint">git push</code>
command with the following two Git configuration changes:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git config remote.pushdefault origin
$ git config push.default current
</code></pre></div>
<p>The first setting saves you from typing <code class="prettyprint">origin</code> every time. And with the second
setting, Git assumes that the remote branch on the GitHub side will have the
same name as your local branch.</p>
<p>After this change, you can run <code class="prettyprint">git push</code> without arguments:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(new-feature) $ git push
</code></pre></div>
<p>Then go to the <a href="https://github.com/youtube/vitess">repository page</a> and it
should prompt you to create a Pull Request from a branch you recently pushed.
You can also <a href="https://github.com/youtube/vitess/compare">choose a branch manually</a>.</p>
<h2 id="addressing-changes">Addressing Changes</h2>
<p>If you need to make changes in response to the reviewer's comments, just make
another commit on your branch and then push it again:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout new-feature
(new-feature) $ git commit
(new-feature) $ git push
</code></pre></div>
<p>That is because a pull request always mirrors all commits from your topic branch which are not in the master branch.</p>
<p>After you merge, close the issue (if it wasn't automatically closed) and delete
the topic branch.</p>
</div>
</div>
</div>
</div>
<div class="page-spacer"></div>
<footer role="contentinfo" id="site-footer">
<nav role="navigation" class="menu bottom-menu">
<a href="https://groups.google.com/forum/#!forum/vitess" target="_blank">Contact: vitess@googlegroups.com</a> <b>·</b>
<a href="https://groups.google.com/forum/#!forum/vitess-announce" target="_blank">Announcements</a> <b>·</b>
© 2016 <a href="/">Vitess</a> powered by <a href="https://developers.google.com/open-source/">Google Inc</a>
</nav>
</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> -->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<!--
<script src="/libs/bootstrap/js/bootstrap.min.js"></script>
-->
<!-- Include the common site javascript -->
<script src="/js/common.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
|
Java
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20131203141255) do
create_table "alchemy_attachments", :force => true do |t|
t.string "name"
t.string "file_name"
t.string "file_mime_type"
t.integer "file_size"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.text "cached_tag_list"
t.string "file_uid"
end
add_index "alchemy_attachments", ["file_uid"], :name => "index_alchemy_attachments_on_file_uid"
create_table "alchemy_cells", :force => true do |t|
t.integer "page_id"
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_contents", :force => true do |t|
t.string "name"
t.string "essence_type"
t.integer "essence_id"
t.integer "element_id"
t.integer "position"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "alchemy_contents", ["element_id", "position"], :name => "index_contents_on_element_id_and_position"
create_table "alchemy_elements", :force => true do |t|
t.string "name"
t.integer "position"
t.integer "page_id"
t.boolean "public", :default => true
t.boolean "folded", :default => false
t.boolean "unique", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.integer "cell_id"
t.text "cached_tag_list"
end
add_index "alchemy_elements", ["page_id", "position"], :name => "index_elements_on_page_id_and_position"
create_table "alchemy_elements_alchemy_pages", :id => false, :force => true do |t|
t.integer "element_id"
t.integer "page_id"
end
create_table "alchemy_essence_booleans", :force => true do |t|
t.boolean "value"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "alchemy_essence_booleans", ["value"], :name => "index_alchemy_essence_booleans_on_value"
create_table "alchemy_essence_dates", :force => true do |t|
t.datetime "date"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_essence_files", :force => true do |t|
t.integer "attachment_id"
t.string "title"
t.string "css_class"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_essence_htmls", :force => true do |t|
t.text "source"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_essence_links", :force => true do |t|
t.string "link"
t.string "link_title"
t.string "link_target"
t.string "link_class_name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
create_table "alchemy_essence_pictures", :force => true do |t|
t.integer "picture_id"
t.string "caption"
t.string "title"
t.string "alt_tag"
t.string "link"
t.string "link_class_name"
t.string "link_title"
t.string "css_class"
t.string "link_target"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "crop_from"
t.string "crop_size"
t.string "render_size"
end
create_table "alchemy_essence_richtexts", :force => true do |t|
t.text "body"
t.text "stripped_body"
t.boolean "do_not_index", :default => false
t.boolean "public"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_essence_selects", :force => true do |t|
t.string "value"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "alchemy_essence_selects", ["value"], :name => "index_alchemy_essence_selects_on_value"
create_table "alchemy_essence_texts", :force => true do |t|
t.text "body"
t.string "link"
t.string "link_title"
t.string "link_class_name"
t.boolean "public", :default => false
t.boolean "do_not_index", :default => false
t.string "link_target"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_folded_pages", :force => true do |t|
t.integer "page_id"
t.integer "user_id"
t.boolean "folded", :default => false
end
create_table "alchemy_languages", :force => true do |t|
t.string "name"
t.string "language_code"
t.string "frontpage_name"
t.string "page_layout", :default => "intro"
t.boolean "public", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.boolean "default", :default => false
t.string "country_code", :default => "", :null => false
t.integer "site_id"
end
add_index "alchemy_languages", ["language_code", "country_code"], :name => "index_alchemy_languages_on_language_code_and_country_code"
add_index "alchemy_languages", ["language_code"], :name => "index_alchemy_languages_on_language_code"
add_index "alchemy_languages", ["site_id"], :name => "index_alchemy_languages_on_site_id"
create_table "alchemy_legacy_page_urls", :force => true do |t|
t.string "urlname", :null => false
t.integer "page_id", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "alchemy_legacy_page_urls", ["urlname"], :name => "index_alchemy_legacy_page_urls_on_urlname"
create_table "alchemy_pages", :force => true do |t|
t.string "name"
t.string "urlname"
t.string "title"
t.string "language_code"
t.boolean "language_root"
t.string "page_layout"
t.text "meta_keywords"
t.text "meta_description"
t.integer "lft"
t.integer "rgt"
t.integer "parent_id"
t.integer "depth"
t.boolean "visible", :default => false
t.boolean "public", :default => false
t.boolean "locked", :default => false
t.integer "locked_by"
t.boolean "restricted", :default => false
t.boolean "robot_index", :default => true
t.boolean "robot_follow", :default => true
t.boolean "sitemap", :default => true
t.boolean "layoutpage", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.integer "language_id"
t.text "cached_tag_list"
end
add_index "alchemy_pages", ["language_id"], :name => "index_pages_on_language_id"
add_index "alchemy_pages", ["parent_id", "lft"], :name => "index_pages_on_parent_id_and_lft"
add_index "alchemy_pages", ["urlname"], :name => "index_pages_on_urlname"
create_table "alchemy_pictures", :force => true do |t|
t.string "name"
t.string "image_file_name"
t.integer "image_file_width"
t.integer "image_file_height"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.string "upload_hash"
t.text "cached_tag_list"
t.string "image_file_uid"
t.integer "image_file_size"
end
create_table "alchemy_sites", :force => true do |t|
t.string "host"
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "public", :default => false
t.text "aliases"
t.boolean "redirect_to_primary_host"
end
add_index "alchemy_sites", ["host", "public"], :name => "alchemy_sites_public_hosts_idx"
add_index "alchemy_sites", ["host"], :name => "index_alchemy_sites_on_host"
create_table "alchemy_users", :force => true do |t|
t.string "firstname"
t.string "lastname"
t.string "login"
t.string "email"
t.string "gender"
t.string "roles", :default => "registered"
t.string "language"
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "password_salt", :limit => 128, :default => "", :null => false
t.integer "sign_in_count", :default => 0, :null => false
t.integer "failed_attempts", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.text "cached_tag_list"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
end
add_index "alchemy_users", ["email"], :name => "index_alchemy_users_on_email", :unique => true
add_index "alchemy_users", ["login"], :name => "index_alchemy_users_on_login", :unique => true
add_index "alchemy_users", ["reset_password_token"], :name => "index_alchemy_users_on_reset_password_token", :unique => true
add_index "alchemy_users", ["roles"], :name => "index_alchemy_users_on_roles"
create_table "events", :force => true do |t|
t.string "name"
t.string "hidden_name"
t.datetime "starts_at"
t.datetime "ends_at"
t.text "description"
t.decimal "entrance_fee", :precision => 6, :scale => 2
t.boolean "published"
t.integer "location_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "locations", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", :force => true do |t|
t.string "name"
end
end
|
Java
|
package team.gif;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import team.gif.commands.*;
public class OI {
public static final Joystick leftStick = new Joystick(1);
public static final rightStick = new Joystick(2);
public static final auxStick = new Joystick(3);
private final Button leftTrigger = new JoystickButton(leftStick, 1);
private final Button right2 = new JoystickButton(rightStick, 2);
private final Button right3 = new JoystickButton(rightStick, 3);
private final Button right6 = new JoystickButton(rightStick, 6);
private final Button right7 = new JoystickButton(rightStick, 7);
public static final Button auxTrigger = new JoystickButton(rightStick, 1);
public OI() {
leftTrigger.whileHeld(new ShifterHigh());
right2.whileHeld(new CollectorReceive());
right2.whenPressed(new EarsOpen());
right3.whileHeld(new CollectorPass());
right3.whenPressed(new EarsOpen());
right3.whenReleased(new CollectorStandby());
right3.whenReleased(new EarsClosed());
right6.whileHeld(new BumperUp());
right7.whileHeld(new CollectorRaise());
}
}
|
Java
|
<?php
namespace app\modules\currency\models\ar;
/**
* This is the model class for table "currency".
*
* @property integer $id
* @property string $code
* @property string $short_name
* @property string $sign
*/
class Currency extends \app\modules\core\db\ActiveRecord
{
const EUR = 'EUR';
const RUB = 'RUB';
const UAH = 'UAH';
const USD = 'USD';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'currency';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['code', 'short_name'], 'required'],
[['code'], 'string', 'max' => 3],
[['sign'], 'string', 'max' => 12],
[['short_name'], 'string', 'max' => 8],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'code' => 'Код',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRates()
{
return $this->hasMany(CurrencyRate::className(), ['src_id' => 'id']);
}
/**
* Returns currency symbol by its code.
* @param string $code
* @return string mixed
*/
public static function getSignByCode($code)
{
$signs = [self::UAH => '₴', self::USD => '$', self::EUR => '€', self::RUB => '₽'];
return $signs[$code];
}
/**
* Returns full currency name in prepositional case.
* @param string $code
* @return string
*/
public static function getFullPrepositionalName($code)
{
$signs = [self::UAH => 'гривнах', self::USD => 'долларах', self::EUR => 'евро', self::RUB => 'рублях'];
return $signs[$code];
}
}
|
Java
|
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from brambling.utils.payment import dwolla_update_tokens
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--days',
action='store',
dest='days',
default=15,
help='Number of days ahead of time to update refresh tokens.'),
)
def handle(self, *args, **options):
try:
days = int(options['days'])
except ValueError:
raise CommandError("Days must be an integer value.")
self.stdout.write("Updating dwolla tokens...")
self.stdout.flush()
count, test_count = dwolla_update_tokens(days)
self.stdout.write("Test tokens updated: {}".format(count))
self.stdout.write("Live tokens updated: {}".format(test_count))
self.stdout.flush()
|
Java
|
# -*- coding: utf-8 -*-
"""
.. _tut-set-eeg-ref:
Setting the EEG reference
=========================
This tutorial describes how to set or change the EEG reference in MNE-Python.
.. contents:: Page contents
:local:
:depth: 2
As usual we'll start by importing the modules we need, loading some
:ref:`example data <sample-dataset>`, and cropping it to save memory. Since
this tutorial deals specifically with EEG, we'll also restrict the dataset to
just a few EEG channels so the plots are easier to see:
"""
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60).load_data()
raw.pick(['EEG 0{:02}'.format(n) for n in range(41, 60)])
###############################################################################
# Background
# ^^^^^^^^^^
#
# EEG measures a voltage (difference in electric potential) between each
# electrode and a reference electrode. This means that whatever signal is
# present at the reference electrode is effectively subtracted from all the
# measurement electrodes. Therefore, an ideal reference signal is one that
# captures *none* of the brain-specific fluctuations in electric potential,
# while capturing *all* of the environmental noise/interference that is being
# picked up by the measurement electrodes.
#
# In practice, this means that the reference electrode is often placed in a
# location on the subject's body and close to their head (so that any
# environmental interference affects the reference and measurement electrodes
# similarly) but as far away from the neural sources as possible (so that the
# reference signal doesn't pick up brain-based fluctuations). Typical reference
# locations are the subject's earlobe, nose, mastoid process, or collarbone.
# Each of these has advantages and disadvantages regarding how much brain
# signal it picks up (e.g., the mastoids pick up a fair amount compared to the
# others), and regarding the environmental noise it picks up (e.g., earlobe
# electrodes may shift easily, and have signals more similar to electrodes on
# the same side of the head).
#
# Even in cases where no electrode is specifically designated as the reference,
# EEG recording hardware will still treat one of the scalp electrodes as the
# reference, and the recording software may or may not display it to you (it
# might appear as a completely flat channel, or the software might subtract out
# the average of all signals before displaying, making it *look like* there is
# no reference).
#
#
# Setting or changing the reference channel
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# If you want to recompute your data with a different reference than was used
# when the raw data were recorded and/or saved, MNE-Python provides the
# :meth:`~mne.io.Raw.set_eeg_reference` method on :class:`~mne.io.Raw` objects
# as well as the :func:`mne.add_reference_channels` function. To use an
# existing channel as the new reference, use the
# :meth:`~mne.io.Raw.set_eeg_reference` method; you can also designate multiple
# existing electrodes as reference channels, as is sometimes done with mastoid
# references:
# code lines below are commented out because the sample data doesn't have
# earlobe or mastoid channels, so this is just for demonstration purposes:
# use a single channel reference (left earlobe)
# raw.set_eeg_reference(ref_channels=['A1'])
# use average of mastoid channels as reference
# raw.set_eeg_reference(ref_channels=['M1', 'M2'])
###############################################################################
# If a scalp electrode was used as reference but was not saved alongside the
# raw data (reference channels often aren't), you may wish to add it back to
# the dataset before re-referencing. For example, if your EEG system recorded
# with channel ``Fp1`` as the reference but did not include ``Fp1`` in the data
# file, using :meth:`~mne.io.Raw.set_eeg_reference` to set (say) ``Cz`` as the
# new reference will then subtract out the signal at ``Cz`` *without restoring
# the signal at* ``Fp1``. In this situation, you can add back ``Fp1`` as a flat
# channel prior to re-referencing using :func:`~mne.add_reference_channels`.
# (Since our example data doesn't use the `10-20 electrode naming system`_, the
# example below adds ``EEG 999`` as the missing reference, then sets the
# reference to ``EEG 050``.) Here's how the data looks in its original state:
raw.plot()
###############################################################################
# By default, :func:`~mne.add_reference_channels` returns a copy, so we can go
# back to our original ``raw`` object later. If you wanted to alter the
# existing :class:`~mne.io.Raw` object in-place you could specify
# ``copy=False``.
# add new reference channel (all zero)
raw_new_ref = mne.add_reference_channels(raw, ref_channels=['EEG 999'])
raw_new_ref.plot()
###############################################################################
# .. KEEP THESE BLOCKS SEPARATE SO FIGURES ARE BIG ENOUGH TO READ
# set reference to `EEG 050`
raw_new_ref.set_eeg_reference(ref_channels=['EEG 050'])
raw_new_ref.plot()
###############################################################################
# Notice that the new reference (``EEG 050``) is now flat, while the original
# reference channel that we added back to the data (``EEG 999``) has a non-zero
# signal. Notice also that ``EEG 053`` (which is marked as "bad" in
# ``raw.info['bads']``) is not affected by the re-referencing.
#
#
# Setting average reference
# ^^^^^^^^^^^^^^^^^^^^^^^^^
#
# To set a "virtual reference" that is the average of all channels, you can use
# :meth:`~mne.io.Raw.set_eeg_reference` with ``ref_channels='average'``. Just
# as above, this will not affect any channels marked as "bad", nor will it
# include bad channels when computing the average. However, it does modify the
# :class:`~mne.io.Raw` object in-place, so we'll make a copy first so we can
# still go back to the unmodified :class:`~mne.io.Raw` object later:
# sphinx_gallery_thumbnail_number = 4
# use the average of all channels as reference
raw_avg_ref = raw.copy().set_eeg_reference(ref_channels='average')
raw_avg_ref.plot()
###############################################################################
# Creating the average reference as a projector
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# If using an average reference, it is possible to create the reference as a
# :term:`projector` rather than subtracting the reference from the data
# immediately by specifying ``projection=True``:
raw.set_eeg_reference('average', projection=True)
print(raw.info['projs'])
###############################################################################
# Creating the average reference as a projector has a few advantages:
#
# 1. It is possible to turn projectors on or off when plotting, so it is easy
# to visualize the effect that the average reference has on the data.
#
# 2. If additional channels are marked as "bad" or if a subset of channels are
# later selected, the projector will be re-computed to take these changes
# into account (thus guaranteeing that the signal is zero-mean).
#
# 3. If there are other unapplied projectors affecting the EEG channels (such
# as SSP projectors for removing heartbeat or blink artifacts), EEG
# re-referencing cannot be performed until those projectors are either
# applied or removed; adding the EEG reference as a projector is not subject
# to that constraint. (The reason this wasn't a problem when we applied the
# non-projector average reference to ``raw_avg_ref`` above is that the
# empty-room projectors included in the sample data :file:`.fif` file were
# only computed for the magnetometers.)
for title, proj in zip(['Original', 'Average'], [False, True]):
fig = raw.plot(proj=proj, n_channels=len(raw))
# make room for title
fig.subplots_adjust(top=0.9)
fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold')
###############################################################################
# EEG reference and source modeling
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# If you plan to perform source modeling (either with EEG or combined EEG/MEG
# data), it is **strongly recommended** to use the
# average-reference-as-projection approach. It is important to use an average
# reference because using a specific
# reference sensor (or even an average of a few sensors) spreads the forward
# model error from the reference sensor(s) into all sensors, effectively
# amplifying the importance of the reference sensor(s) when computing source
# estimates. In contrast, using the average of all EEG channels as reference
# spreads the forward modeling error evenly across channels, so no one channel
# is weighted more strongly during source estimation. See also this `FieldTrip
# FAQ on average referencing`_ for more information.
#
# The main reason for specifying the average reference as a projector was
# mentioned in the previous section: an average reference projector adapts if
# channels are dropped, ensuring that the signal will always be zero-mean when
# the source modeling is performed. In contrast, applying an average reference
# by the traditional subtraction method offers no such guarantee.
#
# For these reasons, when performing inverse imaging, *MNE-Python will
# automatically average-reference the EEG channels if they are present and no
# reference strategy has been specified*. If you want to perform inverse
# imaging and do not want to use an average reference (and hence you accept the
# risks presented in the previous paragraphs), you can force MNE-Python to
# relax its average reference requirement by passing an empty list to
# :meth:`~mne.io.Raw.set_eeg_reference` (i.e., by calling
# ``raw.set_eeg_reference(ref_channels=[])``) prior to performing inverse
# imaging.
#
#
# .. LINKS
#
# .. _`FieldTrip FAQ on average referencing`:
# http://www.fieldtriptoolbox.org/faq/why_should_i_use_an_average_reference_for_eeg_source_reconstruction/
# .. _`10-20 electrode naming system`:
# https://en.wikipedia.org/wiki/10%E2%80%9320_system_(EEG)
|
Java
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013, PAL Robotics S.L.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of hiDOF, Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////
/// \author Adolfo Rodriguez Tsouroukdissian
#include <string>
#include <gtest/gtest.h>
#include <ros/console.h>
#include <hardware_interface/posvelacc_command_interface.h>
using std::string;
using namespace hardware_interface;
TEST(PosVelAccCommandHandleTest, HandleConstruction)
{
string name = "name1";
double pos, vel, eff;
double cmd_pos, cmd_vel, cmd_acc;
EXPECT_NO_THROW(PosVelAccJointHandle tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, &cmd_vel, &cmd_acc));
EXPECT_THROW(PosVelAccJointHandle tmp(JointStateHandle(name, &pos, &vel, &eff), nullptr, &cmd_vel, &cmd_acc), HardwareInterfaceException);
EXPECT_THROW(PosVelAccJointHandle tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, nullptr, &cmd_acc), HardwareInterfaceException);
EXPECT_THROW(PosVelAccJointHandle tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, &cmd_vel, nullptr), HardwareInterfaceException);
// Print error messages
// Requires manual output inspection, but exception message should be descriptive
try {PosVelAccJointHandle tmp(JointStateHandle(name, &pos, &vel, &eff), nullptr, nullptr, nullptr);}
catch(const HardwareInterfaceException& e) {ROS_ERROR_STREAM(e.what());}
}
#ifndef NDEBUG // NOTE: This test validates assertion triggering, hence only gets compiled in debug mode
TEST(JointStateHandleTest, AssertionTriggering)
{
PosVelAccJointHandle h;
// Data with invalid pointers should trigger an assertion
EXPECT_DEATH(h.getPosition(), ".*");
EXPECT_DEATH(h.getVelocity(), ".*");
EXPECT_DEATH(h.getEffort(), ".*");
EXPECT_DEATH(h.getCommandPosition(), ".*");
EXPECT_DEATH(h.getCommandVelocity(), ".*");
EXPECT_DEATH(h.getCommandAcceleration(), ".*");
EXPECT_DEATH(h.setCommandPosition(2.0), ".*");
EXPECT_DEATH(h.setCommandVelocity(3.0), ".*");
EXPECT_DEATH(h.setCommandAcceleration(4.0), ".*");
EXPECT_DEATH(h.setCommand(1.0, 2.0, 3.0), ".*");
}
#endif // NDEBUG
class PosVelAccCommandInterfaceTest : public ::testing::Test
{
protected:
double pos1 = {1.0}, vel1 = {2.0}, eff1 = {3.0}, cmd_pos1 = {0.0}, cmd_vel1 = {0.0}, cmd_acc1 = {0.0};
double pos2 = {4.0}, vel2 = {5.0}, eff2 = {6.0}, cmd_pos2 = {0.0}, cmd_vel2 = {0.0}, cmd_acc2 = {0.0};
string name1 = {"name_1"};
string name2 = {"name_2"};
JointStateHandle hs1 = {name1, &pos1, &vel1, &eff1};
JointStateHandle hs2 = {name2, &pos2, &vel2, &eff2};
PosVelAccJointHandle hc1 = {hs1, &cmd_pos1, &cmd_vel1, &cmd_acc1};
PosVelAccJointHandle hc2 = {hs2, &cmd_pos2, &cmd_vel2, &cmd_acc2};
};
TEST_F(PosVelAccCommandInterfaceTest, ExcerciseApi)
{
PosVelAccJointInterface iface;
iface.registerHandle(hc1);
iface.registerHandle(hc2);
// Get handles
EXPECT_NO_THROW(iface.getHandle(name1));
EXPECT_NO_THROW(iface.getHandle(name2));
PosVelAccJointHandle hc1_tmp = iface.getHandle(name1);
EXPECT_EQ(name1, hc1_tmp.getName());
EXPECT_DOUBLE_EQ(pos1, hc1_tmp.getPosition());
EXPECT_DOUBLE_EQ(vel1, hc1_tmp.getVelocity());
EXPECT_DOUBLE_EQ(eff1, hc1_tmp.getEffort());
EXPECT_DOUBLE_EQ(cmd_pos1, hc1_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(cmd_vel1, hc1_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(cmd_acc1, hc1_tmp.getCommandAcceleration());
const double new_cmd_pos1 = -1.0, new_cmd_vel1 = -2.0, new_cmd_acc1 = -3.0;
hc1_tmp.setCommand(new_cmd_pos1, new_cmd_vel1, new_cmd_acc1);
EXPECT_DOUBLE_EQ(new_cmd_pos1, hc1_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(new_cmd_vel1, hc1_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(new_cmd_acc1, hc1_tmp.getCommandAcceleration());
PosVelAccJointHandle hc2_tmp = iface.getHandle(name2);
EXPECT_EQ(name2, hc2_tmp.getName());
EXPECT_DOUBLE_EQ(pos2, hc2_tmp.getPosition());
EXPECT_DOUBLE_EQ(vel2, hc2_tmp.getVelocity());
EXPECT_DOUBLE_EQ(eff2, hc2_tmp.getEffort());
EXPECT_DOUBLE_EQ(cmd_pos2, hc2_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(cmd_vel2, hc2_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(cmd_acc2, hc2_tmp.getCommandAcceleration());
const double new_cmd_pos2 = -1.0, new_cmd_vel2 = -2.0, new_cmd_acc2 = -3.0;
hc2_tmp.setCommand(new_cmd_pos2, new_cmd_vel2, new_cmd_acc2);
EXPECT_DOUBLE_EQ(new_cmd_pos2, hc2_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(new_cmd_vel2, hc2_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(new_cmd_acc2, hc2_tmp.getCommandAcceleration());
// This interface claims resources
EXPECT_EQ(2, iface.getClaims().size());
// Print error message
// Requires manual output inspection, but exception message should contain the interface name (not its base clase)
try {iface.getHandle("unknown_name");}
catch(const HardwareInterfaceException& e) {ROS_ERROR_STREAM(e.what());}
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Java
|
/*
* Copyright Ekagra and SemanticBits, LLC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/clinical-connector/LICENSE.txt for details.
*/
package gov.nih.nci.cdmsconnector.c3d.service.globus.resource;
import gov.nih.nci.cdmsconnector.c3d.common.C3DGridServiceConstants;
import gov.nih.nci.cdmsconnector.c3d.stubs.C3DGridServiceResourceProperties;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.InvalidResourceKeyException;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceContext;
import gov.nih.nci.cagrid.introduce.servicetools.SingletonResourceHomeImpl;
import org.globus.wsrf.jndi.Initializable;
/**
* DO NOT EDIT: This class is autogenerated!
*
* This class implements the resource home for the resource type represented
* by this service.
*
* @created by Introduce Toolkit version 1.2
*
*/
public class C3DGridServiceResourceHome extends SingletonResourceHomeImpl implements Initializable {
static final Log logger = LogFactory.getLog(C3DGridServiceResourceHome.class);
private static final UUIDGen UUIDGEN = UUIDGenFactory.getUUIDGen();
public Resource createSingleton() {
logger.info("Creating a single resource.");
try {
C3DGridServiceResourceProperties props = new C3DGridServiceResourceProperties();
C3DGridServiceResource resource = new C3DGridServiceResource();
if (resource instanceof PersistenceCallback) {
//try to load the resource if it was persisted
try{
((PersistenceCallback) resource).load(null);
} catch (InvalidResourceKeyException ex){
//persisted singleton resource was not found so we will just create a new one
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
} else {
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
return resource;
} catch (Exception e) {
logger.error("Exception when creating the resource",e);
return null;
}
}
public Resource find(ResourceKey key) throws ResourceException {
C3DGridServiceResource resource = (C3DGridServiceResource) super.find(key);
return resource;
}
/**
* Initialze the singleton resource, when the home is initialized.
*/
public void initialize() throws Exception {
logger.info("Attempting to initialize resource.");
Resource resource = find(null);
if (resource == null) {
logger.error("Unable to initialize resource!");
} else {
logger.info("Successfully initialized resource.");
}
}
/**
* Get the resouce that is being addressed in this current context
*/
public C3DGridServiceResource getAddressedResource() throws Exception {
C3DGridServiceResource thisResource;
thisResource = (C3DGridServiceResource) ResourceContext.getResourceContext().getResource();
return thisResource;
}
}
|
Java
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(function() {
"use strict";
var runFunc;
var count = 0;
function getId() {
return "code" + (count++);
}
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var id = getId();
var output = document.createElement('div');
var outpre = document.createElement('pre');
var stopFunc;
function onKill() {
if (stopFunc) {
stopFunc();
}
}
function onRun(e) {
onKill();
outpre.innerHTML = "";
output.style.display = "block";
run.style.display = "none";
var options = {Race: e.shiftKey};
stopFunc = runFunc(text(code), outpre, options);
}
function onClose() {
onKill();
output.style.display = "none";
run.style.display = "inline-block";
}
var run = document.createElement('button');
run.innerHTML = 'Run';
run.className = 'run';
run.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);
buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
if (play.length > 0) {
if (window.connectPlayground) {
runFunc = window.connectPlayground("ws://" + window.location.host + "/socket");
} else {
// If this message is logged,
// we have neglected to include socket.js or playground.js.
console.log("No playground transport available.");
}
}
})();
|
Java
|
collectd-activemq-python
========================
Python-based plugin to put simple [ActiveMQ] (http://activemq.apache.org/) stats to [collectd](http://collectd.org)
Data captured includes:
* Queue name
* Number of messages in queue
* Number of consumers
* Counter of enqueued messages
* Counter of dequeued messages
[powdahoud's redis-collectd-plugin] (https://github.com/powdahound/redis-collectd-plugin/) was used as template,
[kipsnak's Perl ActiveMQ Munin plugin] (https://github.com/kipsnak/munin-activemq-plugin) - as inspiration. :)
Install
-------
1. Place activemq_info.py in /usr/lib/collectd/plugins/python
2. Configure the plugin (see below).
3. Restart collectd.
Configuration
-------------
Add the following to your collectd config
<LoadPlugin python>
Globals true
</LoadPlugin>
<Plugin python>
ModulePath "/usr/lib/collectd/plugins/python"
Import "activemq_info"
<Module activemq_info>Up
Host "localhost"
Port 8161
</Module>
</Plugin>
Optional attributes can be set to configure http auth or webadmin root path:
<Module activemq_info>
Host "localhost"
Port 8161
User "jdoe"
Pass "123qwerty"
Webadmin "amq-admin"
</Module>
_It will access http://localhost:8161/amq-admin/xml/queues.jsp and authenticate with jdoe/123qwerty_
Dependencies
------------
[Python-requests](http://www.python-requests.org/en/latest/) module is required. Please install it with `pip install requests` or use your package manager to install `python-requests` package or similar.
License
-------
MIT
|
Java
|
/*
* sound/pas2_mixer.c
*
* Mixer routines for the Pro Audio Spectrum cards.
*
* Copyright by Hannu Savolainen 1993
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. 2.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#define _PAS2_MIXER_C_
#include <i386/isa/sound/sound_config.h>
#if defined(CONFIG_PAS)
#include <i386/isa/sound/pas_hw.h>
#define TRACE(what) /* (what) */
extern int translat_code;
extern char pas_model;
extern sound_os_info *pas_osp;
static int rec_devices = (SOUND_MASK_MIC); /* Default recording source */
static int mode_control = 0;
#define POSSIBLE_RECORDING_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | SOUND_MASK_ALTPCM)
#define SUPPORTED_MIXER_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | SOUND_MASK_ALTPCM | SOUND_MASK_IMIX | \
SOUND_MASK_VOLUME | SOUND_MASK_BASS | SOUND_MASK_TREBLE | SOUND_MASK_RECLEV | \
SOUND_MASK_MUTE | SOUND_MASK_ENHANCE | SOUND_MASK_LOUD)
static u_short levels[SOUND_MIXER_NRDEVICES] =
{
0x3232, /* Master Volume */
0x3232, /* Bass */
0x3232, /* Treble */
0x5050, /* FM */
0x4b4b, /* PCM */
0x3232, /* PC Speaker */
0x4b4b, /* Ext Line */
0x4b4b, /* Mic */
0x4b4b, /* CD */
0x6464, /* Recording monitor */
0x4b4b, /* SB PCM */
0x6464 /* Recording level */
};
void
mix_write(u_char data, int ioaddr)
{
/*
* The Revision D cards have a problem with their MVA508 interface.
* The kludge-o-rama fix is to make a 16-bit quantity with identical
* LSB and MSBs out of the output byte and to do a 16-bit out to the
* mixer port - 1. We need to do this because it isn't timing problem
* but chip access sequence problem.
*/
if (pas_model == PAS_16D) {
outw((ioaddr ^ translat_code) - 1, data | (data << 8));
outb(0, 0x80);
} else
pas_write(data, ioaddr);
}
static int
mixer_output(int right_vol, int left_vol, int div, int bits,
int mixer)
{ /* Input or output mixer */
int left = left_vol * div / 100;
int right = right_vol * div / 100;
if (bits & P_M_MV508_MIXER) { /* Select input or output mixer */
left |= mixer;
right |= mixer;
}
if (bits == P_M_MV508_BASS || bits == P_M_MV508_TREBLE) { /* Bass and treble are
* mono devices */
mix_write(P_M_MV508_ADDRESS | bits, PARALLEL_MIXER);
mix_write(left, PARALLEL_MIXER);
right_vol = left_vol;
} else {
mix_write(P_M_MV508_ADDRESS | P_M_MV508_LEFT | bits, PARALLEL_MIXER);
mix_write(left, PARALLEL_MIXER);
mix_write(P_M_MV508_ADDRESS | P_M_MV508_RIGHT | bits, PARALLEL_MIXER);
mix_write(right, PARALLEL_MIXER);
}
return (left_vol | (right_vol << 8));
}
static void
set_mode(int new_mode)
{
mix_write(P_M_MV508_ADDRESS | P_M_MV508_MODE, PARALLEL_MIXER);
mix_write(new_mode, PARALLEL_MIXER);
mode_control = new_mode;
}
static int
pas_mixer_set(int whichDev, u_int level)
{
int left, right, devmask, changed, i, mixer = 0;
TRACE(printf("static int pas_mixer_set(int whichDev = %d, u_int level = %X)\n", whichDev, level));
left = level & 0x7f;
right = (level & 0x7f00) >> 8;
if (whichDev < SOUND_MIXER_NRDEVICES)
if ((1 << whichDev) & rec_devices)
mixer = P_M_MV508_INPUTMIX;
else
mixer = P_M_MV508_OUTPUTMIX;
switch (whichDev) {
case SOUND_MIXER_VOLUME: /* Master volume (0-63) */
levels[whichDev] = mixer_output(right, left, 63, P_M_MV508_MASTER_A, 0);
break;
/*
* Note! Bass and Treble are mono devices. Will use just the
* left channel.
*/
case SOUND_MIXER_BASS: /* Bass (0-12) */
levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_BASS, 0);
break;
case SOUND_MIXER_TREBLE: /* Treble (0-12) */
levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_TREBLE, 0);
break;
case SOUND_MIXER_SYNTH:/* Internal synthesizer (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_FM, mixer);
break;
case SOUND_MIXER_PCM: /* PAS PCM (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_PCM, mixer);
break;
case SOUND_MIXER_ALTPCM: /* SB PCM (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SB, mixer);
break;
case SOUND_MIXER_SPEAKER: /* PC speaker (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SPEAKER, mixer);
break;
case SOUND_MIXER_LINE: /* External line (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_LINE, mixer);
break;
case SOUND_MIXER_CD: /* CD (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_CDROM, mixer);
break;
case SOUND_MIXER_MIC: /* External microphone (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_MIC, mixer);
break;
case SOUND_MIXER_IMIX: /* Recording monitor (0-31) (Output mixer
* only) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_IMIXER,
P_M_MV508_OUTPUTMIX);
break;
case SOUND_MIXER_RECLEV: /* Recording level (0-15) */
levels[whichDev] = mixer_output(right, left, 15, P_M_MV508_MASTER_B, 0);
break;
case SOUND_MIXER_MUTE:
return 0;
break;
case SOUND_MIXER_ENHANCE:
i = 0;
level &= 0x7f;
if (level)
i = (level / 20) - 1;
mode_control &= ~P_M_MV508_ENHANCE_BITS;
mode_control |= P_M_MV508_ENHANCE_BITS;
set_mode(mode_control);
if (i)
i = (i + 1) * 20;
return i;
break;
case SOUND_MIXER_LOUD:
mode_control &= ~P_M_MV508_LOUDNESS;
if (level)
mode_control |= P_M_MV508_LOUDNESS;
set_mode(mode_control);
return !!level; /* 0 or 1 */
break;
case SOUND_MIXER_RECSRC:
devmask = level & POSSIBLE_RECORDING_DEVICES;
changed = devmask ^ rec_devices;
rec_devices = devmask;
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
if (changed & (1 << i)) {
pas_mixer_set(i, levels[i]);
}
return rec_devices;
break;
default:
return -(EINVAL);
}
return (levels[whichDev]);
}
/*****/
static void
pas_mixer_reset(void)
{
int foo;
TRACE(printf("pas2_mixer.c: void pas_mixer_reset(void)\n"));
for (foo = 0; foo < SOUND_MIXER_NRDEVICES; foo++)
pas_mixer_set(foo, levels[foo]);
set_mode(P_M_MV508_LOUDNESS | P_M_MV508_ENHANCE_40);
}
static int
pas_mixer_ioctl(int dev, u_int cmd, ioctl_arg arg)
{
TRACE(printf("pas2_mixer.c: int pas_mixer_ioctl(u_int cmd = %X, u_int arg = %X)\n", cmd, arg));
if (((cmd >> 8) & 0xff) == 'M') {
if (cmd & IOC_IN)
return *(int *) arg = pas_mixer_set(cmd & 0xff, (*(int *) arg));
else { /* Read parameters */
switch (cmd & 0xff) {
case SOUND_MIXER_RECSRC:
return *(int *) arg = rec_devices;
break;
case SOUND_MIXER_STEREODEVS:
return *(int *) arg = SUPPORTED_MIXER_DEVICES & ~(SOUND_MASK_BASS | SOUND_MASK_TREBLE);
break;
case SOUND_MIXER_DEVMASK:
return *(int *) arg = SUPPORTED_MIXER_DEVICES;
break;
case SOUND_MIXER_RECMASK:
return *(int *) arg = POSSIBLE_RECORDING_DEVICES & SUPPORTED_MIXER_DEVICES;
break;
case SOUND_MIXER_CAPS:
return *(int *) arg = 0; /* No special
* capabilities */
break;
case SOUND_MIXER_MUTE:
return *(int *) arg = 0; /* No mute yet */
break;
case SOUND_MIXER_ENHANCE:
if (!(mode_control & P_M_MV508_ENHANCE_BITS))
return *(int *) arg = 0;
return *(int *) arg = ((mode_control & P_M_MV508_ENHANCE_BITS) + 1) * 20;
break;
case SOUND_MIXER_LOUD:
if (mode_control & P_M_MV508_LOUDNESS)
return *(int *) arg = 1;
return *(int *) arg = 0;
break;
default:
return *(int *) arg = levels[cmd & 0xff];
}
}
}
return -(EINVAL);
}
static struct mixer_operations pas_mixer_operations =
{
"Pro Audio Spectrum 16",
pas_mixer_ioctl
};
int
pas_init_mixer(void)
{
pas_mixer_reset();
if (num_mixers < MAX_MIXER_DEV)
mixer_devs[num_mixers++] = &pas_mixer_operations;
return 1;
}
#endif
|
Java
|
<?php
namespace tests\models;
use yii\db\ActiveRecord;
/**
* Post
*
* @property integer $id
* @property string $title
* @property string $body
*
* @property string $tagNames
* @property array $imageNames
*
* @property Tag[] $tags
* @property Image[] $images
*/
class Post extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'body'], 'required'],
];
}
/**
* @inheritdoc
*/
public function transactions()
{
return [
self::SCENARIO_DEFAULT => self::OP_ALL,
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTags()
{
return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
->viaTable('post_tag', ['post_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getImages()
{
return $this->hasMany(Image::className(), ['post_id' => 'id']);
}
}
|
Java
|
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.relationshipexplorer.ui.collection;
import java.util.HashSet;
import java.util.Set;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.view.relationshipexplorer.ui.ConTourElement;
import org.caleydo.view.relationshipexplorer.ui.collection.idprovider.IElementIDProvider;
import org.caleydo.view.relationshipexplorer.ui.column.factory.ColumnFactories;
import org.caleydo.view.relationshipexplorer.ui.column.factory.IColumnFactory;
import org.caleydo.view.relationshipexplorer.ui.detail.parcoords.ParallelCoordinatesDetailViewFactory;
import com.google.common.collect.Sets;
/**
* @author Christian
*
*/
public class TabularDataCollection extends AEntityCollection {
protected final ATableBasedDataDomain dataDomain;
protected final IDCategory itemIDCategory;
protected final TablePerspective tablePerspective;
protected final IDType itemIDType;
protected final VirtualArray va;
protected final Perspective dimensionPerspective;
protected final IDType mappingIDType;
public TabularDataCollection(TablePerspective tablePerspective, IDCategory itemIDCategory,
IElementIDProvider elementIDProvider, ConTourElement relationshipExplorer) {
super(relationshipExplorer);
dataDomain = tablePerspective.getDataDomain();
this.itemIDCategory = itemIDCategory;
this.tablePerspective = tablePerspective;
this.mappingIDType = dataDomain.getDatasetDescriptionIDType(itemIDCategory);
if (dataDomain.getDimensionIDCategory() == itemIDCategory) {
va = tablePerspective.getDimensionPerspective().getVirtualArray();
itemIDType = tablePerspective.getDimensionPerspective().getIdType();
dimensionPerspective = tablePerspective.getRecordPerspective();
} else {
va = tablePerspective.getRecordPerspective().getVirtualArray();
itemIDType = tablePerspective.getRecordPerspective().getIdType();
dimensionPerspective = tablePerspective.getDimensionPerspective();
}
if (elementIDProvider == null)
elementIDProvider = getDefaultElementIDProvider(va);
allElementIDs.addAll(elementIDProvider.getElementIDs());
filteredElementIDs.addAll(allElementIDs);
setLabel(dataDomain.getLabel());
detailViewFactory = new ParallelCoordinatesDetailViewFactory();
}
@Override
public IDType getBroadcastingIDType() {
return itemIDType;
}
@Override
protected Set<Object> getBroadcastIDsFromElementID(Object elementID) {
return Sets.newHashSet(elementID);
}
@Override
protected Set<Object> getElementIDsFromBroadcastID(Object broadcastingID) {
return Sets.newHashSet(broadcastingID);
}
@Override
protected IColumnFactory getDefaultColumnFactory() {
return ColumnFactories.createDefaultTabularDataColumnFactory();
}
/**
* @return the dataDomain, see {@link #dataDomain}
*/
public ATableBasedDataDomain getDataDomain() {
return dataDomain;
}
/**
* @return the perspective, see {@link #dimensionPerspective}
*/
public Perspective getDimensionPerspective() {
return dimensionPerspective;
}
/**
* @return the itemIDCategory, see {@link #itemIDCategory}
*/
public IDCategory getItemIDCategory() {
return itemIDCategory;
}
/**
* @return the itemIDType, see {@link #itemIDType}
*/
public IDType getItemIDType() {
return itemIDType;
}
@Override
public IDType getMappingIDType() {
return mappingIDType;
}
/**
* @return the tablePerspective, see {@link #tablePerspective}
*/
public TablePerspective getTablePerspective() {
return tablePerspective;
}
/**
* @return the va, see {@link #va}
*/
public VirtualArray getVa() {
return va;
}
public static IElementIDProvider getDefaultElementIDProvider(final VirtualArray va) {
return new IElementIDProvider() {
@Override
public Set<Object> getElementIDs() {
return new HashSet<Object>(va.getIDs());
}
};
}
@Override
public String getText(Object elementID) {
return elementID.toString();
}
}
|
Java
|
Language provider interface
===========================
This package provides interface for language provider for accessing application languages from any storage for Yii2 Framework.
It's allows to you create multi-language modules for using in Yii2 based application.
As example of integration to module you can see [yii2-email-template](https://github.com/yiimaker/yii2-email-templates) extension.
[](CHANGELOG.md)
[](https://packagist.org/packages/motion/yii2-language-provider)
[](https://packagist.org/packages/motion/yii2-language-provider)
[](https://travis-ci.org/motion-web-production/yii2-language-provider)
[](https://scrutinizer-ci.com/g/motion-web-production/yii2-language-provider/?branch=master)
From the box you can use:
* [Config language provider](#config-language-provider)
* [Database language provider](#database-language-provider)
If you want to create your implementation of language provider you should implement interface
`motion\i18n\LanguageProviderInterface`.
Installation
------------
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```
$ composer require motion/yii2-language-provider
```
or add
```
"motion/yii2-language-provider": "~2.1"
```
to the `require` section of your `composer.json`.
Usage
-----
### Config language provider
|Option |Description |Type |Default |
|------------------|--------------------------------------------------|------|----------|
|languages |Should contains list of application languages. |array |`[]` |
|defaultLanguage |Should contains default application language. |array |`[]` |
#### Example
```php
$config = [
'languages' => [
[
'label' => 'English',
'locale' => 'en',
],
[
'label' => 'Ukrainian',
'locale' => 'uk',
],
[
'label' => 'Russian',
'locale' => 'ru',
],
],
'defaultLanguage' => [
'label' => 'English',
'locale' => 'en',
],
];
$provider = new \motion\i18n\ConfigLanguageProvider($config);
$provider->getLanguages(); // returns list of languages
$provider->getDefaultLanguage(); // returns default language
$provider->getLanguageLabel('en'); // returns language label by locale (`English`)
```
### Database language provider
|Option |Description |Type |Default |
|---------------|----------------------------------------------------|---------------------------------------|---------------|
|db |Database connection instance. |string, array, `\yii\db\Connection` |`db` |
|tableName |Name of language entity in database. |string |`language` |
|localeField |Name of locale field in language entity. |string |`locale` |
|labelField |Name of label field in language entity. |string |`label` |
|defaultField |Name of field in table with default language flag. |string |`is_default` |
#### Example
```php
$config = [
'db' => 'secondDb',
'labelField' => 'title',
];
$provider = new \motion\i18n\DbLanguageProvider($config);
$provider->getLanguages(); // returns list of languages
$provider->getDefaultLanguage(); // returns default language
$provider->getLanguageLabel('uk'); // returns language label by locale
```
Tests
-----
You can run tests with composer command
```
$ composer test
```
or using following command
```
$ codecept build && codecept run
```
Licence
-------
[](LICENSE)
This project is released under the terms of the BSD-3-Clause [license](LICENSE).
Copyright (c) 2017-2018, Motion Web Production
|
Java
|
<?php
namespace backend\models\base;
use Yii;
/**
* This is the base model class for table "auth_item_child".
*
* @property string $parent
* @property string $child
*
* @property \backend\models\AuthItem $parent0
* @property \backend\models\AuthItem $child0
*/
class AuthItemChild extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['parent', 'child'], 'required'],
[['parent', 'child'], 'string', 'max' => 64]
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'auth_item_child';
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'parent' => 'Parent',
'child' => 'Child',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getParent0()
{
return $this->hasOne(\backend\models\AuthItem::className(), ['name' => 'parent']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getChild0()
{
return $this->hasOne(\backend\models\AuthItem::className(), ['name' => 'child']);
}
/**
* @inheritdoc
* @return \app\models\AuthItemChildQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\models\AuthItemChildQuery(get_called_class());
}
}
|
Java
|
var PgQuery = require('bindings')('pg-query');
module.exports = {
parse: function(query) {
var result = PgQuery.parse(query);
if (result.query) {
result.query = JSON.parse(result.query);
}
if (result.error) {
var err = new Error(result.error.message);
err.fileName = result.error.fileName;
err.lineNumber = result.error.lineNumber;
err.cursorPosition = result.error.cursorPosition;
err.functionName = result.error.functionName;
err.context = result.error.context;
result.error = err;
}
return result;
}
};
|
Java
|
// Replacement for jquery.ui.accordion to avoid dealing with
// jquery.ui theming.
//
// Usage: $('#container').squeezebox(options);
// where the direct child elements of '#container' are
// sequential pairs of header/panel elements, and options
// is an optional object with any of the following properties:
//
// activeHeaderClass: Class name to apply to the active header
// headerSelector: Selector for the header elements
// nextPanelSelector: Selector for the next panel from a header
// speed: Animation speed
(function($) {
$.fn.squeezebox = function(options) {
// Default options.
options = $.extend({
activeHeaderClass: 'squeezebox-header-on',
headerSelector: '> *:even',
nextPanelSelector: ':first',
speed: 500
}, options);
var headers = this.find(options.headerSelector);
// When a header is clicked, iterate through each of the
// headers, getting their corresponding panels, and opening
// the panel for the header that was clicked (slideDown),
// closing the others (slideUp).
headers.click(function() {
var clicked = this;
$.each(headers, function(i, header) {
var panel = $(header).next(options.nextPanelSelector);
if (clicked == header) {
panel.slideDown(options.speed);
$(header).addClass(options.activeHeaderClass);
} else {
panel.slideUp(options.speed);
$(header).removeClass(options.activeHeaderClass);
}
});
});
};
})(jQuery);
|
Java
|
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
////////////////////////////////////////////////////////////////////////////
$org = $auth->createRole('org');
$auth->add($org);
$adviser = $auth->createRole('adviser');
$auth->add($adviser);
$osa = $auth->createRole('osa');
$auth->add($osa);
$auth->addChild($osa, $adviser);
$auth->addChild($osa, $org);
$admin = $auth->createRole('admin');
$auth->add($admin);
///////////////////////////////////////////////////////////////////////////
$index_organizations = $auth->createPermission('indexOrganizations');
$index_organizations->description = 'view the list of organizations';
$auth->add($index_organizations);
$create_organization = $auth->createPermission('createOrganization');
$create_organization->description = 'creates an organization';
$auth->add($create_organization);
$delete_organization = $auth->createPermission('deleteOrganization');
$delete_organization->description = 'deletes an organization';
$auth->add($delete_organization);
$view_organization = $auth->createPermission('viewOrganization');
$view_organization->description = 'views the details of an organization';
$auth->add($view_organization);
$view_own_organization = $auth->createPermission('viewOwnOrganization');
$view_own_organization->description = 'views the details of own organization';
$auth->add($view_own_organization);
$auth->addChild($org, $view_own_organization);
$auth->addChild($osa, $index_organizations);
$auth->addChild($osa, $create_organization);
$auth->addChild($osa, $delete_organization);
$auth->addChild($osa, $view_organization);
////////////////////////////////////////////////////////////////////////////
$auth->assign($org, 4);
$auth->assign($adviser, 3);
$auth->assign($osa, 2);
$auth->assign($admin, 1);
}
}
|
Java
|
import base64
import json
from twisted.internet.defer import inlineCallbacks, DeferredQueue, returnValue
from twisted.web.http_headers import Headers
from twisted.web import http
from twisted.web.server import NOT_DONE_YET
from vumi.config import ConfigContext
from vumi.message import TransportUserMessage, TransportEvent
from vumi.tests.helpers import VumiTestCase
from vumi.tests.utils import MockHttpServer, LogCatcher
from vumi.transports.vumi_bridge.client import StreamingClient
from vumi.utils import http_request_full
from go.apps.http_api.resource import (
StreamResourceMixin, StreamingConversationResource)
from go.apps.tests.helpers import AppWorkerHelper
from go.apps.http_api.vumi_app import StreamingHTTPWorker
class TestStreamingHTTPWorker(VumiTestCase):
@inlineCallbacks
def setUp(self):
self.app_helper = self.add_helper(AppWorkerHelper(StreamingHTTPWorker))
self.config = {
'health_path': '/health/',
'web_path': '/foo',
'web_port': 0,
'metrics_prefix': 'metrics_prefix.',
'conversation_cache_ttl': 0,
}
self.app = yield self.app_helper.get_app_worker(self.config)
self.addr = self.app.webserver.getHost()
self.url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['web_path'])
conv_config = {
'http_api': {
'api_tokens': [
'token-1',
'token-2',
'token-3',
],
'metric_store': 'metric_store',
}
}
conversation = yield self.app_helper.create_conversation(
config=conv_config)
yield self.app_helper.start_conversation(conversation)
self.conversation = yield self.app_helper.get_conversation(
conversation.key)
self.auth_headers = {
'Authorization': ['Basic ' + base64.b64encode('%s:%s' % (
conversation.user_account.key, 'token-1'))],
}
self.client = StreamingClient()
# Mock server to test HTTP posting of inbound messages & events
self.mock_push_server = MockHttpServer(self.handle_request)
yield self.mock_push_server.start()
self.add_cleanup(self.mock_push_server.stop)
self.push_calls = DeferredQueue()
self._setup_wait_for_request()
self.add_cleanup(self._wait_for_requests)
def _setup_wait_for_request(self):
# Hackery to wait for the request to finish
self._req_state = {
'queue': DeferredQueue(),
'expected': 0,
}
orig_track = StreamingConversationResource.track_request
orig_release = StreamingConversationResource.release_request
def track_wrapper(*args, **kw):
self._req_state['expected'] += 1
return orig_track(*args, **kw)
def release_wrapper(*args, **kw):
return orig_release(*args, **kw).addCallback(
self._req_state['queue'].put)
self.patch(
StreamingConversationResource, 'track_request', track_wrapper)
self.patch(
StreamingConversationResource, 'release_request', release_wrapper)
@inlineCallbacks
def _wait_for_requests(self):
while self._req_state['expected'] > 0:
yield self._req_state['queue'].get()
self._req_state['expected'] -= 1
def handle_request(self, request):
self.push_calls.put(request)
return NOT_DONE_YET
@inlineCallbacks
def pull_message(self, count=1):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, messages.put, errors.put, url,
Headers(self.auth_headers))
received_messages = []
for msg_id in range(count):
yield self.app_helper.make_dispatch_inbound(
'in %s' % (msg_id,), message_id=str(msg_id),
conv=self.conversation)
recv_msg = yield messages.get()
received_messages.append(recv_msg)
receiver.disconnect()
returnValue((receiver, received_messages))
def assert_bad_request(self, response, reason):
self.assertEqual(response.code, http.BAD_REQUEST)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
data = json.loads(response.delivered_body)
self.assertEqual(data, {
"success": False,
"reason": reason,
})
@inlineCallbacks
def test_proxy_buffering_headers_off(self):
# This is the default, but we patch it anyway to make sure we're
# testing the right thing should the default change.
self.patch(StreamResourceMixin, 'proxy_buffering', False)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['no'])
@inlineCallbacks
def test_proxy_buffering_headers_on(self):
self.patch(StreamResourceMixin, 'proxy_buffering', True)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['yes'])
@inlineCallbacks
def test_content_type(self):
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(
headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
@inlineCallbacks
def test_messages_stream(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, messages.put, errors.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
msg2 = yield self.app_helper.make_dispatch_inbound(
'in 2', message_id='2', conv=self.conversation)
rm1 = yield messages.get()
rm2 = yield messages.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
rm1, rm2 = sorted([rm1, rm2], key=lambda m: m['message_id'])
self.assertEqual(msg1['message_id'], rm1['message_id'])
self.assertEqual(msg2['message_id'], rm2['message_id'])
self.assertEqual(errors.size, None)
@inlineCallbacks
def test_events_stream(self):
url = '%s/%s/events.json' % (self.url, self.conversation.key)
events = DeferredQueue()
errors = DeferredQueue()
receiver = yield self.client.stream(TransportEvent, events.put,
events.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 1', message_id='1')
ack1 = yield self.app_helper.make_dispatch_ack(
msg1, conv=self.conversation)
msg2 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 2', message_id='2')
ack2 = yield self.app_helper.make_dispatch_ack(
msg2, conv=self.conversation)
ra1 = yield events.get()
ra2 = yield events.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
if ra1['event_id'] != ack1['event_id']:
ra1, ra2 = ra2, ra1
self.assertEqual(ack1['event_id'], ra1['event_id'])
self.assertEqual(ack2['event_id'], ra2['event_id'])
self.assertEqual(errors.size, None)
@inlineCallbacks
def test_missing_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"'])
@inlineCallbacks
def test_invalid_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
headers = Headers({
'Authorization': ['Basic %s' % (base64.b64encode('foo:bar'),)],
})
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url, headers)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"'])
@inlineCallbacks
def test_send_to(self):
msg = {
'to_addr': '+2345',
'content': 'foo',
'message_id': 'evil_id',
}
# TaggingMiddleware.add_tag_to_msg(msg, self.tag)
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
self.assertEqual(response.code, http.OK)
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], sent_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], msg['to_addr'])
self.assertEqual(sent_msg['from_addr'], None)
@inlineCallbacks
def test_send_to_within_content_length_limit(self):
self.conversation.config['http_api'].update({
'content_length_limit': 182,
})
yield self.conversation.save()
msg = {
'content': 'foo',
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], '+1234')
self.assertEqual(sent_msg['from_addr'], None)
@inlineCallbacks
def test_send_to_content_too_long(self):
self.conversation.config['http_api'].update({
'content_length_limit': 10,
})
yield self.conversation.save()
msg = {
'content': "This message is longer than 10 characters.",
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10")
@inlineCallbacks
def test_send_to_with_evil_content(self):
msg = {
'content': 0xBAD,
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'")
@inlineCallbacks
def test_send_to_with_evil_to_addr(self):
msg = {
'content': 'good',
'to_addr': 1234,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'to_addr'")
@inlineCallbacks
def test_in_reply_to(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def test_in_reply_to_within_content_length_limit(self):
self.conversation.config['http_api'].update({
'content_length_limit': 182,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def test_in_reply_to_content_too_long(self):
self.conversation.config['http_api'].update({
'content_length_limit': 10,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': "This message is longer than 10 characters.",
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10")
@inlineCallbacks
def test_in_reply_to_with_evil_content(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 0xBAD,
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'")
@inlineCallbacks
def test_invalid_in_reply_to(self):
msg = {
'content': 'foo',
'in_reply_to': '1', # this doesn't exist
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(response, 'Invalid in_reply_to value')
@inlineCallbacks
def test_invalid_in_reply_to_with_missing_conversation_key(self):
# create a message with no conversation
inbound_msg = self.app_helper.make_inbound('in 1', message_id='msg-1')
vumi_api = self.app_helper.vumi_helper.get_vumi_api()
yield vumi_api.mdb.add_inbound_message(inbound_msg)
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
with LogCatcher(message='Invalid reply to message <Message .*>'
' which has no conversation key') as lc:
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
[error_log] = lc.messages()
self.assert_bad_request(response, "Invalid in_reply_to value")
self.assertTrue(inbound_msg['message_id'] in error_log)
@inlineCallbacks
def test_in_reply_to_with_evil_session_event(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'session_event': 0xBAD5E55104,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response,
"Invalid or missing value for payload key 'session_event'")
self.assertEqual(self.app_helper.get_dispatched_outbound(), [])
@inlineCallbacks
def test_in_reply_to_with_evil_message_id(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'message_id': 'evil_id'
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.get_dispatched_outbound()
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def test_metric_publishing(self):
metric_data = [
("vumi.test.v1", 1234, 'SUM'),
("vumi.test.v2", 3456, 'AVG'),
]
url = '%s/%s/metrics.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(metric_data), self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
prefix = "go.campaigns.test-0-user.stores.metric_store"
self.assertEqual(
self.app_helper.get_published_metrics(self.app),
[("%s.vumi.test.v1" % prefix, 1234),
("%s.vumi.test.v2" % prefix, 3456)])
@inlineCallbacks
def test_concurrency_limits(self):
config = yield self.app.get_config(None)
concurrency = config.concurrency_limit
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
max_receivers = [self.client.stream(
TransportUserMessage, queue.put, queue.put, url,
Headers(self.auth_headers)) for _ in range(concurrency)]
for i in range(concurrency):
msg = yield self.app_helper.make_dispatch_inbound(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
received = yield queue.get()
self.assertEqual(msg['message_id'], received['message_id'])
maxed_out_resp = yield http_request_full(
url, method='GET', headers=self.auth_headers)
self.assertEqual(maxed_out_resp.code, 403)
self.assertTrue(
'Too many concurrent connections' in maxed_out_resp.delivered_body)
[r.disconnect() for r in max_receivers]
@inlineCallbacks
def test_disabling_concurrency_limit(self):
conv_resource = StreamingConversationResource(
self.app, self.conversation.key)
# negative concurrency limit disables it
ctxt = ConfigContext(user_account=self.conversation.user_account.key,
concurrency_limit=-1)
config = yield self.app.get_config(msg=None, ctxt=ctxt)
self.assertTrue(
(yield conv_resource.is_allowed(
config, self.conversation.user_account.key)))
@inlineCallbacks
def test_backlog_on_connect(self):
for i in range(10):
yield self.app_helper.make_dispatch_inbound(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url,
Headers(self.auth_headers))
for i in range(10):
received = yield queue.get()
self.assertEqual(received['message_id'], str(i))
receiver.disconnect()
@inlineCallbacks
def test_health_response(self):
health_url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['health_path'])
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
queue = DeferredQueue()
stream_url = '%s/%s/messages.json' % (self.url, self.conversation.key)
stream_receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, stream_url,
Headers(self.auth_headers))
yield queue.get()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '1')
stream_receiver.disconnect()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
self.assertEqual(self.app.client_manager.clients, {
'sphex.stream.message.%s' % (self.conversation.key,): []
})
@inlineCallbacks
def test_post_inbound_message(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
msg = yield msg_d
posted_msg = TransportUserMessage.from_json(posted_json_data)
self.assertEqual(posted_msg['message_id'], msg['message_id'])
@inlineCallbacks
def test_post_inbound_message_201_response(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(201)
req.finish()
yield msg_d
self.assertEqual(lc.messages(), [])
@inlineCallbacks
def test_post_inbound_message_500_response(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(500)
req.finish()
yield msg_d
[warning_log] = lc.messages()
self.assertTrue(self.mock_push_server.url in warning_log)
self.assertTrue('500' in warning_log)
@inlineCallbacks
def test_post_inbound_event(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_event_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 1', message_id='1')
event_d = self.app_helper.make_dispatch_ack(
msg, conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
ack = yield event_d
self.assertEqual(TransportEvent.from_json(posted_json_data), ack)
@inlineCallbacks
def test_bad_urls(self):
def assert_not_found(url, headers={}):
d = http_request_full(self.url, method='GET', headers=headers)
d.addCallback(lambda r: self.assertEqual(r.code, http.NOT_FOUND))
return d
yield assert_not_found(self.url)
yield assert_not_found(self.url + '/')
yield assert_not_found('%s/%s' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/foo' % (self.url, self.conversation.key),
headers=self.auth_headers)
@inlineCallbacks
def test_send_message_command(self):
yield self.app_helper.dispatch_command(
'send_message',
user_account_key=self.conversation.user_account.key,
conversation_key=self.conversation.key,
command_data={
u'batch_id': u'batch-id',
u'content': u'foo',
u'to_addr': u'to_addr',
u'msg_options': {
u'helper_metadata': {
u'tag': {
u'tag': [u'longcode', u'default10080']
}
},
u'from_addr': u'default10080',
}
})
[msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(msg.payload['to_addr'], "to_addr")
self.assertEqual(msg.payload['from_addr'], "default10080")
self.assertEqual(msg.payload['content'], "foo")
self.assertEqual(msg.payload['message_type'], "user_message")
self.assertEqual(
msg.payload['helper_metadata']['go']['user_account'],
self.conversation.user_account.key)
self.assertEqual(
msg.payload['helper_metadata']['tag']['tag'],
['longcode', 'default10080'])
@inlineCallbacks
def test_process_command_send_message_in_reply_to(self):
msg = yield self.app_helper.make_stored_inbound(
self.conversation, "foo")
yield self.app_helper.dispatch_command(
'send_message',
user_account_key=self.conversation.user_account.key,
conversation_key=self.conversation.key,
command_data={
u'batch_id': u'batch-id',
u'content': u'foo',
u'to_addr': u'to_addr',
u'msg_options': {
u'helper_metadata': {
u'tag': {
u'tag': [u'longcode', u'default10080']
}
},
u'transport_name': u'smpp_transport',
u'in_reply_to': msg['message_id'],
u'transport_type': u'sms',
u'from_addr': u'default10080',
}
})
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], msg['from_addr'])
self.assertEqual(sent_msg['content'], 'foo')
self.assertEqual(sent_msg['in_reply_to'], msg['message_id'])
|
Java
|
from flask import request, current_app, url_for
from flask_jsonschema import validate
from .. import db
from ..models import AHBot as Bot
from .decorators import json_response
from . import api
@api.route('/abusehelper', methods=['GET'])
@json_response
def get_abusehelper():
"""Return a list of available abusehelper
**Example request**:
.. sourcecode:: http
GET /api/1.0/abusehelper HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"abusehelper": [
{
"name": "ShadowServerBot",
"url": "http://sample.com/path.html",
"id": 1
}
]
}
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json array abusehelper: List of available bots
:>jsonobj integer id: Bot ID
:>jsonobj integer name: Bot name
:status 200: Deliverable endpoint found, response may be empty
:status 404: Not found
"""
bots = Bot.query.filter().all()
return {'abusehelper': [a.serialize() for a in bots]}
@api.route('/abusehelper/<int:bot_id>', methods=['GET'])
@json_response
def get_got(bot_id):
"""Get bot from database
**Example request**:
.. sourcecode:: http
GET /api/1.0/abusehelper/1 HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"name": "ShadowServerBot",
"url": "http://sample.com/path.html",
"id": 1
}
:param bot_id: Bot unique ID
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json integer id: Bot unique ID
:>json integer name: Bot name
:status 200: ASN found
:status 404: Resource not found
"""
a = Bot.query.get_or_404(bot_id)
return a.serialize()
@api.route('/abusehelper', methods=['POST', 'PUT'])
@validate('abusehelper', 'add_bot')
@json_response
def add_bot():
"""Add new bot entry
**Example request**:
.. sourcecode:: http
POST /api/1.0/abusehelper HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
Content-Type: application/json
{
"name": "ShadowServerBot",
"url": "http://sample.com/path.html"
}
**Example response**:
.. sourcecode:: http
HTTP/1.0 201 CREATED
Content-Type: application/json
{
"bot": {
"name": "ShadowServerBot",
"url": "http://sample.com/path.html",
"id": 1
},
'message': "Bot added"
}
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:<json integer name: Bot name
:>jsonobj integer id: Unique ID of new bot
:>jsonobj integer name: bot name
:>json string message: Status message
:status 201: ASN successfully saved
:status 400: Bad request
"""
a = Bot.fromdict(request.json)
db.session.add(a)
db.session.commit()
return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \
{'Location': url_for('api.get_bot', bot_id=a.id)}
@api.route('/abusehelper/<int:bot_id>', methods=['PUT'])
@validate('abusehelper', 'update_bot')
@json_response
def update_bot(bot_id):
return NotImplemented
@api.route('/abusehelper/<int:bot_id>', methods=['DELETE'])
@json_response
def delete_bot(bot_id):
"""Delete bot
**Example request**:
.. sourcecode:: http
DELETE /api/1.0/abusehelper/1 HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"message": "Bot deleted"
}
:param bot_id: Bot unique ID.
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json string message: Action status status
:status 200: Bot was deleted
:status 404: Bot was not found
"""
a = Bot.query.filter_by(id == bot_id).delete()
if not a:
return {'message': 'No such bot'}, 404
db.session.commit()
return {'message': 'Bot deleted'}
@api.route('/abusehelper', methods=['DELETE'])
@json_response
def delete_abusehelper():
"""Clear abusehelper table
**Example request**:
.. sourcecode:: http
DELETE /api/1.0/abusehelper HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"message": "Bots deleted"
}
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json string message: Action status status
:status 200: Bot was deleted
:status 404: Bot was not found
"""
a = Bot.query.all().delete()
db.session.commit()
current_app.log.debug('Deleted {} abusehelper'.format(a))
return {'message': 'Bots deleted'}
|
Java
|
/*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
* Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of the NHIN Connect Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* END OF TERMS AND CONDITIONS
*/
package gov.hhs.fha.nhinc.common.dda;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GetDetailDataForUserRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GetDetailDataForUserRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="userId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="dataSource" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="itemId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetDetailDataForUserRequestType", propOrder = {
"userId",
"dataSource",
"itemId"
})
public class GetDetailDataForUserRequestType {
@XmlElement(required = true)
protected String userId;
@XmlElement(required = true)
protected String dataSource;
@XmlElement(required = true)
protected String itemId;
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the dataSource property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataSource() {
return dataSource;
}
/**
* Sets the value of the dataSource property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataSource(String value) {
this.dataSource = value;
}
/**
* Gets the value of the itemId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getItemId() {
return itemId;
}
/**
* Sets the value of the itemId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setItemId(String value) {
this.itemId = value;
}
}
|
Java
|
use actix::Addr;
use actix_web::{http, middleware};
use actix_web::{web, App, HttpServer};
use diesel::r2d2::{self, ConnectionManager};
use diesel::PgConnection;
use crate::database::DbExecutor;
use badge::handlers::badge_handler;
// use run::handlers::run_handler;
use status::handlers::status_handler;
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
#[derive(Clone)]
pub struct WebState {
pub db: Pool,
pub db_actor: Addr<DbExecutor>,
}
pub fn http_server(state: WebState, http_bind: String, http_port: String) {
use actix_web::middleware::cors::Cors;
HttpServer::new(move || {
App::new()
.data(state.clone())
.wrap(middleware::Logger::default())
.wrap(
Cors::new() // <- Construct CORS middleware builder
.allowed_methods(vec!["GET", "POST", "OPTION"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600),
)
.service(web::resource("/{project}/{workflow}/badge.svg").to_async(badge_handler))
.service(web::resource("/mon/status").to(status_handler))
})
.bind(format!("{}:{}", http_bind, http_port))
.unwrap()
.start();
}
|
Java
|
from django.contrib import admin
# Register your models here.
from .models import Photos
admin.site.register(Photos)
|
Java
|
#ifndef SSERVICE_LOGGER_H
#define SSERVICE_LOGGER_H
/******************************************************************************
"Copyright (c) 2015-2015, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"
******************************************************************************/
/** @file
@brief Logger system header.
*/
#include "xss_types.h"
#include "xss_error.h"
/**
* @enum log_target_t defines Types of log messages
*/
#define LOG_ERROR_VAL (0)
#define LOG_WARNING_VAL (1)
#define LOG_INFO_VAL (2)
#define LOG_ALL_VAL ( 0xff )
typedef enum
{
LOG_ERROR = LOG_ERROR_VAL, /**< error. Operation is not successfull; Continue to run */
LOG_WARNING = LOG_WARNING_VAL, /**< Warning. Operation is finished successfully, but there is something to notify (Old keys?) */
LOG_INFO = LOG_INFO_VAL, /**< Information to developer; */
LOG_ALL = LOG_ALL_VAL, /**< Cannot be passed to log, it is just set for Log filtering: Print ALL logs */
} sservice_log_level_t ;
#define LOG_SOURCE_JS_VAL (2)
#define LOG_SOURCE_BRIDGE_VAL (1)
#define LOG_SOURCE_RUNTIME_VAL (0)
typedef enum
{
LOG_SOURCE_JS=LOG_SOURCE_JS_VAL,
LOG_SOURCE_BRIDGE = LOG_SOURCE_BRIDGE_VAL,
LOG_SOURCE_RUNTIME = LOG_SOURCE_RUNTIME_VAL,
} sservice_log_source_t ;
#endif
|
Java
|
#include "Ht.h"
#include "PersBug.h"
void
CPersBug::PersBug()
{
if (PR_htValid) {
switch (PR_htInst) {
case BUG_RTN: {
if (SendReturnBusy_htmain()) {
HtRetry();
break;
}
SendReturn_htmain();
}
break;
default:
assert(0);
}
}
}
|
Java
|
# Copyright (c) 2014, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
# Thanks for using Enthought open source!
#
# Author: Enthought, Inc.
""" Tests for the BetterZoom Chaco tool """
import unittest
import numpy
from chaco.api import create_line_plot
from chaco.tools.api import BetterZoom
from enable.testing import EnableTestAssistant
class TestBetterZoomTool(EnableTestAssistant, unittest.TestCase):
""" Tests for the BetterZoom Chaco tool """
def setUp(self):
values = numpy.arange(10)
self.plot = create_line_plot((values, values))
self.plot.bounds = [100, 100]
self.plot._window = self.create_mock_window()
self.tool = BetterZoom(component=self.plot)
self.plot.active_tool = self.tool
self.plot.do_layout()
def tearDown(self):
del self.tool
del self.plot
def test_default_position(self):
tool = self.tool
# this doesn't throw an exception
self.send_key(tool, '+')
self.assertEqual(tool.position, (50, 50))
# expected behaviour for a normal zoom in operation
self.assertNotEqual(tool._index_factor, 1.0)
self.assertNotEqual(tool._value_factor, 1.0)
self.assertEqual(len(tool._history), 2)
|
Java
|
/**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.core.di.exception;
/**
* A base class for bean exceptions
*/
public class BeanException extends Exception {
private static final long serialVersionUID = 4487528732406582847L;
public BeanException(String message) {
super(message);
}
}
|
Java
|
<?php
/**
* Created by PhpStorm.
* User: wesley
* Date: 03/01/15
* Time: 10:04
*/
namespace Ordemservico\Form\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormElementErrors;
class FormElementErros extends FormElementErrors {
public function render(ElementInterface $element, array $attributes = array()){
//Associando menssagem com varivel
$messages = $element->getMessages();
//Verificando se $message está vazio
if(empty($messages)){
return '';
}
$markup = '<div class="alert alert-danger col-sm-10 col-sm-offset-2" role="alert">';
$markup .= implode(' - ', $messages);
$markup .= '</div>';
return $markup;
}
}
|
Java
|
<?php
use yii\helpers\Html;
use yii\bootstrap\Modal;
use yii\bootstrap\ButtonGroup;
use yii\widgets\Menu;
use yii\widgets\Pjax;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\TransaccionrefaccionSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Transaccionrefaccions');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="transaccionrefaccion-index col-lg-12 col-md-12 col-xs-12 well">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="col-md-12 col-lg-12 col-xs-12 well">
<?php $datagrid=[
['class' => 'kartik\grid\SerialColumn'],
// 'id_transaccionrefaccion',
[
'attribute'=>'id_lineaprovisional',
'value'=>'tblMaquinaIdMaquina.tblLineaIdLinea.tbl_linea_nombre',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>$model->tbllineaList,
'filterInputOptions'=>['placeholder' => 'Selecciona '],
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'group'=>true,
'groupFooter'=>function ($model, $key, $index, $widget) { // Closure method
return [
'mergeColumns'=>[[0,2]], // columns to merge in summary
'content'=>[ // content to show in each summary cell
0=>'Resumen (' . $model->tblMaquinaIdMaquina->tblLineaIdLinea->tbl_linea_nombre . ')',
2=>GridView::F_SUM,
3=>GridView::F_SUM,
],
'contentFormats'=>[ // content reformatting for each summary cell
2=>['format'=>'number', 'decimals'=>0],
3=>['format'=>'number', 'decimals'=>2],
],
'contentOptions'=>[ // content html attributes for each summary cell
0=>['style'=>'font-variant:small-caps'],
2=>['style'=>'text-align:right'],
3=>['style'=>'text-align:right'],
],
'options'=>['class'=>'danger','style'=>'font-weight:bold;']
];
}
],
[
'attribute'=>'tbl_maquina_id_maquina',
'value'=>'tblMaquinaIdMaquina.tbl_maquina_bim',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>$model->tblmaquinaList,
'filterInputOptions'=>['placeholder' => 'Selecciona '],
'group'=>true,
'subGroupOf'=>1,
'groupFooter'=>function ($model, $key, $index, $widget) { // Closure method
return [
'mergeColumns'=>[[3]], // columns to merge in summary
'content'=>[ // content to show in each summary cell
2=>'Resumen (' . $model->tblMaquinaIdMaquina->tbl_maquina_bim . ')',
3=>GridView::F_SUM,
],
'contentFormats'=>[ // content reformatting for each summary cell
3=>['format'=>'number', 'decimals'=>0],
4=>['format'=>'number', 'decimals'=>2],
],
'contentOptions'=>[ // content html attributes for each summary cell
2=>['style'=>'font-variant:small-caps'],
3=>['style'=>'text-align:right'],
],
'options'=>['class'=>'success','style'=>'font-weight:bold;']
];
},
],
[
'label'=>'Total',
'value'=>function ($model, $key, $index, $column) {
$precios=$model->tblItemIdItem->tblPrecios;
$costo=0;
foreach($precios as $precio){
if($precio->tbl_precio_opcion==1){
$costo=$costo+$precio->tbl_precio_precio;
}
}
return $costo*$model->sumacount;
},
],
[
'attribute'=>'mod_transaccionrefaccion_date',
'value'=>'mod_transaccionrefaccion_date',
'filter'=> kartik\daterange\DateRangePicker::widget([
'model' => $searchModel,
'attribute'=>'mod_transaccionrefaccion_date',
'convertFormat'=>true,
'pluginOptions'=>[
'locale'=>[
'format'=>'Y-m-d',
'separator' => 'to',
]
]
]),
'format' => ['date', 'php:Y-m-d'],
],
];
$exportvar=ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' =>$datagrid,
'target' => ExportMenu::TARGET_BLANK,
'asDropdown' => false,
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' =>$datagrid,
'responsive'=>true,
'panel'=>[
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i>'.Html::encode($this->title).'</h3>',
],
'toolbar'=>[
'{export}',[
'content'=>Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['reporte'], ['class' => 'btn btn-default', 'title'=> 'Reset Grid'])
]
],
'export'=>[
'itemsAfter'=> [
'<li role="presentation" class="divider"></li>',
'<li class="dropdown-header">All Data</li>',
$exportvar
]
]
]); ?>
</div>
<?php Modal::begin([
'id'=>'transaccionrefaccion-modal',
'size'=>'modal-lg'
]);
?>
<div id="transaccionrefaccion-modal-form"></div>
<?php Modal::end(); ?>
</div>
|
Java
|
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = DjangoCorrelationId
SOURCEDIR = .
BUILDDIR = ../build/sphinx
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sun Mar 01 12:04:16 AEDT 2015 -->
<title>X509AttributeCertificateHolderSelectorBuilder (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="X509AttributeCertificateHolderSelectorBuilder (Bouncy Castle Library 1.52 API Specification)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.52</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/cert/selector/X509CertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html" target="_top">Frames</a></li>
<li><a href="X509AttributeCertificateHolderSelectorBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.bouncycastle.cert.selector</div>
<h2 title="Class X509AttributeCertificateHolderSelectorBuilder" class="title">Class X509AttributeCertificateHolderSelectorBuilder</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.bouncycastle.cert.selector.X509AttributeCertificateHolderSelectorBuilder</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">X509AttributeCertificateHolderSelectorBuilder</span>
extends java.lang.Object</pre>
<div class="block">This class builds selectors according to the set criteria.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#X509AttributeCertificateHolderSelectorBuilder()">X509AttributeCertificateHolderSelectorBuilder</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)">addTargetGroup</a></strong>(org.bouncycastle.asn1.x509.GeneralName group)</code>
<div class="block">Adds a target group criterion for the attribute certificate to the target
information extension criteria.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#addTargetName(org.bouncycastle.asn1.x509.GeneralName)">addTargetName</a></strong>(org.bouncycastle.asn1.x509.GeneralName name)</code>
<div class="block">Adds a target name criterion for the attribute certificate to the target
information extension criteria.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector">X509AttributeCertificateHolderSelector</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#build()">build</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setAttributeCert(org.bouncycastle.cert.X509AttributeCertificateHolder)">setAttributeCert</a></strong>(<a href="../../../../org/bouncycastle/cert/X509AttributeCertificateHolder.html" title="class in org.bouncycastle.cert">X509AttributeCertificateHolder</a> attributeCert)</code>
<div class="block">Set the attribute certificate to be matched.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setAttributeCertificateValid(java.util.Date)">setAttributeCertificateValid</a></strong>(java.util.Date attributeCertificateValid)</code>
<div class="block">Set the time, when the certificate must be valid.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setHolder(org.bouncycastle.cert.AttributeCertificateHolder)">setHolder</a></strong>(<a href="../../../../org/bouncycastle/cert/AttributeCertificateHolder.html" title="class in org.bouncycastle.cert">AttributeCertificateHolder</a> holder)</code>
<div class="block">Sets the holder.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setIssuer(org.bouncycastle.cert.AttributeCertificateIssuer)">setIssuer</a></strong>(<a href="../../../../org/bouncycastle/cert/AttributeCertificateIssuer.html" title="class in org.bouncycastle.cert">AttributeCertificateIssuer</a> issuer)</code>
<div class="block">Sets the issuer the attribute certificate must have.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setSerialNumber(java.math.BigInteger)">setSerialNumber</a></strong>(java.math.BigInteger serialNumber)</code>
<div class="block">Sets the serial number the attribute certificate must have.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setTargetGroups(java.util.Collection)">setTargetGroups</a></strong>(java.util.Collection names)</code>
<div class="block">Adds a collection with target groups criteria.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#setTargetNames(java.util.Collection)">setTargetNames</a></strong>(java.util.Collection names)</code>
<div class="block">Adds a collection with target names criteria.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="X509AttributeCertificateHolderSelectorBuilder()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>X509AttributeCertificateHolderSelectorBuilder</h4>
<pre>public X509AttributeCertificateHolderSelectorBuilder()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="setAttributeCert(org.bouncycastle.cert.X509AttributeCertificateHolder)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAttributeCert</h4>
<pre>public void setAttributeCert(<a href="../../../../org/bouncycastle/cert/X509AttributeCertificateHolder.html" title="class in org.bouncycastle.cert">X509AttributeCertificateHolder</a> attributeCert)</pre>
<div class="block">Set the attribute certificate to be matched. If <code>null</code> is
given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attributeCert</code> - The attribute certificate holder to set.</dd></dl>
</li>
</ul>
<a name="setAttributeCertificateValid(java.util.Date)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAttributeCertificateValid</h4>
<pre>public void setAttributeCertificateValid(java.util.Date attributeCertificateValid)</pre>
<div class="block">Set the time, when the certificate must be valid. If <code>null</code>
is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attributeCertificateValid</code> - The attribute certificate validation
time to set.</dd></dl>
</li>
</ul>
<a name="setHolder(org.bouncycastle.cert.AttributeCertificateHolder)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHolder</h4>
<pre>public void setHolder(<a href="../../../../org/bouncycastle/cert/AttributeCertificateHolder.html" title="class in org.bouncycastle.cert">AttributeCertificateHolder</a> holder)</pre>
<div class="block">Sets the holder. If <code>null</code> is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>holder</code> - The holder to set.</dd></dl>
</li>
</ul>
<a name="setIssuer(org.bouncycastle.cert.AttributeCertificateIssuer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setIssuer</h4>
<pre>public void setIssuer(<a href="../../../../org/bouncycastle/cert/AttributeCertificateIssuer.html" title="class in org.bouncycastle.cert">AttributeCertificateIssuer</a> issuer)</pre>
<div class="block">Sets the issuer the attribute certificate must have. If <code>null</code>
is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>issuer</code> - The issuer to set.</dd></dl>
</li>
</ul>
<a name="setSerialNumber(java.math.BigInteger)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSerialNumber</h4>
<pre>public void setSerialNumber(java.math.BigInteger serialNumber)</pre>
<div class="block">Sets the serial number the attribute certificate must have. If
<code>null</code> is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>serialNumber</code> - The serialNumber to set.</dd></dl>
</li>
</ul>
<a name="addTargetName(org.bouncycastle.asn1.x509.GeneralName)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addTargetName</h4>
<pre>public void addTargetName(org.bouncycastle.asn1.x509.GeneralName name)</pre>
<div class="block">Adds a target name criterion for the attribute certificate to the target
information extension criteria. The <code>X509AttributeCertificateHolder</code>
must contain at least one of the specified target names.
<p>
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - The name as a GeneralName (not <code>null</code>)</dd></dl>
</li>
</ul>
<a name="setTargetNames(java.util.Collection)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTargetNames</h4>
<pre>public void setTargetNames(java.util.Collection names)
throws java.io.IOException</pre>
<div class="block">Adds a collection with target names criteria. If <code>null</code> is
given any will do.
<p>
The collection consists of either GeneralName objects or byte[] arrays representing
DER encoded GeneralName structures.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>names</code> - A collection of target names.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - if a parsing error occurs.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#addTargetName(org.bouncycastle.asn1.x509.GeneralName)"><code>addTargetName(org.bouncycastle.asn1.x509.GeneralName)</code></a></dd></dl>
</li>
</ul>
<a name="addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addTargetGroup</h4>
<pre>public void addTargetGroup(org.bouncycastle.asn1.x509.GeneralName group)</pre>
<div class="block">Adds a target group criterion for the attribute certificate to the target
information extension criteria. The <code>X509AttributeCertificateHolder</code>
must contain at least one of the specified target groups.
<p>
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>group</code> - The group as GeneralName form (not <code>null</code>)</dd></dl>
</li>
</ul>
<a name="setTargetGroups(java.util.Collection)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTargetGroups</h4>
<pre>public void setTargetGroups(java.util.Collection names)
throws java.io.IOException</pre>
<div class="block">Adds a collection with target groups criteria. If <code>null</code> is
given any will do.
<p>
The collection consists of <code>GeneralName</code> objects or <code>byte[]</code representing DER
encoded GeneralNames.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>names</code> - A collection of target groups.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - if a parsing error occurs.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html#addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)"><code>addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)</code></a></dd></dl>
</li>
</ul>
<a name="build()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>build</h4>
<pre>public <a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector">X509AttributeCertificateHolderSelector</a> build()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.52</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/cert/selector/X509CertificateHolderSelector.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/cert/selector/X509AttributeCertificateHolderSelectorBuilder.html" target="_top">Frames</a></li>
<li><a href="X509AttributeCertificateHolderSelectorBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
/* iCheck plugin Square skin, black
----------------------------------- */
.icheckbox_square,
.iradio_square {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 22px;
height: 22px;
background: url(square.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_square {
background-position: 0 0;
}
.icheckbox_square.hover {
background-position: -24px 0;
}
.icheckbox_square.checked {
background-position: -48px 0;
}
.icheckbox_square.disabled {
background-position: -72px 0;
cursor: default;
}
.icheckbox_square.checked.disabled {
background-position: -96px 0;
}
.iradio_square {
background-position: -120px 0;
}
.iradio_square.hover {
background-position: -144px 0;
}
.iradio_square.checked {
background-position: -168px 0;
}
.iradio_square.disabled {
background-position: -192px 0;
cursor: default;
}
.iradio_square.checked.disabled {
background-position: -216px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi), (min-resolution: 1.25dppx) {
.icheckbox_square,
.iradio_square {
background-image: url(square@2x.png);
-webkit-background-size: 240px 24px;
background-size: 240px 24px;
}
}
|
Java
|
import pytest
from py4jdbc.dbapi2 import connect, Connection
from py4jdbc.resultset import ResultSet
from py4jdbc.exceptions.dbapi2 import Error
def test_connect(gateway):
url = "jdbc:derby:memory:testdb;create=true"
conn = connect(url, gateway=gateway)
cur = conn.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs, ResultSet)
def test_execute(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs, ResultSet)
def test_execute_with_params(derby):
derby.autocommit = False
cur = derby.cursor()
cur.execute("create schema x_with_params")
cur.execute("create table x_with_params.cowtest(a int, b char(1))")
# Verify table is empty.
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == 0
# Insert one with parameter binding..
sql = "insert into x_with_params.cowtest (a, b) values (?, ?)"
cur.execute(sql, (12, "m"))
# Verify there's 1 row.
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == 1
# Insert a bunch.
params = list(enumerate("thecowsaremooing"))
cur.executemany(sql, params)
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == len("thecowsaremooing") + 1
derby.rollback()
derby.autocommit = True
def test_fetchone(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs.fetchone(), rs.Row)
def test_fetchmany(derby):
'''Assert all rows of result set have the correct class.
'''
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs.fetchmany(5)})
def test_fetchManyCount(derby):
derby.autocommit = False
cur = derby.cursor()
cur.execute("create schema x_with_params")
cur.execute("create table x_with_params.cowtest(a int, b char(1))")
sql = "insert into x_with_params.cowtest (a, b) values (?, ?)"
params = list(enumerate("thecowsaremooing"))
cur.executemany(sql, params)
rs = cur.execute("select a from x_with_params.cowtest")
ress = []
while True:
x = rs.fetchmany(3)
ress.append(x)
if len(x) < 3:
break
derby.rollback()
derby.autocommit = True
assert sum(map(len, ress)) == len("thecowsaremooing")
def test_fetchall(derby):
'''Assert all rows of result set have the correct class.
'''
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs.fetchall()})
def test_Cursor__iter__(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs})
def test_Cursor__iter__(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
# Exhaust all rows.
list(rs)
assert rs.fetchone() == None
def test_close_and_execute(derby):
cur = derby.cursor()
cur.close()
with pytest.raises(Error):
cur.execute("select * from SYS.SYSTABLES")
def test_close_and_fetchone(derby):
cur = derby.cursor()
cur.execute("select * from SYS.SYSTABLES")
cur.close()
with pytest.raises(Error):
cur.fetchone()
def test_close_twice(derby):
cur = derby.cursor()
cur.close()
with pytest.raises(Error):
cur.close()
|
Java
|
## How to be a contributor to this project
### Are you submitting a pull request?
* Make sure to fill out an issue for your PR, so that we have traceability as to what you are trying to fix,
versus how you fixed it.
* Spaces (not tabs), and 2 of them, that's what we like. Set your code style :)
* Sign the [Sonatype CLA](https://sonatypecla.herokuapp.com/sign-cla)
* Try to fix one thing per pull request! Many people work on this code, so the more focused your changes are, the less
of a headache other people will have when they merge their work in.
* Ensure your Pull Request passes tests either locally or via CircleCI (it will run automatically on your PR)
* Make sure to add yourself or your organization to CONTRIBUTORS.md as a part of your PR, if you are new to the project!
* If you're stuck, ask our [gitter channel](https://gitter.im/sonatype/nexus-developers)! There are a number of
experienced programmers who are happy to help with learning and troubleshooting.
### Are you new and looking to dive in?
* Check our issues to see if there is something you can dive in to.
* Come hang out with us at our [gitter channel](https://gitter.im/sonatype/nexus-developers).
|
Java
|
# writestream-promise
Adds WriteStream.itsa_endPromise(): WriteStream.end() as a Promise.
|
Java
|
"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
|
Java
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\WindowSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="window-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'status_ventana') ?>
<?= $form->field($model, 'status_cortina') ?>
<?= $form->field($model, 'rain_sensor') ?>
<?= $form->field($model, 'light_sensor') ?>
<?= $form->field($model, 'voice_sensor') ?>
<?php // echo $form->field($model, 'datetime') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
Java
|
from importlib import import_module
from inspect import getdoc
def attribs(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d)
|
Java
|
#include "Statistics.hpp"
#include "CaptureInstance.hpp"
#include "MainWindow.hpp"
#include "ui_Statistics.h"
using namespace EPL_Viz;
using namespace EPL_DataCollect;
Statistics::Statistics(MainWindow *parent) : QDialog(parent), ui(new Ui::Statistics), mw(parent) {
ui->setupUi(this);
refresh();
}
Statistics::~Statistics() { delete ui; }
void Statistics::refresh() {
CaptureInstance *ci = mw->getCaptureInstance();
auto stats = ci->getCycleBuilder()->getStats();
auto ihStats = ci->getInputHandler()->getStats();
ui->List->clear();
// Make sure not to devide by 0
if (stats.cycleCount == 0)
stats.cycleCount = 1;
if (ihStats.packetsParsed == 0)
ihStats.packetsParsed = 1;
if (ihStats.cyclesParsed == 0)
ihStats.cyclesParsed = 1;
QList<QTreeWidgetItem *> items;
QTreeWidgetItem * pItem = nullptr;
items.append(new QTreeWidgetItem({"Cycle count", std::to_string(stats.cycleCount).c_str()}));
items.append(new QTreeWidgetItem({"Cycle count", std::to_string(stats.cycleCount).c_str()}));
items.append(new QTreeWidgetItem({"Packet count", std::to_string(stats.packetCount).c_str()}));
items.append(new QTreeWidgetItem({"Events count", std::to_string(stats.eventsCount).c_str()}));
items.append(new QTreeWidgetItem({"Packet parsed", std::to_string(ihStats.packetsParsed).c_str()}));
items.append(new QTreeWidgetItem({"Cycles parsed", std::to_string(ihStats.cyclesParsed).c_str()}));
items.append(new QTreeWidgetItem({"Cycle Processing time", ""}));
pItem = items.back();
items.append(new QTreeWidgetItem(pItem, {"Total", (std::to_string(stats.totalTime.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(stats.totalTime.count() / stats.cycleCount) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Time waited for packets to be parsed", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(stats.waitForPacketsTime.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(stats.waitForPacketsTime.count() / stats.cycleCount) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Packets parsing time", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(ihStats.timePacketsParsed.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem,
{"Average", (std::to_string(ihStats.timePacketsParsed.count() / ihStats.packetsParsed) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Packets of a Cycle parsing time", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(ihStats.timeCyclesParsed.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(ihStats.timeCyclesParsed.count() / ihStats.cyclesParsed) + " ns").c_str()}));
ui->List->addTopLevelItems(items);
ui->List->expandAll();
ui->List->header()->resizeSection(0, 275);
}
|
Java
|
---
layout: organization
category: national
title: Sereolipi Nomadic Education Foundation Inc.
impact_area: Children
keywords:
location_services:
location_offices:
website: www.thorntreeproject.org
description:
mission: |
Our mission is to help educate the children of traditional nomadic families in Northern Samburu. We work to help more Samburu children go to school and receive the level of education they desire, whether that is primary school, high school, technical school, or college. With hard work, resourcefulness, and a little help from the outside world, the Samburu people have begun to create significant, meaningful, and measurable change by providing education for their children. The Thorn Tree Project exists to do all it can to support their efforts.
Our mission comes from the Samburu people themselves. It is a privilege to be invited into the Samburu tribe, and we make sure that everything we do is in tune with their culture and aligned with their goals. We aim to have the smallest possible footprint in Samburu, maintaining our focus on education.
cash_grants:
grants:
service_opp:
services:
learn:
cont_relationship:
salutation:
first_name:
last_name:
title_contact_person:
city: Troutman
state: NC
address: |
PO Box 263
Troutman NC 28166
lat: 35.677955
lng: -80.879258
phone:
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---
|
Java
|
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JustLogic nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Vectors/Sqr Magnitude (Vector4)")]
[UnitFriendlyName("Sqr Magnitude")]
[UnitUsage(typeof(System.Single), HideExpressionInActionsList = true)]
public class JLVector4SqrMagnitude : JLExpression
{
[Parameter(ExpressionType = typeof(Vector4))]
public JLExpression OperandValue;
public override object GetAnyResult(IExecutionContext context)
{
Vector4 opValue = OperandValue.GetResult<Vector4>(context);
return opValue.SqrMagnitude();
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Sat Oct 20 16:08:50 CDT 2012 -->
<TITLE>
I-Index
</TITLE>
<META NAME="date" CONTENT="2012-10-20">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="I-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR>
<A NAME="_I_"><!-- --></A><H2>
<B>I</B></H2>
<DL>
<DT><A HREF="../org/epri/pt2/gui/FuzzTestUtils.html#initFuzzTestsFromDatabase()"><B>initFuzzTestsFromDatabase()</B></A> -
Method in class org.epri.pt2.gui.<A HREF="../org/epri/pt2/gui/FuzzTestUtils.html" title="class in org.epri.pt2.gui">FuzzTestUtils</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/RequestPanel.html#initRequestPacketTable()"><B>initRequestPacketTable()</B></A> -
Method in class org.epri.pt2.fuzzer.<A HREF="../org/epri/pt2/fuzzer/RequestPanel.html" title="class in org.epri.pt2.fuzzer">RequestPanel</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/ResponsePanel.html#initResponsePacketTable()"><B>initResponsePacketTable()</B></A> -
Method in class org.epri.pt2.fuzzer.<A HREF="../org/epri/pt2/fuzzer/ResponsePanel.html" title="class in org.epri.pt2.fuzzer">ResponsePanel</A>
<DD>
<DT><A HREF="../org/epri/pt2/gui/StatusArea.html#initTabComponent(int, java.lang.String, org.epri.pt2.gui.TestExecutionTask)"><B>initTabComponent(int, String, TestExecutionTask)</B></A> -
Method in class org.epri.pt2.gui.<A HREF="../org/epri/pt2/gui/StatusArea.html" title="class in org.epri.pt2.gui">StatusArea</A>
<DD>
<DT><A HREF="../org/epri/pt2/InterfaceMapper.html" title="class in org.epri.pt2"><B>InterfaceMapper</B></A> - Class in <A HREF="../org/epri/pt2/package-summary.html">org.epri.pt2</A><DD>The InterfaceMapper class provides a static mapping method
<A HREF="../org/epri/pt2/InterfaceMapper.html#getClass(org.epri.pt2.InterfaceType)"><CODE>InterfaceMapper.getClass(InterfaceType)</CODE></A> which returns an AbstractIfaceDO instance.<DT><A HREF="../org/epri/pt2/InterfaceMapper.html#InterfaceMapper()"><B>InterfaceMapper()</B></A> -
Constructor for class org.epri.pt2.<A HREF="../org/epri/pt2/InterfaceMapper.html" title="class in org.epri.pt2">InterfaceMapper</A>
<DD>
<DT><A HREF="../org/epri/pt2/InterfaceType.html" title="enum in org.epri.pt2"><B>InterfaceType</B></A> - Enum in <A HREF="../org/epri/pt2/package-summary.html">org.epri.pt2</A><DD>A list of permissible interface types.<DT><A HREF="../org/epri/pt2/gui/model/MyTableModel.html#isCellEditable(int, int)"><B>isCellEditable(int, int)</B></A> -
Method in class org.epri.pt2.gui.model.<A HREF="../org/epri/pt2/gui/model/MyTableModel.html" title="class in org.epri.pt2.gui.model">MyTableModel</A>
<DD>
<DT><A HREF="../org/epri/pt2/gui/model/TestCaseDOTableModel.html#isCellEditable(int, int)"><B>isCellEditable(int, int)</B></A> -
Method in class org.epri.pt2.gui.model.<A HREF="../org/epri/pt2/gui/model/TestCaseDOTableModel.html" title="class in org.epri.pt2.gui.model">TestCaseDOTableModel</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/AbstractIfaceDO.html#isConnected()"><B>isConnected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/AbstractIfaceDO.html" title="class in org.epri.pt2.DO">AbstractIfaceDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isEnabled()"><B>isEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html#isErroredOrClosed()"><B>isErroredOrClosed()</B></A> -
Method in class org.epri.pt2.fuzzer.request.<A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html" title="class in org.epri.pt2.fuzzer.request">SocketHandler</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isFilteringEnabled()"><B>isFilteringEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/PacketDO.html#isFuzzed()"><B>isFuzzed()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isFuzzingEnabled()"><B>isFuzzingEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isInterceptEnabled()"><B>isInterceptEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html#isLeaf()"><B>isLeaf()</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html" title="class in org.epri.pt2.packetparser.treemodel">XMLNode</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLTreeModel.html#isLeaf(java.lang.Object)"><B>isLeaf(Object)</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLTreeModel.html" title="class in org.epri.pt2.packetparser.treemodel">XMLTreeModel</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html#isOpen()"><B>isOpen()</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html" title="class in org.epri.pt2.sniffer">PCAPEthListener</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferController.html#isOpen(org.epri.pt2.DO.DeviceDO)"><B>isOpen(DeviceDO)</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferController.html" title="class in org.epri.pt2.sniffer">SnifferController</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferInterface.html#isOpen()"><B>isOpen()</B></A> -
Method in interface org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferInterface.html" title="interface in org.epri.pt2.sniffer">SnifferInterface</A>
<DD>
<DT><A HREF="../org/epri/pt2/reassembler/TcpLink.html#isProcessed()"><B>isProcessed()</B></A> -
Method in class org.epri.pt2.reassembler.<A HREF="../org/epri/pt2/reassembler/TcpLink.html" title="class in org.epri.pt2.reassembler">TcpLink</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html#isReadyToSend()"><B>isReadyToSend()</B></A> -
Method in class org.epri.pt2.fuzzer.request.<A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html" title="class in org.epri.pt2.fuzzer.request">SocketHandler</A>
<DD>
<DT><A HREF="../org/epri/pt2/reassembler/TcpReassembler.html#isRunning()"><B>isRunning()</B></A> -
Method in class org.epri.pt2.reassembler.<A HREF="../org/epri/pt2/reassembler/TcpReassembler.html" title="class in org.epri.pt2.reassembler">TcpReassembler</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/DataTypeDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/DataTypeDO.html" title="class in org.epri.pt2.DO">DataTypeDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/FuzzTestDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/FuzzTestDO.html" title="class in org.epri.pt2.DO">FuzzTestDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/PacketDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/TestCaseDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/TestCaseDO.html" title="class in org.epri.pt2.DO">TestCaseDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html#isSnifferType(int)"><B>isSnifferType(int)</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html" title="class in org.epri.pt2.sniffer">PCAPEthListener</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferInterface.html#isSnifferType(int)"><B>isSnifferType(int)</B></A> -
Method in interface org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferInterface.html" title="interface in org.epri.pt2.sniffer">SnifferInterface</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isSSLEnabled()"><B>isSSLEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html#isText()"><B>isText()</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html" title="class in org.epri.pt2.packetparser.treemodel">XMLNode</A>
<DD>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR>
</BODY>
</HTML>
|
Java
|
class Requirement(object):
"""
Requirements are the basis for Dominion. They define
what needs to exist on a host/role, or perhaps what *mustn't* exist.
Requirements are defined on Roles.
"""
creation_counter = 0
"The base class for requirements."
def __init__(self, required=True, ensure=None, depends=None, post=None):
self.required = required
self.ensure = ensure or "exists"
self.depends = depends or ()
if self.ensure == "removed":
self.required = False
self.post = post or ()
# Increase the creation counter, and save our local copy.
self.creation_counter = Requirement.creation_counter
Requirement.creation_counter += 1
def __call__(self):
self.apply()
def apply(self):
if self.ensure == "exists" or self.required:
if hasattr(self, 'install'):
return self.install()
if self.ensure == "removed":
if hasattr(self, 'uninstall'):
return self.uninstall()
|
Java
|
<?php
use app\components\Formatter;
use yii\helpers\Html;
?>
<div class="rep-wrapper">
<div id="stats">
<div id="rep-page-container">
<table class="rep-table">
<tbody>
<?php foreach ($reputes as $date => $repute): ?>
<tr class="rep-table-row">
<td class="rep-cell">
<span class="rep-up"><?php echo $repute['total']; ?></span>
</td>
<td title="<?php echo $date; ?>" class="rep-day ">
<a class="load-body expander-arrow-small-hide hide-body expander-arrow-small-show" style=""></a>
<?php echo $date; ?>
</td>
</tr>
<tr class="loaded-body">
<td style="height: 0px; padding: 0px;" class="body-container body-loaded" colspan="2">
<div style="display: block;">
<div class="rep-breakdown">
<table class="tbl-reputation">
<tbody>
<?php foreach ($repute['list'] as $item): ?>
<tr class="rep-breakdown-row rep-recent-row expandable-row">
<td class="rep-left">
<span class="rep-up"><?php echo $item->reputation; ?></span>
</td>
<td title="<?php echo Formatter::time($item->time); ?>" class="rep-time"><?php echo Formatter::ago($item->time); ?></td>
<td class="rep-desc"><?php echo $item->lng; ?></td>
<td class="rep-link async-load load-prepped">
<?php
$url = $item->question->url;
if ($item->apostid > 0) {
$url .= '#' . $item->apostid;
}
echo Html::a(Html::encode($item->question->title), $url, array('class' => "answer-hyperlink"));
?>
</td>
</tr>
<tr class="loaded-body">
<td colspan="4" class="body-container" style="padding: 0px;"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
expandPostBody('.tbl-reputation td.rep-link.async-load:not(.load-prepped)', null, null, 4);
});
</script>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= yii\widgets\LinkPager::widget(['pagination' => $pages, 'options' => ['id' => 'reputation-pager', 'class' => 'pagination']]); ?>
<script type="text/javascript">
var reputationView = 'post';
var reputationPageSize = 30;
$(function () {
expandPostBody('.rep-table td.async-load:not(.load-prepped)', '', null, 2);
if (!$('.rep-day .expander-arrow-small-hide').length)
$(".rep-table .load-body").slice(0, 3).click();
});
</script>
</div>
</div>
</div>
|
Java
|
include ../../Library/GNU.mk
Title= libzip
Name= libzip
Version= 0.12.2
Revision= 0
Site= http://nih.at/libzip/
Source= http://nih.at/libzip//$(Name)-$(Version).tar.bz2
License= BSD
LicenseFile= $(SourceDir)/LICENSE
define test_inner_hook
/usr/local/bin/zipcmp -h
/usr/local/bin/zipmerge -h
endef
|
Java
|
package registry
import (
"crypto/tls"
"fmt"
"log"
"net/http"
"strings"
)
type LogfCallback func(format string, args ...interface{})
/*
* Discard log messages silently.
*/
func Quiet(format string, args ...interface{}) {
/* discard logs */
}
/*
* Pass log messages along to Go's "log" module.
*/
func Log(format string, args ...interface{}) {
log.Printf(format, args...)
}
type Registry struct {
URL string
Client *http.Client
Logf LogfCallback
}
/*
* Create a new Registry with the given URL and credentials, then Ping()s it
* before returning it to verify that the registry is available.
*
* You can, alternately, construct a Registry manually by populating the fields.
* This passes http.DefaultTransport to WrapTransport when creating the
* http.Client.
*/
func New(registryURL, username, password string) (*Registry, error) {
transport := http.DefaultTransport
return newFromTransport(registryURL, username, password, transport, Log)
}
/*
* Create a new Registry, as with New, using an http.Transport that disables
* SSL certificate verification.
*/
func NewInsecure(registryURL, username, password string) (*Registry, error) {
transport := &http.Transport{
TLSClientConfig: &tls.Config{
// TODO: Why?
InsecureSkipVerify: true, //nolint:gosec
},
}
return newFromTransport(registryURL, username, password, transport, Log)
}
/*
* Given an existing http.RoundTripper such as http.DefaultTransport, build the
* transport stack necessary to authenticate to the Docker registry API. This
* adds in support for OAuth bearer tokens and HTTP Basic auth, and sets up
* error handling this library relies on.
*/
func WrapTransport(transport http.RoundTripper, url, username, password string) http.RoundTripper {
tokenTransport := &TokenTransport{
Transport: transport,
Username: username,
Password: password,
}
basicAuthTransport := &BasicTransport{
Transport: tokenTransport,
URL: url,
Username: username,
Password: password,
}
errorTransport := &ErrorTransport{
Transport: basicAuthTransport,
}
return errorTransport
}
func newFromTransport(registryURL, username, password string, transport http.RoundTripper, logf LogfCallback) (*Registry, error) {
url := strings.TrimSuffix(registryURL, "/")
transport = WrapTransport(transport, url, username, password)
registry := &Registry{
URL: url,
Client: &http.Client{
Transport: transport,
},
Logf: logf,
}
if err := registry.Ping(); err != nil {
return nil, err
}
return registry, nil
}
func (r *Registry) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", r.URL, pathSuffix)
return url
}
func (r *Registry) Ping() error {
url := r.url("/v2/")
r.Logf("registry.ping url=%s", url)
resp, err := r.Client.Get(url)
if resp != nil {
defer resp.Body.Close()
}
return err
}
|
Java
|
/* CoAP on Moterunner Demonstration
* Copyright (c) 2013-2014, SAP AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the SAP AG nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Contributors:
* Matthias Thoma
* Martin Zabel
* Theofilos Kakantousis
*
* The following things need to be added before any public release:
* 3. Consider to add TTL / Resend stuff (see hellosensor.java)
* 4. Have a look at rules for message id and consider to move it either here or to some generic class
*/
package com.sap.coap;
import com.ibm.saguaro.system.*;
import com.ibm.iris.*;
import com.ibm.saguaro.mrv6.*;
//##if LOGGING
import com.ibm.saguaro.logger.*;
//##endif
public class Message {
public byte[] header = new byte[4];
public byte[] token = null;
public byte[] payload = null;
public int payloadLength = 0;
public byte[] options;
public int optionArraySize = 0;
public int roundCounter = 0;
@Immutable public static final byte CON = 0x00;
@Immutable public static final byte NON = 0x01;
@Immutable public static final byte ACK = 0x02;
@Immutable public static final byte RST = 0x03;
@Immutable public static final byte EMPTY = 0x00;
@Immutable public static final byte GET = 0x01;
@Immutable public static final byte POST = 0x02;
@Immutable public static final byte PUT = 0x03;
@Immutable public static final byte DELETE = 0x04;
public final void setPayload(byte[] mypayload){
this.payload = mypayload;
this.payloadLength = mypayload.length;
}
public Message() {
header[0] = 0x40; // set the version number
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type"> something </param>
/// <param name="tokenLen"> token legnth </param>
/// <param name="code"> CoAP message code </param>
/// <param name="msgid"> CoAP message id </param>
public Message(byte type, byte tokenLen, byte code, int msgid) {
setMessageHeader(type, tokenLen, code, msgid);
}
public final void setMessageHeader(byte type, byte tokenLen, byte code, int msgid) {
header[0] = (byte) ((0x40 | (type << 4)) | tokenLen);
header[1] = code;
Util.set16be(header,2,msgid);
}
public static byte createResponseCode(final byte cl, final byte cc) {
return (byte) ((cl << 5) | cc);
}
public final byte getVersion() {
return (byte) ((header[0] >>> 6) & 0x03);
}
public final byte getType() {
return (byte) ((header[0] & 0x30) >> 4);
}
public final void setType(final byte type) {
byte tl = (byte) (header [0] & 0x0F);
header[0] = (byte) ((0x40 | (type << 4)) | tl); // set the version number
}
public final byte getTokenLength() {
return (byte) (header[0] & 0x0F);
}
public final byte getCode() {
return header[1];
}
public final int getMessageId() {
return Util.get16be(header,2);
}
public final void clearOptions() {
options=null;
optionArraySize=0;
}
public final void clearPayload() {
payloadLength = 0;
payload = null;
}
public final byte[] getPayload() {
return this.payload;
}
public final int getPayloadSize() {
return this.payloadLength;
}
public byte[] getURIfromOptionArray() {
int partNo = 0;
int bufferOffset = 0;
int offset = getOffsetOfOptionWithId(11, partNo);
if (offset<0)
return null;
int bufferSize = 0;
// Calculate buffer size
int firstOffset = offset;
while (offset>=0) {
if (partNo>0)
bufferSize++;
int valueSize = getValueSizeOfOptionWithOffset(offset);
bufferSize += valueSize;
partNo++;
offset = getOffsetOfOptionWithId(11, partNo);
}
byte[] buffer = new byte[bufferSize];
partNo=0;
offset = getOffsetOfOptionWithId(11, partNo);
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
while (data != null) {
if (partNo>0) {
buffer[bufferOffset]='/';
bufferOffset++;
}
partNo++;
Util.copyData(data, 0, buffer, bufferOffset, valueSize);
bufferOffset += valueSize;
offset = getOffsetOfOptionWithId(11, partNo);
data = null;
if (offset>=0) {
valueSize = getValueSizeOfOptionWithOffset(offset);
data = getValueOfOptionWithOffset(offset);
}
}
return buffer;
}
public boolean hasOption(int id) {
return (getOffsetOfOptionWithId(id,0) != -1);
}
public void insertOption(int id, byte[] value, int valueSize) {
//1. find position
// an ascending order of the options has to be kept
// find start offsets of the 'enclosing' options left and right of the one to insert
// special case: inserting at the beginning: offsetRightOption = 0
// special case: inserting at the end: offsetRightOption = optionArraySize (i.e. points behind the array)
int offsetRightOption = 0;
int idRightOption = 0;
int idLeftOption = 0;
while(offsetRightOption < optionArraySize) { //if the loop is not left by a break, the option has to be inserted at the end
idRightOption = idOfOptionWithOffset(options, offsetRightOption, idRightOption);
if(idRightOption > id) { //insertion point found
break;
}
idLeftOption = idRightOption;
offsetRightOption = findOffsetOfNextOption(options, offsetRightOption);
}
//2. calculate value length field size for this option
int optionExtendedLengthFieldSize = getExtendedOptionFieldSizeFor(valueSize);
//3. calculate delta value for this option.
// depends on the previous id (being 0 when no previous option exists)
int delta = id - idLeftOption;
//4. calculate delta field size for this option
int optionExtendedDeltaFieldSize = getExtendedOptionFieldSizeFor(delta);
//5. recalculate the delta field size for the next option
// the delta value for the next option decreases due to the insertion
// this may result in less bytes being used for the size field
int deltaFieldSizeRightOption = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaRightOptionNew = 0;
int extendedDeltaFieldSizeDifferenceRightOption = 0;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = idRightOption - id;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
extendedDeltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOption - deltaFieldSizeRightOptionNew;
}
//7. calculate total size of new option array
int optionArraySizeNew = optionArraySize
+ 1
+ optionExtendedLengthFieldSize
+ optionExtendedDeltaFieldSize
+ valueSize
- extendedDeltaFieldSizeDifferenceRightOption;
//8. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//9. copy options until insertion point to new array
if(offsetRightOption>0) {
Util.copyData(options, 0, optionsNew, 0, offsetRightOption);
}
int currentOffset = offsetRightOption; //next position to read from the old options where no additional option is present. points now to the header byte of the next option
int offsetFirstByte = offsetRightOption; //points to the header byte of the option to insert
int currentOffsetNew = offsetFirstByte+1; //next position to write in the new array (after the header byte of the option to insert)
//10. write delta
if(optionExtendedDeltaFieldSize == 1) {
optionsNew[offsetFirstByte] += 13 << 4;
optionsNew[currentOffsetNew] = (byte)(delta-13);
}
else if(optionExtendedDeltaFieldSize == 2) {
optionsNew[offsetFirstByte] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew, delta-269);
}
else { //optionExtendedDeltaFieldSize == 0
optionsNew[offsetFirstByte] += delta << 4;
}
currentOffsetNew += optionExtendedDeltaFieldSize;
//11. write value length
if(optionExtendedLengthFieldSize == 1) {
optionsNew[offsetFirstByte] += 13;
optionsNew[currentOffsetNew] = (byte)(valueSize-13);
}
else if(optionExtendedLengthFieldSize == 2) {
optionsNew[offsetFirstByte] += 14;
Util.set16(optionsNew, currentOffsetNew, valueSize-269);
}
else { //optionExtendedLengthFieldSize == 0
optionsNew[offsetFirstByte] += valueSize;
}
currentOffsetNew += optionExtendedLengthFieldSize;
//12. copy value
if(valueSize>0) {
Util.copyData(value, 0, optionsNew, currentOffsetNew, valueSize);
}
currentOffsetNew += valueSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//13. write header of next option with adjusted delta
//length stays constant, delta is erased
optionsNew[currentOffsetNew] = (byte) (options[currentOffset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[currentOffsetNew] += 13 << 4;
optionsNew[currentOffsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[currentOffsetNew] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[currentOffsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
currentOffsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
currentOffset += 1+deltaFieldSizeRightOption;
//14. copy rest of array (= next option's extended value length field, next option's value, all subsequent options)
int restLength = optionArraySize - currentOffset;
Util.copyData(options, currentOffset, optionsNew, currentOffsetNew, restLength);
}
//15. replace old options by new
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public int getOffsetOfOptionWithId(int wantedOptionId, int matchNumber) {
int currentOptionOffset = 0;
int currentDelta = 0;
while(currentOptionOffset < optionArraySize) {
int currentOptionId = idOfOptionWithOffset(options, currentOptionOffset, currentDelta);
if(currentOptionId == wantedOptionId) { //first of the options has been found. iterate them until the right match number is found
for(int i = 0; i<matchNumber; i++) {
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
if(currentOptionOffset == optionArraySize || (options[currentOptionOffset] & 0xF0) != 0x00) {
return -1; //array length has been exceeded or the delta is not 0, i.e. an option with an higher id was found
}
}
return currentOptionOffset;
}
if(currentOptionId > wantedOptionId) {
return -1;
}
currentDelta = currentOptionId;
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
}
return -1;
}
public byte[] getValueOfOptionWithOffset(int offset) {
int valueSize = getValueSizeOfOptionWithOffset(options, offset);
int headerSize = headerSizeOfOptionWithOffset(options, offset);
offset += headerSize;
byte[] value = new byte[valueSize];
if(valueSize>0) {
Util.copyData(options, offset, value, 0, valueSize);
}
return value;
}
public int getValueSizeOfOptionWithOffset(int offset) {
return getValueSizeOfOptionWithOffset(options, offset);
}
public void removeOptionWithOffset(int offset) {
//1. get delta of this option
int delta = idOfOptionWithOffset(options, offset, 0); //this method with 0 as previous delta gives just the delta of this option
//2. get length of the block to remove
int optionSize = headerSizeOfOptionWithOffset(options, offset)
+ getValueSizeOfOptionWithOffset(options, offset);
//3. recalculate next option's new delta value
int offsetRightOption = offset + optionSize; //same as findOffsetOfNextOption(options, offset);
int deltaRightOption;
int deltaFieldSizeRightOption = 0;
int deltaRightOptionNew = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaFieldSizeDifferenceRightOption = 0;
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaRightOption = idOfOptionWithOffset(options, offsetRightOption, 0); //this method with 0 as previous delta gives just the delta of this option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = delta + deltaRightOption;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
deltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOptionNew - deltaFieldSizeRightOption;
}
//6. calculate new array size
int optionArraySizeNew = optionArraySize
- optionSize
+ deltaFieldSizeDifferenceRightOption;
//7. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//8. copy old option array to the start of the option to remove
if (offset>0)
Util.copyData(options, 0, optionsNew, 0, offset);
int offsetNew = offset;
offset += optionSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//9. write new delta for next option
//length stays constant, delta is erased
optionsNew[offsetNew] = (byte) (options[offset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[offsetNew] += 13 << 4;
optionsNew[offsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[offsetNew] += 14 << 4;
Util.set16(optionsNew, offsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[offsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
offsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
offset += 1+deltaFieldSizeRightOption;
//10. copy rest of the array
int restLength = optionArraySizeNew - offsetNew;
Util.copyData(options, offset, optionsNew, offsetNew, restLength);
}
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public void removeOptionWithId(int id, int matchNumber) {
int offset = getOffsetOfOptionWithId(id, matchNumber);
removeOptionWithOffset(offset);
}
public byte[] valueOfOptionWithId(int id, int no) {
int partNo = 0;
int offset = getOffsetOfOptionWithId(id, no);
if (offset>=0) {
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
return data;
}
return null;
}
public int findOffsetOfNextOption(int offset) {
return findOffsetOfNextOption(this.options, offset);
}
public int idOfOptionWithOffset(int offset, int currentDelta) {
return idOfOptionWithOffset(this.options, offset, currentDelta);
}
public void encodeTo(byte[] buffer, int offset) {
int iOffset = 0;
Util.copyData(header, 0, buffer, offset, 4);
iOffset+=4;
byte tokenLength = this.getTokenLength();
if (tokenLength > 0) {
Util.copyData(token,0, buffer, offset+iOffset, tokenLength);
iOffset += tokenLength;
}
if (optionArraySize>0) {
Util.copyData(options, 0, buffer, offset+iOffset, optionArraySize);
iOffset += optionArraySize;
}
if (this.payloadLength!=0) {
buffer[offset+iOffset] = (byte) 0xFF;
iOffset++;
Util.copyData(this.payload,0, buffer, offset+iOffset, this.payloadLength);
}
}
//
// Return:
// 0: OK
// -1: Protocol error
// -2: Currently unsupported feature
public byte decode(byte[] inBuffer, int offset, int len) {
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: ENTER DECODE"));
Logger.flush(Mote.INFO);
//##endif
int inOffset = offset;
int endLen = offset+len;
payloadLength = 0;
Util.copyData(inBuffer, offset, header, 0, 4);
inOffset += 4;
// Read token
byte tokenLength = getTokenLength();
if(tokenLength > 8) {
return -1;
}
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: token len"));
Logger.appendInt(tokenLength);
Logger.flush(Mote.INFO);
//##endif
if (tokenLength>0) {
token = new byte[tokenLength];
Util.copyData(inBuffer, inOffset, token, 0, tokenLength);
}
inOffset += tokenLength;
// Check if end of Message
if (inOffset >= endLen) // Zero length Message, zero options
return 0;
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: start reading options "));
Logger.flush(Mote.INFO);
//##endif
// Check if payload marker or options
int optionOffset = inOffset;
inOffset = jumpOverOptions(inBuffer, inOffset, endLen);
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: new offset"));
Logger.appendInt(inOffset);
Logger.appendString(csr.s2b("CoAPDecode :: endlen"));
Logger.appendInt(endLen);
Logger.flush(Mote.INFO);
//##endif
optionArraySize = inOffset - optionOffset; //may be 0 if no options are given
options = new byte[optionArraySize];
if(optionArraySize > 0) {
Util.copyData(inBuffer, optionOffset, options, 0, optionArraySize);
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: end reading options "));
Logger.flush(Mote.INFO);
//##endif
if (inOffset == endLen) { // Zero length Message
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: no payload "));
Logger.flush(Mote.INFO);
//##endif
return 0;
}
if (inBuffer[inOffset] == (byte) 0xFF) {
inOffset++;
if(inOffset == endLen) { //protocol error: there is no payload though the marker indicates
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
// Payload
payloadLength = endLen-inOffset;
payload = new byte[payloadLength];
Util.copyData(inBuffer, inOffset, payload, 0, payloadLength);
}
else {
inOffset++;
if(inOffset < endLen) { //protocol error: there is payload though there is no marker
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
}
return 0;
}
public final int getMessageLength() {
int len=4+getTokenLength();
if (this.payloadLength!=0)
len += 1+payloadLength;
len += optionArraySize;
return len;
}
public final Packet prepareResponseForSourcePacket(int inDstPort, byte[] inDstAddr, byte[] inSrcAddr, int srcPort) {
int dstport = inDstPort;
int lenp = getMessageLength();
Packet tempPacket = Mac.getPacket();
tempPacket.release();
Address.copyAddress(inDstAddr, 0, tempPacket.dstaddr, 0);
Address.copyAddress(inSrcAddr, 0, tempPacket.srcaddr, 0);
tempPacket.create(dstport, srcPort, lenp);
encodeTo(tempPacket.payloadBuf, tempPacket.payloadOff);
return tempPacket;
}
private static int jumpOverOptions(byte[] inBuffer, int offset, int len) {
int nextOptionOffset = offset;
while(nextOptionOffset < len && inBuffer[nextOptionOffset] != (byte) 0xFF) {
// checking for protocol violation -- one of the nibbles is F but it's not the payload marker
// check belongs only here since the first time parsing of a received message happens here
if( (inBuffer[offset] & 0x0F) == 0x0F || (inBuffer[offset] & 0xF0) == 0xF0 ) {
return -1;
}
nextOptionOffset = findOffsetOfNextOption(inBuffer, nextOptionOffset);
}
return nextOptionOffset;
}
private static int findOffsetOfNextOption(byte[] inBuffer, int offset) {
int headerSize = headerSizeOfOptionWithOffset(inBuffer, offset);
int valueSize = getValueSizeOfOptionWithOffset(inBuffer, offset);
int currentOptionSize = headerSize + valueSize;
return offset + currentOptionSize;
}
private static int headerSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
int size = 1;
size += optionExtendedDeltaFieldSize(inBuffer, offset);
size += optionExtendedLengthFieldSize(inBuffer, offset);
return size;
}
private static int optionExtendedDeltaFieldSize(byte[] inBuffer, int offset) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return 0;
if(optionDelta == 13)
return 1;
return 2; //optionDelta == 14
}
private static int optionExtendedLengthFieldSize(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return 0;
if(optionLength == 13)
return 1;
return 2; //optionLength == 14
}
private static int getValueSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return optionLength;
else {
offset += 1 + optionExtendedDeltaFieldSize(inBuffer, offset);
if(optionLength == 13) {
return inBuffer[offset] + 13;
}
return Util.get16(inBuffer, offset) + 269; //optionLength == 14
}
}
private static int idOfOptionWithOffset(byte[] inBuffer, int offset, int currentDelta) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return currentDelta + optionDelta;
else {
offset += 1;
if(optionDelta == 13) {
return currentDelta + inBuffer[offset] + 13;
}
return currentDelta + Util.get16(inBuffer, offset) + 269; //optionDelta == 14
}
}
private static int getExtendedOptionFieldSizeFor(int input) {
if(input<13)
return 0;
else if(input >= 13 && input < 269)
return 1;
return 2; //input >= 269
}
}
|
Java
|
/* Copyright (c) Robert Adams
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the copyright holder may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// #include "StdAfx.h"
#include "OLPreloadArchive.h"
#include "OgreFileSystem.h"
#include "LookingGlassOgre.h"
#include "RendererOgre.h"
namespace LG {
OLPreloadArchive::OLPreloadArchive( const Ogre::String& name, const Ogre::String& archType )
: Ogre::Archive(name, archType) {
LG::Log("OLPreloadArchive creation: n=%s, t=%s", name.c_str(), archType.c_str());
m_FSArchive = NULL;
return;
}
OLPreloadArchive::~OLPreloadArchive(void) {
unload();
}
/// Get the name of this archive
// const String& OLPreloadArchive::getName(void) const { return mName; }
/// Returns whether this archive is case sensitive in the way it matches files
bool OLPreloadArchive::isCaseSensitive(void) const {
return m_FSArchive->isCaseSensitive();
}
// Loads the archive.
void OLPreloadArchive::load() {
// this is really a wrapper for a filesystem archive
LG::Log("OLPreloadArchive::load(): mName=%s", mName.c_str());
m_defaultMeshFilename = LG::GetParameter("Renderer.Ogre.DefaultMeshFilename");
LG::Log("OLPreloadArchive::load(): DefaultMeshFile=%s", m_defaultMeshFilename.c_str());
m_defaultTextureFilename = LG::GetParameter("Renderer.Ogre.DefaultTextureFilename");
LG::Log("OLPreloadArchive::load(): DefaultTextureFile=%s", m_defaultTextureFilename.c_str());
m_FSArchive = OGRE_NEW Ogre::FileSystemArchive(mName, "XXOLFilesystem");
m_FSArchive->load();
}
// Unloads the archive.
void OLPreloadArchive::unload() {
Ogre::ArchiveManager::getSingleton().unload(m_FSArchive);
}
// The preloaded entities are in a filesystem without the grid name at the beginning.
// This routine strips the grid name of the beginning and looks for the file.
Ogre::DataStreamPtr OLPreloadArchive::open(const Ogre::String& filename, bool readonly) const {
LG::Log("OLPreloadArchive::open(%s)", filename.c_str());
Ogre::String entityName = ExtractEntityFromFilename(filename);
if (m_FSArchive->exists(entityName)) {
return m_FSArchive->open(entityName);
}
// if the file doesn't exist, we shouldn't have been asked for it
LG::Log("OLPreloadArchive::open(): the entity didn't exist!!!!. '%s'", entityName.c_str());
return Ogre::DataStreamPtr(new Ogre::MemoryDataStream(10));
}
Ogre::DataStreamPtr OLPreloadArchive::open(const Ogre::String& filename) const {
return this->open(filename, true);
}
// List all file names in the archive.
Ogre::StringVectorPtr OLPreloadArchive::list(bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::list()");
return m_FSArchive->list(recursive, dirs);
}
// List all files in the archive with accompanying information.
Ogre::FileInfoListPtr OLPreloadArchive::listFileInfo(bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::listFileInfo()");
return m_FSArchive->listFileInfo(recursive, dirs);
}
Ogre::// Find all file or directory names matching a given pattern
StringVectorPtr OLPreloadArchive::find(const Ogre::String& pattern, bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::find(%s)", pattern.c_str());
return m_FSArchive->find(pattern, recursive, dirs);
}
// Find out if the named file exists (note: fully qualified filename required) */
bool OLPreloadArchive::exists(const Ogre::String& filename) {
// Ogre::String entityName = ExtractEntityFromFilename(filename);
// bool answer = m_FSArchive->exists(ExtractEntityFromFilename(filename));
// LG::Log("OLPreloadArchive::exists(%s)(%s)(%s)", filename.c_str(),
// entityName.c_str(), answer ? "exists" : "does not exist");
// return answer;
return m_FSArchive->exists(ExtractEntityFromFilename(filename));
}
// Retrieve the modification time of a given file */
time_t OLPreloadArchive::getModifiedTime(const Ogre::String& filename) {
return m_FSArchive->getModifiedTime(ExtractEntityFromFilename(filename));
}
// Find all files or directories matching a given pattern in this
Ogre::FileInfoListPtr OLPreloadArchive::findFileInfo(const Ogre::String& pattern,
bool recursive, bool dirs) {
return m_FSArchive->findFileInfo(pattern, recursive, dirs);
}
const Ogre::String& OLPreloadArchiveFactory::getType(void) const {
static Ogre::String name = OLPreloadTypeName;
return name;
}
Ogre::Archive* OLPreloadArchiveFactory::createInstance( const Ogre::String& name ) {
LG::Log("OLPreloadArchiveFactory::createInstance(%s)", name.c_str());
return OGRE_NEW OLPreloadArchive(name, OLPreloadTypeName);
}
// The filename passed to us has the grid name at the beginning. Remove that and
// return the result. We presume it's everything up the slash.
Ogre::String OLPreloadArchive::ExtractEntityFromFilename(Ogre::String filename) const {
int pos = filename.find("/");
if (pos > 0) {
return filename.substr(pos + 1);
}
return Ogre::String("");
}
}
|
Java
|
import py
try:
from pypy.rpython.test.test_llinterp import interpret
except ImportError:
py.test.skip('Needs PyPy to be on the PYTHONPATH')
from rply import ParserGenerator, Token
from rply.errors import ParserGeneratorWarning
from .base import BaseTests
from .utils import FakeLexer, BoxInt, ParserState
class TestTranslation(BaseTests):
def run(self, func, args):
return interpret(func, args)
def test_basic(self):
pg = ParserGenerator(["NUMBER", "PLUS"])
@pg.production("main : expr")
def main(p):
return p[0]
@pg.production("expr : expr PLUS expr")
def expr_op(p):
return BoxInt(p[0].getint() + p[2].getint())
@pg.production("expr : NUMBER")
def expr_num(p):
return BoxInt(int(p[0].getstr()))
with self.assert_warns(ParserGeneratorWarning, "1 shift/reduce conflict"):
parser = pg.build()
def f(n):
return parser.parse(FakeLexer([
Token("NUMBER", str(n)),
Token("PLUS", "+"),
Token("NUMBER", str(n))
])).getint()
assert self.run(f, [12]) == 24
def test_state(self):
pg = ParserGenerator(["NUMBER", "PLUS"], precedence=[
("left", ["PLUS"]),
])
@pg.production("main : expression")
def main(state, p):
state.count += 1
return p[0]
@pg.production("expression : expression PLUS expression")
def expression_plus(state, p):
state.count += 1
return BoxInt(p[0].getint() + p[2].getint())
@pg.production("expression : NUMBER")
def expression_number(state, p):
state.count += 1
return BoxInt(int(p[0].getstr()))
parser = pg.build()
def f():
state = ParserState()
return parser.parse(FakeLexer([
Token("NUMBER", "10"),
Token("PLUS", "+"),
Token("NUMBER", "12"),
Token("PLUS", "+"),
Token("NUMBER", "-2"),
]), state=state).getint() + state.count
assert self.run(f, []) == 26
|
Java
|
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>SLS_PHP_SDK » \Aliyun_Log_Models_ListLogstoresRequest</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner"><div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">SLS_PHP_SDK</a><div class="nav-collapse"><ul class="nav">
<li class="dropdown">
<a href="#api" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b></a><ul class="dropdown-menu">
<li><a>Packages</a></li>
<li><a href="../packages/SLS_PHP_SDK.html"><i class="icon-folder-open"></i> SLS_PHP_SDK</a></li>
</ul>
</li>
<li class="dropdown" id="charts-menu">
<a href="#charts" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="../graph_class.html"><i class="icon-list-alt"></i> Class hierarchy diagram</a></li></ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#reports" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b></a><ul class="dropdown-menu">
<li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors
<span class="label label-info">290</span></a></li>
<li><a href="../markers.html"><i class="icon-map-marker"></i> Markers
<ul></ul></a></li>
<li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements
<span class="label label-info">0</span></a></li>
</ul>
</li>
</ul></div>
</div></div>
<div class="go_to_top"><a href="#___" style="color: inherit">Back to top <i class="icon-upload icon-white"></i></a></div>
</div>
<div id="___" class="container">
<noscript><div class="alert alert-warning">
Javascript is disabled; several features are only available
if Javascript is enabled.
</div></noscript>
<div class="row">
<div class="span4">
<div xmlns:php="http://php.net/xsl" class="btn-toolbar">
<div class="btn-group visibility" data-toggle="buttons-checkbox">
<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>
</div>
<div class="btn-group view pull-right" data-toggle="buttons-radio">
<button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button>
</div>
</div>
<ul xmlns:php="http://php.net/xsl" class="side-nav nav nav-list">
<li class="nav-header">
<i title="Methods" class="icon-custom icon-method"></i> Methods
<ul>
<li class="method public "><a href="#method___construct" title="__construct() :: Aliyun_Log_Models_ListLogstoresRequest constructor"><span class="description">Aliyun_Log_Models_ListLogstoresRequest constructor</span><pre>__construct()</pre></a></li>
<li class="method public inherited"><a href="#method___construct" title="__construct() :: Aliyun_Log_Models_Request constructor"><span class="description">Aliyun_Log_Models_Request constructor</span><pre>__construct()</pre></a></li>
<li class="method public inherited"><a href="#method_getProject" title="getProject() :: Get project name"><span class="description">Get project name</span><pre>getProject()</pre></a></li>
<li class="method public inherited"><a href="#method_setProject" title="setProject() :: Set project name"><span class="description">Set project name</span><pre>setProject()</pre></a></li>
</ul>
</li>
<li class="nav-header">
<i title="Properties" class="icon-custom icon-property"></i> Properties
<ul></ul>
</li>
<li class="nav-header private">» Private
<ul><li class="property private "><a href="#property_project" title="$project() :: "><span class="description">project name</span><pre>$project</pre></a></li></ul>
</li>
</ul>
</div>
<div class="span8">
<a xmlns:php="http://php.net/xsl" id="\Aliyun_Log_Models_ListLogstoresRequest"></a><ul xmlns:php="http://php.net/xsl" class="breadcrumb">
<li>
<a href="../index.html"><i title="Classes" class="icon-custom icon-class"></i></a><span class="divider">\</span>
</li>
<li class="active">
<span class="divider">\</span><a href="../classes/Aliyun_Log_Models_ListLogstoresRequest.html">Aliyun_Log_Models_ListLogstoresRequest</a>
</li>
</ul>
<div xmlns:php="http://php.net/xsl" class="element class">
<p class="short_description">The request used to list logstore from sls.</p>
<div class="details">
<div class="long_description"></div>
<table class="table table-bordered">
<tr>
<th>author</th>
<td><a href="">sls_dev</a></td>
</tr>
<tr>
<th>package</th>
<td><a href="../packages/SLS_PHP_SDK.html">SLS_PHP_SDK</a></td>
</tr>
<tr>
<th>inherited_from</th>
<td>\Aliyun_Log_Models_Request</td>
</tr>
</table>
<h3>
<i title="Methods" class="icon-custom icon-method"></i> Methods</h3>
<a id="method___construct"></a><div class="element clickable method public method___construct " data-toggle="collapse" data-target=".method___construct .collapse" title="public">
<h2>Aliyun_Log_Models_ListLogstoresRequest constructor</h2>
<pre>__construct(string $project<code> = null</code>) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>inherited_from</th>
<td>\Aliyun_Log_Models_Request::__construct()</td>
</tr></table>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<a id="method___construct"></a><div class="element clickable method public method___construct inherited" data-toggle="collapse" data-target=".method___construct .collapse" title="public">
<h2>Aliyun_Log_Models_Request constructor</h2>
<pre>__construct(string $project) </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<a id="method_getProject"></a><div class="element clickable method public method_getProject inherited" data-toggle="collapse" data-target=".method_getProject .collapse" title="public">
<h2>Get project name</h2>
<pre>getProject() : string</pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response">
<code>string</code>project name</div>
</div></div>
</div>
<a id="method_setProject"></a><div class="element clickable method public method_setProject inherited" data-toggle="collapse" data-target=".method_setProject .collapse" title="public">
<h2>Set project name</h2>
<pre>setProject(string $project) </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<h3>
<i title="Properties" class="icon-custom icon-property"></i> Properties</h3>
<a id="property_project"> </a><div class="element clickable property private property_project" data-toggle="collapse" data-target=".property_project .collapse" title="private">
<h2>project name</h2>
<pre>$project : string</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
</div>
</div>
</div>
</div>
<div class="row"><footer class="span12">
Template is built using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap 2</a> and icons provided by <a href="http://glyphicons.com/">Glyphicons</a>.<br>
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor v2.8.0-3-gd2074ac</a> and<br>
generated on 2015-01-26T01:53:31-08:00.<br></footer></div>
</div>
</body>
</html>
|
Java
|
/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String formatType1(String date)
{
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType2(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType3(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
}
|
Java
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
#define MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
#include <stdint.h>
#include <map>
#include <memory>
#include "base/containers/lru_cache.h"
#include "base/macros.h"
#include "base/sequence_checker.h"
#include "gpu/ipc/service/gpu_memory_buffer_factory.h"
#include "media/base/video_decoder.h"
#include "media/gpu/test/video_player/video_decoder_client.h"
#include "media/media_buildflags.h"
#include "media/video/video_decode_accelerator.h"
namespace media {
class VideoFrame;
namespace test {
class FrameRenderer;
// The test VDA video decoder translates between the media::VideoDecoder and the
// media::VideoDecodeAccelerator interfaces. This makes it possible to run
// VD-based tests against VDA's.
class TestVDAVideoDecoder : public media::VideoDecoder,
public VideoDecodeAccelerator::Client {
public:
// Constructor for the TestVDAVideoDecoder.
TestVDAVideoDecoder(bool use_vd_vda,
const gfx::ColorSpace& target_color_space,
FrameRenderer* const frame_renderer,
gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory);
TestVDAVideoDecoder(const TestVDAVideoDecoder&) = delete;
TestVDAVideoDecoder& operator=(const TestVDAVideoDecoder&) = delete;
~TestVDAVideoDecoder() override;
// media::VideoDecoder implementation
VideoDecoderType GetDecoderType() const override;
bool IsPlatformDecoder() const override;
void Initialize(const VideoDecoderConfig& config,
bool low_delay,
CdmContext* cdm_context,
InitCB init_cb,
const OutputCB& output_cb,
const WaitingCB& waiting_cb) override;
void Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) override;
void Reset(base::OnceClosure reset_cb) override;
bool NeedsBitstreamConversion() const override;
bool CanReadWithoutStalling() const override;
int GetMaxDecodeRequests() const override;
private:
// media::VideoDecodeAccelerator::Client implementation
void NotifyInitializationComplete(Status status) override;
void ProvidePictureBuffers(uint32_t requested_num_of_buffers,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
uint32_t texture_target) override;
void ProvidePictureBuffersWithVisibleRect(uint32_t requested_num_of_buffers,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
const gfx::Rect& visible_rect,
uint32_t texture_target) override;
void DismissPictureBuffer(int32_t picture_buffer_id) override;
void PictureReady(const Picture& picture) override;
void ReusePictureBufferTask(int32_t picture_buffer_id);
void NotifyEndOfBitstreamBuffer(int32_t bitstream_buffer_id) override;
void NotifyFlushDone() override;
void NotifyResetDone() override;
void NotifyError(VideoDecodeAccelerator::Error error) override;
// Helper thunk to avoid dereferencing WeakPtrs on the wrong thread.
static void ReusePictureBufferThunk(
absl::optional<base::WeakPtr<TestVDAVideoDecoder>> decoder_client,
scoped_refptr<base::SequencedTaskRunner> task_runner,
int32_t picture_buffer_id);
// Get the next bitstream buffer id to be used.
int32_t GetNextBitstreamBufferId();
// Get the next picture buffer id to be used.
int32_t GetNextPictureBufferId();
// Called when initialization is done. The callback is stored only when VDA
// allows deferred initialization.
InitCB init_cb_;
// Called when a buffer is decoded.
OutputCB output_cb_;
// Called when the decoder finished flushing.
DecodeCB flush_cb_;
// Called when the decoder finished resetting.
base::OnceClosure reset_cb_;
// Whether VdVideoDecodeAccelerator is used.
bool use_vd_vda_;
// Output color space, used as hint to decoder to avoid conversions.
const gfx::ColorSpace target_color_space_;
// Frame renderer used to manage GL context.
FrameRenderer* const frame_renderer_;
#if BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION)
// Owned by VideoDecoderClient.
gpu::GpuMemoryBufferFactory* const gpu_memory_buffer_factory_;
#endif // BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION)
// Map of video frames the decoder uses as output, keyed on picture buffer id.
std::map<int32_t, scoped_refptr<VideoFrame>> video_frames_;
// Map of video frame decoded callbacks, keyed on bitstream buffer id.
std::map<int32_t, DecodeCB> decode_cbs_;
// Records the time at which each bitstream buffer decode operation started.
base::LRUCache<int32_t, base::TimeDelta> decode_start_timestamps_;
int32_t next_bitstream_buffer_id_ = 0;
int32_t next_picture_buffer_id_ = 0;
std::unique_ptr<VideoDecodeAccelerator> decoder_;
scoped_refptr<base::SequencedTaskRunner> vda_wrapper_task_runner_;
SEQUENCE_CHECKER(vda_wrapper_sequence_checker_);
base::WeakPtr<TestVDAVideoDecoder> weak_this_;
base::WeakPtrFactory<TestVDAVideoDecoder> weak_this_factory_{this};
};
} // namespace test
} // namespace media
#endif // MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<?php
//Get Controller Action name
$action_ = Yii::app()->controller->action->id;
if($action_=='login')
{
//If Login Page, below html are worked
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/login_style_v1.css" />
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jQueryRotate.js"></script>
<!-- Custom jquery scripts -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/custom_jquery.js" type="text/javascript"></script>
<!-- MUST BE THE LAST SCRIPT IN <HEAD></HEAD></HEAD> png fix -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.pngFix.pack.js" type="text/javascript"></script>
<script type="text/javascript">
//javascript code for Rotate Logo in Login Page
$(document).ready(function()
{
$(document).pngFix( ); //call function , for png image fix in IE
//code for Rotating Logo Image
var angle = 0;
setInterval(function()
{
angle+=3;
$("#image1").rotate(angle);
},50);
} );
//End here, Code for Rotate Logo in Login Page
</script>
<body id="login-bg">
<div id="left-cont-login" >
<table width="860" border="0">
<tr>
<td class="left-cont-login-inner" width="416" align="center" >
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/login/rotate.png" alt="" id="image1" style="position:absolute; margin-top:32px; " />
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/login/l_hrms.png" width="250" height="106" alt="" id="image" align="center" />
<br />
<br />
<!---left content---->
<p>
eHORIZON HRMS delivers comprehensive HR capabilities, from workforce management to compensation and talent management. Extensive business process automation and rich self service capabilities enable HR teams to perform value added services while reducing operational costs. eHorizon HRMS comprise an array of features, and the powerful reporting and analysis capabilities that an organization needs to manage the workforce.</p><br />
<p>
The System transforms HR practices from administrative to strategic. It automates common administrative tasks, and leverages industry best practices to enable strategic management, along with efficient administration.
</p><br />
<!---left content---->
</td>
<td width="434" align="center" valign="top">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/login/stl-logo.png">
<div id="login-holder">
<div class="clear"></div>
<!-- START LOGIN BOX -->
<div id="loginbox">
<div id="login-inner">
<?php echo $content; ?>
</div>
<!-- end login-inner -->
<div class="clear"></div>
<!--<a href="" class="forgot-pwd">Forgot Password?</a>-->
</div>
<!-- END LOGIN BOX -->
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
<?php } else {
?>
<?php
$modelname = Yii::app()->controller->id;
$modelaction = Yii::app()->controller->action->id;
//echo "<h1>".$modelname."--------".$modelaction."</h1>";
//Calling Bootstrap CSS Framework
echo Yii::app()->bootstrap->init();//Yii::app()->language = 'zh-cn';
$this->widget('application.extensions.PNotify.PNotify',
array(
'message'=>'Some Information Showing Here After Login'
),
$_default_options=array(
'width'=>'700px',
'title_escape'=>false,
'text'=>false,
// 'text_escape'=>false,
)
);
//echo "<h1>".Yii::app()->user->id."</h1>";
// $condition="PID=".Yii::app()->user->id;
// $Theme_rst= Theme_Management::model()->find($condition);
// if($Theme_rst->THEME<>"") {
// $css_theme_rst = $Theme_rst->THEME;
// }
// else {$css_theme_rst="default"; }
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<!-- blueprint CSS framework -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" />
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/pure-css-custom-form-elements/style.css" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/page_style_v1.css" />
<link id="change_theme" rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/theme_changer/<?php echo trim(Yii::app()->session['css_theme_rst']) ?>.css" />
<!------Including page slide js----------->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/jquery.pageslide.css" />
<!-- <link rel="stylesheet" type="text/css" href="--><?php //echo Yii::app()->request->baseUrl; ?><!--/assets/custom_css/dropdown_menu.css" />-->
<!------Including page slidejs----------->
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<!------including jquery scroll js and css-------->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/Form_Wizard/formwizard.js" type="text/javascript">
<link href="<?php echo Yii::app()->request->baseUrl; ?>/assets/SrollBar/perfect-scrollbar.css" rel="stylesheet">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/SrollBar/jquery.mousewheel.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/SrollBar/perfect-scrollbar.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.wheelmenu.js"></script>
<!------including jquery scroll js and css-------->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.maskedinput.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/assets/Form_Wizard/formwizard.css" />
<!-- <link rel="stylesheet" type="text/css" href="--><?php //echo Yii::app()->request->baseUrl; ?><!--/css/add_new_menu_css/default.css"/>-->
<!-- <link rel="stylesheet" type="text/css" href="--><?php //echo Yii::app()->request->baseUrl; ?><!--/css/add_new_menu_css/elusive-webfont.css"/>-->
<!-- <link rel="stylesheet" type="text/css" href="--><?php //echo Yii::app()->request->baseUrl; ?><!--/css/add_new_menu_css/style.css"/> -->
<script type="text/javascript">
$(document).ready(function(){
$('#panel2').slidePanel({
triggerName: '#trigger2',
triggerTopPos: '20px',
panelTopPos: '10px'
});
$("#css-D371A7").click(function() {
$("#change_theme").attr({href : "<?php echo Yii::app()->request->baseUrl; ?>/css/theme_changer/D371A7.css"});
});
$("#css-blue").click(function() {
$("#change_theme").attr({href : "<?php echo Yii::app()->request->baseUrl; ?>/css/theme_changer/blue.css"});
});
$("#css-green").click(function() {
$("#change_theme").attr({href : "<?php echo Yii::app()->request->baseUrl; ?>/css/theme_changer/green.css"});
});
//popover for user account
//$("[rel='popover']").popover({
//placement : 'bottom', // top, bottom, left or right
//title : 'My Settings <a class="close" href="#");">×</a>',
//html: 'true',
//content : '<div class="msg" style="width:auto;"><table id="popovertable" style="margin-bottom:.1em !important ;"><tr><td>Change Password</td></tr><tr><td><a href="<?php echo Yii::app()->request->baseUrl; ?>/index.php/site/logout">Logout</a></td></tr><table></div>'
//});
// $(document).click(function (e) {
// if ($(e.target).is('.close')) {
// $("[rel='popover']").popover('hide');
// }
// });//
// Clickable Dropdown
//popover end
//Add and Manage Icons Top
$("#patternDiv").append("<div style='float:right; width:200px; height:25px; text-align:right'><a href='<?php echo Yii::app()->request->baseUrl."/index.php/".$modelname?>/create' data-toggle='tooltip' title='Create New' class='btn btn-success btn-mini' style='margin-right:5px;'><i class='icon-white icon-plus-sign'></i>Create</a><a href='<?php echo Yii::app()->request->baseUrl."/index.php/".$modelname?>/admin' data-toggle='tooltip' title='Manage' class='btn btn-success btn-mini'><i class='icon-white icon-cog'></i>Manage<a></div>");
//tooltip code
$("input[type=text]").dblclick(function()
{
var valueoftooltip =$(this).val();
if(valueoftooltip!="")
{
$("#"+$(this).attr("id")).after("<div class=tooltip-style id=tooltip-"+$(this).attr("id")+" style=display:block;>"+$(this).val()+"<div id=tooltip-pointer></div></div>");
$("#tooltip-"+$(this).attr("id")).animate({opacity: 1.0}, 3000).fadeOut("slow");
}
});
//tooltip end
//start Add new Button [ OLD STYLE BUT GOOD ANIMATION]
// $(".wheel-button").wheelmenu({
// trigger: "hover",
// animation: "fly",
// animationSpeed: "fast"
// });
//end Add new Button [ OLD STYLE BUT GOOD ANIMATION]
//code for slide show -- orgbanner
$("#slideshow_org_banner > div:gt(0)").hide();
setInterval(function() {
$('#slideshow_org_banner > div:first')
.fadeIn(1000)
.next()
.fadeOut(1000)
.end()
.appendTo('#slideshow_org_banner');
}, 3000);
//end slide show code -- orgbanner
//code for fixed header after scroll down--- start
$(window).bind("scroll",function(e){
if($(document).scrollTop() > 120) //
{
//alert("scroll downe...");
//$("#Help_Box1").show();
//$("#top_menu_bar").show(1000);
$("#top_menu_bar").addClass("somecloass");
$("#bottom_menu_bar").addClass("somecloass_bottom");
//Set content B to header
} else {
$("#top_menu_bar").removeClass("somecloass");
$("#bottom_menu_bar").removeClass("somecloass_bottom");
//alert("Normal Position ");
//$("#Help_Box1").hide();
//$("#top_menu_bar").css({ position: "none",z-index: ""; })
//Set content A to header
}
});
//end
$("#example_bottom").click(function(){
//alert("clicked");
if ($('#u_menu_content').css('display') == 'none') {
$("#u_menu_content").fadeIn("1000");
}
else {
$("#u_menu_content").fadeOut("1000");
}
});
$("#cross_myaccount").click(function(){
$("#u_menu_content").fadeOut("1000");
});
$("#theme_selector").click(function(){
//alert("clicked");
if ($('#u_theme_content').css('display') == 'none') {
$("#u_theme_content").fadeIn("1000");
}
else {
$("#u_theme_content").fadeOut("1000");
}
});
$("#cross_theme").click(function(){
$("#u_theme_content").fadeOut("1000");
});
//$("#example_bottom").popover({placement:'bottom',container:'#page-bgtop'});
});
///add some animation on scroll
// function scroll_to(div){
// $('#Help_Box1').animate({
// scrollTop: $(div).offset().top
// },1000);
// }
// - See more at: http://www.w3resource.com/twitter-bootstrap/popover-tutorial.php#sthash.IhP0YULz.dpuf
$(function() {
$("#red").treeview({
//collapsed: true,
animated: "medium",
control:"#treecontrol",
persist: "location"
});
})
</script>
<!---Write Some Inline CSS To Overide Bootstrap CSS Style--->
<style>
.table { width: auto; float:left}
</style>
<body viewsource="no">
<!--<a href="#" id="trigger2" class="trigger right"><img src="<?php echo Yii::app()->request->baseUrl; ?>/css/images/theme-icon.png" width="25" height="25" style="padding: 2px;"></a>-->
<!-- <div id="panel2" class="panel right">
<h4>Choose Your Theme</h4>
<span><a id="css-red" href="#red"><div id="box_red"></div></a></span>
<span><a id="css-green" href="#green"><div id="box_green"></div></a></span>
<span><a id="css-blue" href="#blue"><div id="box_blue"></div></a></span>
<span style="margin-left:5px;"><a href="#" class="btn btn-info btn-mini"><i class="icon-white icon-thumbs-up"></i> Activate</a></span>
</div>-->
<div id="top_menu_bar" style="display: none">
<?php require_once("menus/top_menu_bar.php"); ?>
</div>
<div id="menu-wrapper">
<!--- logo ---->
<img src="<?php echo Yii::app()->request->baseUrl; ?>/css/img/logo.png" width="115" height="100" style="float:left; padding: 5px;">
<!--ORGANIZATION Banner --->
<div id="org_name_position" style="">
<div id="slideshow_org_banner">
<!-- <div>-->
<!-- <img src="--><?php //echo Yii::app()->request->baseUrl; ?><!--/images/organization_banner/org1/banner1.jpg" alt="" class="active" />-->
<!-- </div>-->
<!-- <div>-->
<!-- <img src="--><?php //echo Yii::app()->request->baseUrl; ?><!--/images/organization_banner/org1/banner2.jpg" alt="" />-->
<!-- </div>-->
<!-- <div>-->
<!-- <img src="--><?php //echo Yii::app()->request->baseUrl; ?><!--/images/organization_banner/org1/banner3.jpg" alt="" />-->
<!-- </div>-->
<!-- <div>-->
<!-- Pretty cool eh?-->
<!-- </div>-->
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="468" height="75">
<param name="movie" value="<?php echo Yii::app()->request->baseUrl; ?>/images/flashvortex.swf" />
<param name="quality" value="best" />
<param name="menu" value="true" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="<?php echo Yii::app()->request->baseUrl; ?>/images/flashvortex.swf" quality="best" menu="true" width="468" height="75" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="sameDomain" />
</object>
</div>
</div>
<!---START TOP RIGHT USER IMAGE-->
<div id="menu">
<div id="example_bottom" style="background-image:url(<?php echo Yii::app()->request->baseUrl; ?>/images/prof_image1.jpg)">
</div>
<div id="u_menu_content">
<div class="arrow-up"></div>
<table id="inside_table_dmenu">
<tr>
<td class="title_td">My Account</td>
<td class="title_td" style="text-align: right"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/cross_orange.png" width="16" style="cursor: pointer; padding-right: 5px;" id="cross_myaccount"> </td>
</tr>
<tr class="d_menu_sub_tr">
<td class="dmenu_sub_td">Change Password</td><td style="text-align: right" class="dmenu_sub_td"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/lock.png" style="padding-right: 5px;"> </td>
</tr>
<tr class="d_menu_sub_tr">
<td class="dmenu_sub_td"><a id="text_color" href="<?php echo Yii::app()->request->baseUrl; ?>/index.php?site/logout">Logout</a> </td><td style="text-align: right" class="dmenu_sub_td"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/logout.png" style="padding-right: 5px;"> </td>
</tr>
</table>
</div>
</div>
<!-- END USER IMAGE-->
<!----start notification icons---->
<div id="icons_div_on_top" style="margin-top: 13px !important; ">
<div style="width: auto; height: auto; float: left; margin-top: 3px ; margin-right: 4px";>
<img id="theme_selector" src="<?php echo Yii::app()->request->baseUrl; ?>/css/images/theme-icon.png" width="25" height="25" align="right" title="Change Theme" style="cursor: pointer;">
</div>
<div id="u_theme_content">
<div class="arrow-up"></div>
<table id="inside_table_dmenu">
<tr>
<td class="title_td">Choose Any Theme</td>
<td class="title_td" style="text-align: right"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/cross_orange.png" width="16" style="cursor: pointer; padding-right: 5px;" id="cross_theme"> </td>
</tr>
<tr class="d_menu_sub_tr">
<td colspan="2" class="dmenu_sub_td">
<span><a id="css-D371A7" href="#D371A7"><div id="box_D371A7"></div></a></span>
<span><a id="css-green" href="#green"><div id="box_green"></div></a></span>
<span><a id="css-blue" href="#blue"><div id="box_blue"></div></a></span>
<span style="margin-right:5px; float: right;"><a href="#" class="btn btn-info btn-mini"><i class="icon-white icon-thumbs-up"></i> Activate</a></span>
</td>
<!--<td style="text-align: right" class="dmenu_sub_td"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/lock.png" style="padding-right: 5px;"> </td>-->
</tr>
<!-- <tr class="d_menu_sub_tr">
<td class="dmenu_sub_td"><a href="<?php echo Yii::app()->request->baseUrl; ?>/index.php?site/logout">Logout</a> </td><td style="text-align: right" class="dmenu_sub_td"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/logout.png" style="padding-right: 5px;"> </td>
</tr>-->
</table>
</div>
<div style="width: auto; height: auto; float: left; margin-top: 3px ; margin-right: 10px";>
<img class="bell" src="<?php echo Yii::app()->request->baseUrl; ?>/images/bell.png" width="25" height="25" align="right" style="cursor: pointer;">
<div style=" position: absolute; margin-left: 15px;">
<span style="font-size: 10px; color: white; padding: 2px; background-color: red; border-radius: 100%; cursor: pointer; font-weight: bold;">23</span>
</div>
</div>
<div style="width: auto; height: auto; float: left; margin-top: 0px; margin-right: 5px";>
<div style="width: auto; height: auto; float: left; margin-top: 3px";>
<img class="vertical" src="<?php echo Yii::app()->request->baseUrl; ?>/images/calendar.png" width="25" height="25" align="right" style="cursor: pointer">
<div style=" position: absolute;margin-left: 18px;">
<span style="font-size: 10px; color: white; padding: 2px; background-color: red; border-radius: 100%; cursor: pointer; font-weight: bold;">41</span>
</div>
</div>
</div>
<div style="width: auto; height: auto; float: left; margin-top: 0px; margin-right: 10px";>
<div style="width: auto; height: auto; float: left; margin-top: 0px";>
<!-- <img rel='popover' src="--><?php //echo Yii::app()->request->baseUrl; ?><!--/images/user_small.png" width="20" height="20" align="right" style="cursor: pointer">-->
</div>
</div>
</div>
<!----end notification------->
</div>
<div id="bottom_menu_bar">
<?php require_once("menus/bottom_menu_bar.php") ?>
</div>
<!-------Start Header--------->
<div id="header-wrapper">
<div id="header"></div>
</div>
<!----End Header----->
<div id="wrapper">
<div id="page">
<?php require_once("help_box/help_box_with_menu.php"); ?>
<div id="page-bgtop">
<div id="page-bgbtm">
<div id="contentnew">
<?php echo $content; ?>
<div style="clear: both;"> </div>
</div>
<div id="sidebar2" style="visibility: hidden; position: absolute" >
<!---Start Here Tree menu [include js and css]-->
<link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl; ?>/tree/jquery.treeview.css">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/tree/jquery.cookie.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/tree/jquery.treeview.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/tree/demo.js"></script>
<!---End Here Tree menu [include js and css] -->
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.pageslide.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.slidePanel.js"></script>
<div id="modal">
<img id="Navigate_Right_Icon" src="<?php echo Yii::app()->request->baseUrl; ?>/images/cross.png" onclick="js:$.pageslide.close()" style="position:absolute; cursor: pointer;left: -10px; top: -2%;" />
<!----Including And Displaying Tree menu----->
<!--<div id="treecontrol"><a href="?#">Collapse All</a> | <a href="?#">Expand All</a></div>-->
<?php include_once("menus/TreeMenu.php"); ?>
<!----End here Including And Displaying Tree menu----->
</div>
</div>
<!-------Script For Menu Slide----------->
<script>
/* Slide to the left, and make it model (you'll have to call $.pageslide.close() to close) */
$(".second").pageslide({ direction: "left", modal: false });
</script>
<!-------End Here Script For Menu Slide----------->
</div>
<div style="clear: both;"> </div>
</div>
</div>
</div>
</div>
<!-- BEGIN FOOTER -->
<div id="footer">
<p>Copyright © <?php echo date('Y')?> <a href="http://www.loksolutions.biz/" target="_blank">LOK Solutions</a> Private Limited. All Rights Reserved.</p>
</div>
<!-- END FOOTER -->
</body>
</html>
<?php } ?>
|
Java
|
extract:
${tooldir}/ecore2bgf BIBTEXML.ecore grammar.bgf
include ../../Makefile.grammar
|
Java
|
{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FunctionalDependencies
, UndecidableInstances
#-}
-- For ghc 6.6 compatibility
-- {-# OPTIONS -fglasgow-exts -fallow-undecidable-instances #-}
----------------------------------------------------------------------
-- |
-- Module : Data.FunArr
-- Copyright : (c) Conal Elliott 2007-2013
-- License : BSD3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
-- Portability : portable
--
-- Conversion between arrow values and wrapped functions.
----------------------------------------------------------------------
module Data.FunArr
(
FunArr(..) -- , wapl
) where
-- import Control.Monad.Identity
import Control.Compose
infixr 0 $$ -- FunArr application
-- | Convert between an arrow value and a \"wrapped function\". The \"arrow\"
-- doesn't really have to be an arrow. I'd appreciate ideas for names &
-- uses.
class FunArr ar w | ar->w , w->ar where
-- | Convert a @w@-wrapped function to an arrow value
toArr :: w (a->b) -> (a `ar` b)
-- | Apply an arrow to a @w@-wrapped value
($$) :: (a `ar` b) -> w a -> w b
-- -- | Apply a wrapped function to a wrapped value
-- wapl :: FunArr ar w => w (a->b) -> w a -> w b
-- wapl f a = toArr f $$ a
-- The type of wapl matches <*> from Control.Applicative. What about
-- "pure" from the Applicative class, with type a -> w a?
-- Function/Id instance
instance FunArr (->) Id where
toArr (Id f) = f
f $$ Id a = Id (f a)
-- -- Oops! This instance can't work with the mutual functional
-- dependencies. Instead, instantiate it per @h@.
--
-- instance FunArr (FunA h) h where
-- toArr = error "toArr: undefined for FunArr" -- Add FunArrable class & delegate
-- FunA f $$ ha = f ha
-- The following instance violates the "coverage condition" and so
-- requires -fallow-undecidable-instances.
instance (FunArr ar w, FunArr ar' w')
=> FunArr (ar ::*:: ar') (w :*: w') where
toArr (Prod (f,f')) = Prodd (toArr f, toArr f')
Prodd (f,f') $$ Prod (w,w') = Prod (f $$ w, f' $$ w')
|
Java
|
# -*- coding: utf-8 -*-
#
# zambiaureport documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'zambiaureport'
copyright = u'2014, Andre Lesa'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'zambiaureportdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'zambiaureport.tex', u'zambiaureport Documentation',
u'Andre Lesa', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'zambiaureport', u'zambiaureport Documentation',
[u'Andre Lesa'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'zambiaureport', u'zambiaureport Documentation',
u'Andre Lesa', 'zambiaureport',
'Zambia U-Report reference implementation.','Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
|
Java
|
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2619.SirLancebot2016.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc2619.SirLancebot2016.subsystems.*;
/**
*
*/
public class CrossRockWallCG extends CommandGroup {
double distanceFromStart = 4.2;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
public CrossRockWallCG() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
addSequential(new DriveXfeet(distanceFromStart));
addSequential(new DriveUntilFlat(1));
}
}
|
Java
|
#include<iostream>
using namespace std;
int n,k;
const int maxn=100010;
bool b[2*maxn];
struct
{
int num,cn;
}queue[2*maxn];
int head,tail;
void bfs()
{
b[n]=1;
queue[0].num=n;
queue[0].cn=1;
while(head<=tail)
{
if(queue[head].num==k)
{
printf("%d\n",queue[head].cn);
return;
}
else if(queue[head].num>k&&!b[queue[head].num-1])
{
b[queue[head].num-1]=1;
queue[++tail].num=queue[head].num-1;
queue[tail].cn=queue[head].cn+1;
}
else
{
if(queue[head].num>0&&!b[queue[head].num-1])
{
b[queue[head].num-1]=1;
queue[++tail].num=queue[head].num-1;
queue[tail].cn=queue[head].cn+1;
}
if(!b[queue[head].num*2])
{
b[queue[head].num*2]=1;
queue[++tail].num=queue[head].num*2;
queue[tail].cn=queue[head].cn+1;
}
if(!b[queue[head].num+1])
{
b[queue[head].num+1]=1;
queue[++tail].num=queue[head].num+1;
queue[tail].cn=queue[head].cn+1;
}
}
++head;
}
}
int main()
{
scanf("%d%d",&n,&k);
if(n==k)
{
printf("1\n");
return 0;
}
memset(b,0,sizeof(b));
head=tail=0;
bfs();
return 0;
}
|
Java
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "contact".
*
* @property integer $id
* @property string $type
* @property string $name
* @property string $lastname
* @property string $email
* @property string $cellphone
* @property string $message
* @property string $identity
* @property string $medium
*/
class Contact extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'contact';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['type', 'name', 'lastname', 'email', 'cellphone', 'message'], 'required'],
[['type', 'message'], 'string'],
[['name', 'lastname', 'email'], 'string', 'max' => 150],
[['cellphone', 'identity'], 'string', 'max' => 10],
[['medium'], 'string', 'max' => 50]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'type' => 'Type',
'name' => 'Name',
'lastname' => 'Lastname',
'email' => 'Email',
'cellphone' => 'Cellphone',
'message' => 'Message',
'identity' => 'Identity',
'medium' => 'Medium',
];
}
}
|
Java
|
#include <iostream>
#include <type_traits>
#include <vector>
#include <cassert>
#include <agency/execution/executor/sequenced_executor.hpp>
#include <agency/execution/executor/executor_traits.hpp>
int main()
{
using namespace agency;
static_assert(is_bulk_synchronous_executor<sequenced_executor>::value,
"sequenced_executor should be a bulk synchronous executor");
static_assert(is_bulk_executor<sequenced_executor>::value,
"sequenced_executor should be a bulk executor");
static_assert(detail::is_detected_exact<sequenced_execution_tag, executor_execution_category_t, sequenced_executor>::value,
"sequenced_executor should have sequenced_execution_tag execution_category");
static_assert(detail::is_detected_exact<size_t, executor_shape_t, sequenced_executor>::value,
"sequenced_executor should have size_t shape_type");
static_assert(detail::is_detected_exact<size_t, executor_index_t, sequenced_executor>::value,
"sequenced_executor should have size_t index_type");
static_assert(detail::is_detected_exact<std::future<int>, executor_future_t, sequenced_executor, int>::value,
"sequenced_executor should have std::future furture");
static_assert(executor_execution_depth<sequenced_executor>::value == 1,
"sequenced_executor should have execution_depth == 1");
sequenced_executor exec;
size_t shape = 10;
auto result = exec.bulk_sync_execute(
[](size_t idx, std::vector<int>& results, std::vector<int>& shared_arg)
{
results[idx] = shared_arg[idx];
},
shape,
[=]{ return std::vector<int>(shape); }, // results
[=]{ return std::vector<int>(shape, 13); } // shared_arg
);
assert(std::vector<int>(10, 13) == result);
std::cout << "OK" << std::endl;
return 0;
}
|
Java
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkBitArray.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkBitArray - dynamic, self-adjusting array of bits
// .SECTION Description
// vtkBitArray is an array of bits (0/1 data value). The array is packed
// so that each byte stores eight bits. vtkBitArray provides methods
// for insertion and retrieval of bits, and will automatically resize
// itself to hold new data.
#ifndef vtkBitArray_h
#define vtkBitArray_h
#include "vtkCommonCoreModule.h" // For export macro
#include "vtkDataArray.h"
class vtkBitArrayLookup;
class VTKCOMMONCORE_EXPORT vtkBitArray : public vtkDataArray
{
public:
static vtkBitArray *New();
vtkTypeMacro(vtkBitArray,vtkDataArray);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Allocate memory for this array. Delete old storage only if necessary.
// Note that ext is no longer used.
int Allocate(vtkIdType sz, vtkIdType ext=1000);
// Description:
// Release storage and reset array to initial state.
void Initialize();
// satisfy vtkDataArray API
int GetDataType() {return VTK_BIT;};
int GetDataTypeSize() { return 0; }
// Description:
// Set the number of n-tuples in the array.
void SetNumberOfTuples(vtkIdType number);
// Description:
// Set the tuple at the ith location using the jth tuple in the source array.
// This method assumes that the two arrays have the same type
// and structure. Note that range checking and memory allocation is not
// performed; use in conjunction with SetNumberOfTuples() to allocate space.
virtual void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source);
// Description:
// Insert the jth tuple in the source array, at ith location in this array.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source);
// Description:
// Copy the tuples indexed in srcIds from the source array to the tuple
// locations indexed by dstIds in this array.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds,
vtkAbstractArray *source);
// Description:
// Copy n consecutive tuples starting at srcStart from the source array to
// this array, starting at the dstStart location.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart,
vtkAbstractArray* source);
// Description:
// Insert the jth tuple in the source array, at the end in this array.
// Note that memory allocation is performed as necessary to hold the data.
// Returns the location at which the data was inserted.
virtual vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray* source);
// Description:
// Get a pointer to a tuple at the ith location. This is a dangerous method
// (it is not thread safe since a pointer is returned).
double *GetTuple(vtkIdType i);
// Description:
// Copy the tuple value into a user-provided array.
void GetTuple(vtkIdType i, double * tuple);
// Description:
// Set the tuple value at the ith location in the array.
void SetTuple(vtkIdType i, const float * tuple);
void SetTuple(vtkIdType i, const double * tuple);
// Description:
// Insert (memory allocation performed) the tuple into the ith location
// in the array.
void InsertTuple(vtkIdType i, const float * tuple);
void InsertTuple(vtkIdType i, const double * tuple);
// Description:
// Insert (memory allocation performed) the tuple onto the end of the array.
vtkIdType InsertNextTuple(const float * tuple);
vtkIdType InsertNextTuple(const double * tuple);
// Description:
// These methods remove tuples from the data array. They shift data and
// resize array, so the data array is still valid after this operation. Note,
// this operation is fairly slow.
virtual void RemoveTuple(vtkIdType id);
virtual void RemoveFirstTuple();
virtual void RemoveLastTuple();
// Description:
// Set the data component at the ith tuple and jth component location.
// Note that i is less then NumberOfTuples and j is less then
// NumberOfComponents. Make sure enough memory has been allocated (use
// SetNumberOfTuples() and SetNumberOfComponents()).
void SetComponent(vtkIdType i, int j, double c);
// Description:
// Free any unneeded memory.
void Squeeze();
// Description:
// Resize the array while conserving the data.
virtual int Resize(vtkIdType numTuples);
// Description:
// Get the data at a particular index.
int GetValue(vtkIdType id);
// Description:
// Fast method based setting of values without memory checks. First
// use SetNumberOfValues then use SetValue to actually set them.
// Specify the number of values for this object to hold. Does an
// allocation as well as setting the MaxId ivar. Used in conjunction with
// SetValue() method for fast insertion.
void SetNumberOfValues(vtkIdType number);
// Description:
// Set the data at a particular index. Does not do range checking. Make sure
// you use the method SetNumberOfValues() before inserting data.
void SetValue(vtkIdType id, int value);
// Description:
// Inserts values and checks to make sure there is enough memory
void InsertValue(vtkIdType id, int i);
// Description:
// Set a value in the array from a variant.
void SetVariantValue(vtkIdType idx, vtkVariant value);
// Description:
// Inserts values from a variant and checks to ensure there is enough memory
void InsertVariantValue(vtkIdType idx, vtkVariant value);
vtkIdType InsertNextValue(int i);
// Description:
// Insert the data component at ith tuple and jth component location.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertComponent(vtkIdType i, int j, double c);
// Description:
// Direct manipulation of the underlying data.
unsigned char *GetPointer(vtkIdType id) {return this->Array + id/8;}
// Description:
// Get the address of a particular data index. Make sure data is allocated
// for the number of items requested. Set MaxId according to the number of
// data values requested.
unsigned char *WritePointer(vtkIdType id, vtkIdType number);
void* WriteVoidPointer(vtkIdType id, vtkIdType number)
{ return this->WritePointer(id, number); }
void *GetVoidPointer(vtkIdType id)
{
return static_cast<void *>(this->GetPointer(id));
}
// Description:
// Deep copy of another bit array.
void DeepCopy(vtkDataArray *da);
void DeepCopy(vtkAbstractArray* aa)
{ this->Superclass::DeepCopy(aa); }
// Description:
// This method lets the user specify data to be held by the array. The
// array argument is a pointer to the data. size is the size of
// the array supplied by the user. Set save to 1 to keep the class
// from deleting the array when it cleans up or reallocates memory.
// The class uses the actual array provided; it does not copy the data
// from the supplied array. If save 0, the array must have been allocated
// with new[] not malloc.
#ifndef __VTK_WRAP__
void SetArray(unsigned char* array, vtkIdType size, int save);
#endif
void SetVoidArray(void *array, vtkIdType size, int save)
{
this->SetArray(static_cast<unsigned char *>(array), size, save);
}
void SetVoidArray(void *array, vtkIdType size, int save,
int vtkNotUsed(deleteMethod))
{
this->SetArray(static_cast<unsigned char *>(array), size, save);
}
// Description:
// Returns a new vtkBitArrayIterator instance.
VTK_NEWINSTANCE vtkArrayIterator* NewIterator();
// Description:
// Return the indices where a specific value appears.
virtual vtkIdType LookupValue(vtkVariant value);
virtual void LookupValue(vtkVariant value, vtkIdList* ids);
vtkIdType LookupValue(int value);
void LookupValue(int value, vtkIdList* ids);
// Description:
// Tell the array explicitly that the data has changed.
// This is only necessary to call when you modify the array contents
// without using the array's API (i.e. you retrieve a pointer to the
// data and modify the array contents). You need to call this so that
// the fast lookup will know to rebuild itself. Otherwise, the lookup
// functions will give incorrect results.
virtual void DataChanged();
// Description:
// Delete the associated fast lookup data structure on this array,
// if it exists. The lookup will be rebuilt on the next call to a lookup
// function.
virtual void ClearLookup();
protected:
vtkBitArray();
~vtkBitArray();
unsigned char *Array; // pointer to data
unsigned char *ResizeAndExtend(vtkIdType sz);
// function to resize data
int TupleSize; //used for data conversion
double *Tuple;
int SaveUserArray;
private:
// hide superclass' DeepCopy() from the user and the compiler
void DeepCopy(vtkDataArray &da) {this->vtkDataArray::DeepCopy(&da);}
private:
vtkBitArray(const vtkBitArray&) VTK_DELETE_FUNCTION;
void operator=(const vtkBitArray&) VTK_DELETE_FUNCTION;
vtkBitArrayLookup* Lookup;
void UpdateLookup();
};
inline void vtkBitArray::SetNumberOfValues(vtkIdType number)
{
this->Allocate(number);
this->MaxId = number - 1;
this->DataChanged();
}
inline void vtkBitArray::SetValue(vtkIdType id, int value)
{
if (value)
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] | (0x80 >> id%8));
}
else
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] & (~(0x80 >> id%8)));
}
this->DataChanged();
}
inline void vtkBitArray::InsertValue(vtkIdType id, int i)
{
if ( id >= this->Size )
{
if (!this->ResizeAndExtend(id+1))
{
return;
}
}
if (i)
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] | (0x80 >> id%8));
}
else
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] & (~(0x80 >> id%8)));
}
if ( id > this->MaxId )
{
this->MaxId = id;
}
this->DataChanged();
}
inline void vtkBitArray::SetVariantValue(vtkIdType id, vtkVariant value)
{
this->SetValue(id, value.ToInt());
}
inline void vtkBitArray::InsertVariantValue(vtkIdType id, vtkVariant value)
{
this->InsertValue(id, value.ToInt());
}
inline vtkIdType vtkBitArray::InsertNextValue(int i)
{
this->InsertValue (++this->MaxId,i);
this->DataChanged();
return this->MaxId;
}
inline void vtkBitArray::Squeeze() {this->ResizeAndExtend (this->MaxId+1);}
#endif
|
Java
|
/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__
#define __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__
#include <iostream>
#include "mem/gems_common/Map.hh"
#include "mem/protocol/AccessType.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/system/MachineID.hh"
class PersistentTableEntry
{
public:
void print(std::ostream& out) const {}
NetDest m_starving;
NetDest m_marked;
NetDest m_request_to_write;
};
class PersistentTable
{
public:
// Constructors
PersistentTable();
// Destructor
~PersistentTable();
// Public Methods
void persistentRequestLock(const Address& address, MachineID locker,
AccessType type);
void persistentRequestUnlock(const Address& address, MachineID unlocker);
bool okToIssueStarving(const Address& address, MachineID machID) const;
MachineID findSmallest(const Address& address) const;
AccessType typeOfSmallest(const Address& address) const;
void markEntries(const Address& address);
bool isLocked(const Address& addr) const;
int countStarvingForAddress(const Address& addr) const;
int countReadStarvingForAddress(const Address& addr) const;
static void printConfig(std::ostream& out) {}
void print(std::ostream& out) const;
private:
// Private copy constructor and assignment operator
PersistentTable(const PersistentTable& obj);
PersistentTable& operator=(const PersistentTable& obj);
// Data Members (m_prefix)
Map<Address, PersistentTableEntry>* m_map_ptr;
};
inline std::ostream&
operator<<(std::ostream& out, const PersistentTable& obj)
{
obj.print(out);
out << std::flush;
return out;
}
inline std::ostream&
operator<<(std::ostream& out, const PersistentTableEntry& obj)
{
obj.print(out);
out << std::flush;
return out;
}
#endif // __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__
|
Java
|
/*******************************************************************************
* Copyright (c) 2009-2012, University of Manchester
*
* Licensed under the New BSD License.
* Please see LICENSE file that is distributed with the source code
******************************************************************************/
package uk.ac.manchester.cs.owl.semspreadsheets.model;
/**
* Author: Matthew Horridge<br>
* The University of Manchester<br>
* Information Management Group<br>
* Date: 08-Nov-2009
*/
public interface NamedRange {
String getName();
Range getRange();
}
|
Java
|
/*L
* Copyright SAIC, SAIC-Frederick.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caadapter/LICENSE.txt for details.
*/
package gov.nih.nci.caadapter.sdtm.util;
/**
* This class represents a entity
*
* @author OWNER: Harsha Jayanna
* @author LAST UPDATE $Author: phadkes $
* @version Since caAdapter v4.0 revision
* $Revision: 1.4 $
* $Date: 2008-06-09 19:53:51 $
*/
public class Entity {
private String schema = null;
private String entityName = null;
/**
* Creates a new instance of Entity
*/
public Entity(String schema, String entityName) {
this.setSchema(schema);
this.setEntityName(entityName);
}
public String toString() {
return getEntityName();
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
/**
* Change History
* $Log: not supported by cvs2svn $
* Revision 1.3 2008/06/06 18:55:19 phadkes
* Changes for License Text
*
* Revision 1.2 2007/08/16 19:04:58 jayannah
* Reformatted and added the Comments and the log tags for all the files
*
*/
|
Java
|
define(function () {
return [
{
"default": {
name: 'form1',
label: 'Form 1',
"_elements": [
{
"default": {
"name": "id",
"type": "hidden"
}
},
{
"default": {
"name": "test1",
"type": "text",
"label": "Test1",
"defaultValue": "test1",
"page": 0
}
},
{
"default": {
"name": "test2",
"type": "text",
"label": "Test2",
"defaultValue": "test2",
"page": 0
}
},
{
"default": {
"name": "calc_button",
"type": "button",
"label": "Calculate",
"persist": false,
"page": 0
}
},
{
"default": {
"name": "calc",
"type": "message",
"label": "Calc",
"labelPlacement": "default",
"labelStyle": "Plain",
"showTextbox": "show",
"calculationType": "manual",
"buttonText": "Calculate",
"persist": true,
"page": 0
}
}
],
"_checks": [
],
"_actions": [
{
"default": {
"javascript": "\"[test1]\"+\"[test2]\"",
"outputTarget": "calc",
"name": "CALC_calc"
}
}
],
"_behaviours": [
{
"default": {
"name": "auto_calculations",
"trigger": {
"formElements": ["calc_button"]
},
"actions": [
"CALC_calc"
]
}
}
]
}
}
];
});
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.