repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
szaghi/VecFor | src/tests/vecfor_R4P/vecfor_R4P-doctest-167.f90 | 149 | program volatile_doctest
use vecfor_R4P
type(vector_R4P) :: pt
pt = ex_R4P + ey_R4P + ez_R4P
print "(L1)", 4_I8P >= pt
endprogram volatile_doctest | bsd-2-clause |
johnkerl/mcmc-interacting-spatial-permutations | psdes.h | 6407 | // ================================================================
// Copyright (c) 2004 John Kerl.
// [email protected]
//
// This code and information is provided as is without warranty of
// any kind, either expressed or implied, including but not limited to
// the implied warranties of merchantability and/or fitness for a
// particular purpose.
//
// No restrictions are placed on copy or reuse of this code, as long
// as these paragraphs are included in the code.
// ================================================================
// ================================================================
// The following is a pseudorandom sequence generator, loosely inspired by DES,
// adapted from _Numerical Recipes in C_.
//
// John Kerl
// [email protected]
// 2004-08-14
//
// ================================================================
// The key function is a 64-bit-to-64-bit hash. The former 64 bits are the
// generator state; the latter are the generator output:
//
// * Seeding the generator means setting the 64-bit state.
//
// * Stepping the generator runs the hash on the 64-bit state, then
// incrementing the state, then returning the hash output.
//
// * The generator thus has a period of 2^64.
//
// Example: Suppose the state is set to 0x00000002fffffffc. The generator
// is run 6 times, with the following output:
//
// State Output
// ------------------ ------------------
// 0x00000002fffffffc 0x57733ef0998adaea
// 0x00000002fffffffd 0xe486359a3e59f158
// 0x00000002fffffffe 0x624cb3680dd3090c
// 0x00000002ffffffff 0x5e920cb5bfc315ce
// 0x0000000300000000 0xadcd49eef6f27d08
// 0x0000000300000001 0x786f6a22d7df7670
//
// The state will now be 0x0000000300000002.
//
// ================================================================
// Details:
//
// * 64-bit integers are represented as a 32-bit pair.
//
// * Several functions are supplied, some of which only return the bottom
// 32 bits of the generator output.
//
// * Non-reentrant and reentrant versions are supplied. The former are
// simpler to call; the generator state is remembered for you. For the
// latter, you keep the state yourself. (However, the generator will
// still increment your state each time it is called.) Reentrant versions
// end in "_r".
//
// * For the reentrant versions, you must seed the generator (i.e. assign
// values to the two 32-bit state values) yourself. For convenience,
// a function (sran32_tod_r) is supplied, which you can use to obtain a
// seed value which will probably be different on each call.
//
// * For the non-reentrant version, you may seed the generator if you wish,
// but you do not need to. The generator remembers if its state has been
// seeded -- if not, it sets a time-of-day seed the first time it is called.
//
// ================================================================
// Sample usage:
// * Non-reentrant version with default seeds:
//
// unsigned rand;
// rand = iran32();
// rand = iran32();
// rand = iran32();
//
// double rand;
// rand = fran32();
// rand = fran32();
// rand = fran32();
// * Non-reentrant version with specified seeds:
//
// unsigned rand;
// sran32(1);
// // Or, sran32b(0, 1);
// rand = iran32();
// rand = iran32();
// rand = iran32();
//
// double rand;
// sran32(1);
// // Or, sran32b(0, 1);
// rand = fran32();
// rand = fran32();
// rand = fran32();
// * Reentrant version with time-of-day seeds:
//
// unsigned state0, state1, rand;
// sran32_tod_r(1, &state0, &state1);
// rand = iran32(&state0, &state1);
// rand = iran32(&state0, &state1);
// rand = iran32(&state0, &state1);
//
// unsigned state0, state1;
// double rand;
// sran32(1);
// rand = fran32(&state0, &state1);
// rand = fran32(&state0, &state1);
// rand = fran32(&state0, &state1);
// * Reentrant version with specified seeds:
//
// unsigned state0, state1, rand;
// state0 = 7;
// state1 = 8;
// rand = iran32(&state0, &state1);
// rand = iran32(&state0, &state1);
// rand = iran32(&state0, &state1);
//
// unsigned state0, state1;
// double rand;
// state0 = 7;
// state1 = 8;
// rand = fran32(&state0, &state1);
// rand = fran32(&state0, &state1);
// rand = fran32(&state0, &state1);
// ================================================================
#ifndef PSDES_H
#define PSDES_H
// ----------------------------------------------------------------
// These versions are non-reentrant.
// Usage: Nominally, just call iran32() or fran32(). They remember whether
// or not a seed has been supplied, and call sran32_tod() if not. Use sran32()
// only if you want to force the same generator output each time.
// Uniformly distributed pseudorandom 32-bit integer.
unsigned iran32(void);
// Uniformly distributed pseudorandom 64-bit integer.
void iran64(unsigned * pout0, unsigned * pout1);
// Uniformly distributed single-precision double between 0.0 and 1.0.
double fran32(void);
// Sets lower 32 bits of generator state to the specified value, and sets
// the upper 32 bits of generator state to 0.
void sran32(unsigned s);
// Sets all 64 bits of generator state to the specified values.
void sran32b(unsigned s0, unsigned s1);
// Sets all 64 bits of generator state to the values dependent on the
// Unix PID, time of day in seconds, and time of day in microseconds.
void sran32_tod(void);
// ----------------------------------------------------------------
// These versions are reentrant.
// Uniformly distributed pseudorandom 32-bit integer.
unsigned iran32_r(unsigned * pstate0, unsigned * pstate1);
// Uniformly distributed pseudorandom 64-bit integer.
void iran64_r(unsigned * pout0, unsigned * pout1,
unsigned * pstate0, unsigned * pstate1);
// Uniformly distributed single-precision double between 0.0 and 1.0.
double fran32_r(unsigned * pstate0, unsigned * pstate1);
// There is no sran32_r() function. You own the state variables and may
// assign to them whatever values you wish.
// This puts time-of-day information into your state variables.
void sran32_tod_r(unsigned * pstate0, unsigned * pstate1void);
// ----------------------------------------------------------------
// This is the 64-bit pseudo-DES in-place hash.
void psdes_hash_64(
unsigned * pword0,
unsigned * pword1);
#endif // PSDES_H
| bsd-2-clause |
ptek/tofu-kozo | spec/spec_tools.rb | 1231 | require 'asdf'
require 'cgi'
require 'json'
module SpecTools
def run_server
$stdout.reopen("/dev/null", "a")
$stderr.reopen("/dev/null", "a")
Dir.chdir "./test_files"
Asdf::Server.start
end
def inner_html string
string.gsub(/^<html>/,"").gsub(/<\/html>/,"")
end
def e url
CGI.escape url
end
def error_msg text
{"actionStatus" => "error", "content"=> text}
end
def ok_msg page_body
{"actionStatus" => "ok", "content"=> page_body.gsub("\n", "")}
end
def result_path token
tmp_dir + token
end
def tmp_dir
"/tmp/tofu-kozo/#{@kozo_port}/"
end
# just an alias for better readablitiy in tests
def discard_result token
interpret_result token
end
def interpret_result token, tries=5
if tries < 0
raise "Could not get result file for #{token}."
end
s = File.read(result_path token)
if s.length == 0
sleep 1
return interpret_result(token, tries - 1)
end
dirty = JSON.parse s
if dirty["content"]
clean_content = dirty["content"].gsub("\n","")
else
clean_content = ""
end
{
"actionStatus" => dirty["actionStatus"],
"content" => clean_content
}
end
end
| bsd-2-clause |
Remotion/reflect | tests/reflection_test.cpp | 4697 | /* blah_test.cpp -*- C++ -*-
Rémi Attab ([email protected]), 29 Mar 2014
FreeBSD-style copyright and disclaimer apply
Experimental tests
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define REFLECT_USE_EXCEPTIONS 1
#include "reflect.h"
#include "types/primitives.h"
#include "dsl/all.h"
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace reflect;
/******************************************************************************/
/* BAR */
/******************************************************************************/
namespace test {
struct Bar
{
Bar() : bar(0) {}
int bar;
};
} // namespace test
reflectType(test::Bar)
{
reflectField(bar);
}
/******************************************************************************/
/* FOO */
/******************************************************************************/
namespace test {
struct Foo : public Bar
{
Foo() : field(0), constField(0), value(0) {}
Foo(int i) : field(i), constField(i), value(i) {}
int field;
const int constField;
void void_() {}
void copyArg(int i) { value = i; }
int copyRet() const { return value; }
void lValueArg(int& i) { value = i; }
int& lValueRet() { return value; }
void constLValueArg(const int& i) { value = i; }
const int& constLValueRet() const { return value; }
void rValueArg(int&& i) { value = std::move(i); }
int rValueRet() { return std::move(value); }
void fn(int a, int b, int c) { value += a * b + c; }
static int staticFn(int a, int b) { return a * b ;}
static int staticFn(int a, int b, int c) { return a * b + c;}
Foo& operator+=(const Foo& other)
{
field += other.field;
value += other.value;
return *this;
}
Foo operator+(const Foo& other) const
{
Foo result(*this);
result += other;
return result;
}
int value;
};
} // namespace test
reflectType(test::Foo)
{
reflectParent(test::Bar);
reflectCons(int);
reflectPlumbing();
reflectOpAssign();
reflectOpArithmetic();
reflectFn(void_);
reflectField(value);
reflectField(field);
reflectField(constField);
reflectFn(copyArg);
reflectFn(copyRet);
reflectFn(lValueArg);
reflectFn(lValueRet);
reflectFn(constLValueArg);
reflectFn(constLValueRet);
reflectFn(rValueArg);
reflectFn(rValueRet);
reflectFn(fn);
reflectFnTyped(staticFn, int(int, int));
reflectFnTyped(staticFn, int(int, int, int));
reflectCustom(custom) (test::Foo& obj, int a, int b) {
obj.value = a + b;
};
}
/******************************************************************************/
/* TESTS */
/******************************************************************************/
BOOST_AUTO_TEST_CASE(basics)
{
const Type* typeBar = type("test::Bar");
const Type* typeFoo = type("test::Foo");
BOOST_CHECK(typeBar);
BOOST_CHECK(typeFoo);
std::cerr << scope()->print() << std::endl;
std::cerr << typeBar->print() << std::endl;
std::cerr << typeFoo->print() << std::endl;
BOOST_CHECK_EQUAL(typeFoo->parent(), typeBar);
BOOST_CHECK( typeFoo->isChildOf(typeBar));
BOOST_CHECK(!typeBar->isChildOf(typeFoo));
BOOST_CHECK( typeBar->hasField("bar"));
BOOST_CHECK(!typeBar->hasField("field"));
BOOST_CHECK( typeFoo->hasField("bar"));
BOOST_CHECK(!typeFoo->hasField("baz"));
BOOST_CHECK(!typeFoo->hasField("void_"));
BOOST_CHECK( typeFoo->hasField("field"));
BOOST_CHECK( typeFoo->hasFunction("fn"));
BOOST_CHECK( typeFoo->hasFunction("custom"));
Value vFoo = typeFoo->construct();
const auto& foo = vFoo.get<test::Foo>();
const auto& bar = vFoo.get<test::Bar>();
BOOST_CHECK_EQUAL(
typeFoo->call<int>("staticFn", 1, 2),
test::Foo::staticFn(1,2));
vFoo.field("bar").assign(1);
BOOST_CHECK_EQUAL(foo.bar, 1);
BOOST_CHECK_EQUAL(bar.bar, 1);
BOOST_CHECK_EQUAL(vFoo.field<int>("bar"), foo.bar);
vFoo.field("value").assign(1);
BOOST_CHECK_EQUAL(foo.value, 1);
BOOST_CHECK_EQUAL(vFoo.field<int>("value"), foo.value);
Value a = vFoo.call<Value>("copyRet");
vFoo.call<void>("custom", a, 2);
BOOST_CHECK_EQUAL(foo.value, a.get<int>() + 2);
Value result = typeFoo->construct(100) + typeFoo->construct(20);
BOOST_CHECK_EQUAL(result.field<int>("field"), 120);
}
| bsd-2-clause |
lephuoccat/MATLAB | spfirst/filterdesign/help/theory.html | 4235 | <html>
<head>
<title> Theory </title>
<link rel="stylesheet" href="pagestyles.css">
</head>
<body>
<div class="Heading">
Theory
</div>
<div class="Entry">
<ol>
<li><a href="#Theory"><strong>Theory</strong></a></li>
<li><a href="#Windows"><strong>Windows</strong></a></li>
</ol>
</div>
<a name="Theory">
<div class="SubHeading">
Filter Design - Theory
</div></a>
<p>
Please refer to <em>"Discrete-Time Signal Processing" by Alan V. Oppenheim and Ronald W. Schafer </em>, for a detailed explanation of the theoretical concepts presented in this GUI.</p>
<a name="Windows">
<div class="SubHeading">
Filter Design - Windows
</div></a>
<p>
The equations of various <b>Windows</b> used in FIR Filter Design section are
presented below:</p>
<ol>
<li>
<p class="MsoNormal" style="line-height: 200%"><font face="Arial">
<font face="Arial"><b>Rectangular:</b> w(n) = 1 for n = 0, 1,
.., N-1</font>
</li>
<li>
<p class="MsoNormal" style="line-height: 200%"><font face="Arial"><font face="Arial"><b>Bartlett:</b>
w(n) = 1- (|n-N/2| / N/2) for n = 0 to N-1</font>
</li>
<li>
<p class="MsoNormal" style="line-height: 200%"><font face="Arial"><b>Hann:</b>
w(n) = 0.5- 0.5*cos(2*pi*n/N) for n = 0 to N-1 </font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<font face="Arial"><b>Hamming: </b>w(n) = 0.54 - 0.46*cos(2*pi*n/N)
for n = 0 to N-1</font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<font face="Arial"><b>Blackman:</b> w(n) = 0.42 -
0.5*cos(2*k*n/(N-1)) + 0.08*cos(4*pi*k/(N-1)) </font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<font face="Arial"><b>Gaussian:</b> w(n) = exp(-.5*
(((alpha*(n-N/2))/(N/2)).^2)) </font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<font face="Arial"><b>Dolph-Chebyshev </b>: beta = cosh ( ( acosh
(10^alpha) /N ) ) W(k)= ( (-1) ^k) * cos(N * acos( ( beta * cos(pi * k/N) ) )
) / cosh(len * acosh(beta) )</font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<face="Arial"><b>Lanczos</b>:
w(n) = sin( (n-N/2) *pi / N)</font></li>
<li>
<p class="MsoNormal" style="line-height: 200%">
<face="Arial"><b>Kaiser</b>:
</font>
</li>
<!-- <li>
<p class="MsoNormal" style="line-height: 200%"><font face="Arial"><b>Barcilon-Temes:
</b> C=acosh(10^alpha);<br>
beta=cosh(C/N);<br>
A = sinh(C);<br>
B = cosh(C);<br>
y = N * acos( beta * cos( pi * n/N ) );<br>
W(n) = ((-1)^n) * (A * cos( y ) ) + ( B*(y * sin(y) /C ) )/ (C+A*B) * ( ( y/C
) ^2 +1)</font></li> -->
</ol>
<em>Harris, F. J. "On the Use of Windows for Harmonic Analysis with
the Discrete Fourier Transform." Proceedings of the IEEE. Vol. 66
(January 1978)</em>
<p>
<a name="Windows">
<div class="SubHeading"> Filter Design - Parks-McClellan</div></a>
<p style="line-height: 200%">The Parks-McClellan designs an optimum
FIR filter given a set of specifications and uses Remez Iterations in order to
design the filter. The Parks-McClellan algorithm for the design is referred from
Chapter-7 of "<i>Discrete-Time Signal Processing"<b> </b>by Alan V. Oppenheim
and Ronald W. Schafer</i>. </p>
<h4><a href="#top"><small>[Back to Top]</small></a></h4>
</body>
</html> | bsd-2-clause |
ohsu-qin/qiprofile | src/common/moment.pipe.ts | 834 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'moment'})
/**
* Transforms a moment date value to a display value.
*
* @module common
* @class MomentPipe
*/
export class MomentPipe implements PipeTransform {
constructor() { }
/**
* Looks up the input value within the `choices.cfg` section
* for the given topic. If found, then this method returns
* the look-up result, otherwise this method returns the
* input value. If the input value is an array, then this
* method collects the item transformations.
*
* @method transform
* @param value {Object} the moment date input
* @param format {string} the optional date format
* @return {string} the display string
*/
transform(value: Object, format='MM/DD/YYYY'): string {
return value && value.format(format);
}
}
| bsd-2-clause |
daviddpd/dpdChatFabric | tools/nonce.c | 788 |
#include <stdio.h>
#include <sys/types.h> // kqueue / kevent
#include <stdlib.h> // exit
#include <netinet/in.h>
#define crypto_secretbox_NONCEBYTES 8U
void
print_bin2hex(unsigned char * x, int len) {
int i;
for (i=0; i<len; i++) {
printf ( "%02x", x[i] );
if ( (i>0) && ( (i+1)%4 == 0 ) ) { printf (" "); }
}
printf ("\n");
}
int main(int argc, char**argv)
{
uint32_t u,l;
unsigned char mynonce[crypto_secretbox_NONCEBYTES];
arc4random_buf(&(mynonce), crypto_secretbox_NONCEBYTES);
while (1) {
print_bin2hex( &(mynonce), crypto_secretbox_NONCEBYTES );
memcpy ( &u, &(mynonce), 4);
memcpy ( &l, &(mynonce[4]), 4);
u = htonl(u);
l = htonl(l);
l++;
u = ntohl(u);
l = ntohl(l);
memcpy ( &(mynonce), &u, 4);
memcpy ( &(mynonce[4]), &l, 4);
}
}
| bsd-2-clause |
ox-vgg/vise | src/vise/vise_util.h | 4323 | /** @file util.h
* @brief Various utility functions used by VISE
* @author Abhishek Dutta
* @date 12 Nov. 2019
*/
#ifndef VISE_UTIL_H
#define VISE_UTIL_H
#include <string>
#include <map>
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <regex>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <omp.h>
#include <cmath>
#include <boost/filesystem.hpp>
#include <Magick++.h>
#include "vise_version.h"
/*
#ifndef ASSERT
#define ASSERT(expression) if (!(expression)) { std::cerr << "Precondition failed: " #expression " in " << __FUNCTION__ << " (" __FILE__ ":" << __LINE__ << ")\n"; exit(1); }
#endif
*/
namespace vise {
// command line interface (CLI)
bool parse_cli_args(int argc, char **argv,
std::unordered_map<std::string, std::string> &cli_args,
std::unordered_map<std::string, std::string> &pname_pconf_list);
// VISE settings
void init_vise_settings_comments(std::map<std::string, std::string> &vise_settings);
void init_vise_settings(std::map<std::string, std::string> &vise_settings);
bool does_vise_home_and_store_exist(std::map<std::string, std::string> &vise_settings);
bool create_vise_home_and_store(std::map<std::string, std::string> &vise_settings);
void init_default_vise_settings(std::map<std::string, std::string> &vise_settings);
// VISE configuration
bool configuration_load(std::string filename,
std::map<std::string, std::string> &conf );
bool configuration_save(std::map<std::string, std::string> &conf,
std::string filename);
void configuration_show(std::map<std::string, std::string> const &conf);
std::string configuration_get(std::string key);
uint32_t configuration_get_nthread();
boost::filesystem::path vise_home();
// string
bool starts_with(const std::string &s, const std::string prefix);
bool ends_with(const std::string &s, const std::string suffix);
bool contains(const std::string &s, const std::string substr);
std::vector<std::string> split(const std::string &s, const char separator);
void split(const std::string &s,
const char separator,
const std::size_t start,
const std::size_t stop,
std::vector<std::string> &chunks);
void decompose_uri(const std::string &uri,
std::vector<std::string>& uri_components,
std::unordered_map<std::string, std::string>& uri_param);
void parse_urlencoded_form(const std::string &formdata_str,
std::unordered_map<std::string, std::string>& formdata);
void escape_string(std::string &in, char match_char, std::string replace_match_with);
// file
bool file_load(const boost::filesystem::path fn,
std::string& file_content);
bool file_save(const boost::filesystem::path fn,
std::string& file_content);
bool file_save_binary(const boost::filesystem::path fn,
std::string& file_content);
// URI decoding
// e.g. "http%3A%2F%2Ffoo%20bar%2F" -> "http://foo bar/"
bool url_decode(const std::string& in, std::string& out);
bool decode_uri_query_param(const std::string& in, std::string& out); // '+' is decoded as space ' '
std::string json_escape_str(const std::string &in);
// print
template<typename T>
void print_vector( std::string name, std::vector<T> const &v ) {
if (v.size() == 0) {
return;
}
std::ostringstream s;
s << v[0];
for ( std::size_t i = 1; i < v.size(); ++i ) {
s << "," << v[i];
}
std::cout << name << " = [" << s.str() << "]" << std::endl;
}
void print_map(std::string name,
std::map<std::string, std::string> const &m );
// timing and profiling
std::string now_timestamp();
uint32_t getmillisecs();
// check if input image is valid
bool is_valid_image(std::string img_fn, std::string &message);
bool if_valid_get_image_size(std::string img_fn, std::string &message, uint32_t &width, uint32_t &height);
// parse string
void csv_string_to_float_array(std::string csv_string,
std::vector<float> &float_array);
double iou(std::vector<float> &a, std::vector<float> &b);
}
#endif
| bsd-2-clause |
qqzwc/XX-Net | code/default/x_tunnel/local/cloudflare_front/front.py | 6638 | import time
import os
import threading
import collections
from xlog import getLogger
xlog = getLogger("cloudflare_front")
xlog.set_buffer(500)
import simple_http_client
from config import config
import http_dispatcher
import connect_control
import check_ip
class Front(object):
name = "cloudflare_front"
def __init__(self):
self.dispatchs = {}
threading.Thread(target=self.update_front_domains).start()
self.last_success_time = time.time()
self.last_fail_time = 0
self.continue_fail_num = 0
self.success_num = 0
self.fail_num = 0
self.last_host = "center.xx-net.net"
self.rtts = collections.deque([(0, time.time())])
self.rtts_lock = threading.Lock()
self.traffics = collections.deque()
self.traffics_lock = threading.Lock()
self.recent_sent = 0
self.recent_received = 0
self.total_sent = 0
self.total_received = 0
threading.Thread(target=self.debug_data_clearup_thread).start()
@staticmethod
def update_front_domains():
next_update_time = time.time()
while connect_control.keep_running:
if time.time() < next_update_time:
time.sleep(4)
continue
try:
timeout = 30
if config.getint("proxy", "enable", 0):
client = simple_http_client.Client(proxy={
"type": config.get("proxy", "type", ""),
"host": config.get("proxy", "host", ""),
"port": int(config.get("proxy", "port", "0")),
"user": config.get("proxy", "user", ""),
"pass": config.get("proxy", "passwd", ""),
}, timeout=timeout)
else:
client = simple_http_client.Client(timeout=timeout)
url = "https://raw.githubusercontent.com/XX-net/XX-Net/master/code/default/x_tunnel/local/cloudflare_front/front_domains.json"
response = client.request("GET", url)
if response.status != 200:
xlog.warn("update front domains fail:%d", response.status)
raise Exception("status:%r", response.status)
need_update = True
front_domains_fn = os.path.join(config.DATA_PATH, "front_domains.json")
if os.path.exists(front_domains_fn):
with open(front_domains_fn, "r") as fd:
old_content = fd.read()
if response.text == old_content:
need_update = False
if need_update:
with open(front_domains_fn, "w") as fd:
fd.write(response.text)
check_ip.update_front_domains()
next_update_time = time.time() + (4 * 3600)
xlog.info("updated cloudflare front domains from github.")
except Exception as e:
next_update_time = time.time() + (1800)
xlog.debug("updated cloudflare front domains from github fail:%r", e)
def log_debug_data(self, rtt, sent, received):
now = time.time()
self.rtts.append((rtt, now))
with self.traffics_lock:
self.traffics.append((sent, received, now))
self.recent_sent += sent
self.recent_received += received
self.total_sent += sent
self.total_received += received
def get_rtt(self):
now = time.time()
while len(self.rtts) > 1:
with self.rtts_lock:
rtt, log_time = rtt_log = max(self.rtts)
if now - log_time > 5:
self.rtts.remove(rtt_log)
continue
return rtt
return self.rtts[0][0]
def debug_data_clearup_thread(self):
while True:
now = time.time()
with self.rtts_lock:
if len(self.rtts) > 1 and now - self.rtts[0][-1] > 5:
self.rtts.popleft()
with self.traffics_lock:
if self.traffics and now - self.traffics[0][-1] > 60:
sent, received, _ = self.traffics.popleft()
self.recent_sent -= sent
self.recent_received -= received
time.sleep(1)
def worker_num(self):
host = self.last_host
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
dispatcher = self.dispatchs[host]
return len(dispatcher.workers)
def get_score(self, host=None):
now = time.time()
if now - self.last_fail_time < 60 and \
self.continue_fail_num > 10:
return None
if host is None:
host = self.last_host
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
dispatcher = self.dispatchs[host]
worker = dispatcher.get_worker(nowait=True)
if not worker:
return None
return worker.get_score()
def request(self, method, host, path="/", headers={}, data="", timeout=120):
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
self.last_host = host
dispatcher = self.dispatchs[host]
response = dispatcher.request(method, host, path, dict(headers), data, timeout=timeout)
if not response:
xlog.warn("req %s get response timeout", path)
return "", 602, {}
status = response.status
if status not in [200, 405]:
# xlog.warn("front request %s %s%s fail, status:%d", method, host, path, status)
self.fail_num += 1
self.continue_fail_num += 1
self.last_fail_time = time.time()
else:
self.success_num += 1
self.continue_fail_num = 0
content = response.task.read_all()
if status == 200:
xlog.debug("%s %s%s status:%d trace:%s", method, response.worker.ssl_sock.host, path, status,
response.task.get_trace())
else:
xlog.warn("%s %s%s status:%d trace:%s", method, response.worker.ssl_sock.host, path, status,
response.task.get_trace())
return content, status, response
def stop(self):
connect_control.keep_running = False
front = Front()
| bsd-2-clause |
Auxx/niceql | niceql/src/com/grilledmonkey/niceql/structs/Migration.java | 707 | package com.grilledmonkey.niceql.structs;
import java.util.LinkedList;
import java.util.List;
import com.grilledmonkey.niceql.interfaces.SqlMigration;
public class Migration implements SqlMigration {
private final List<String> sql = new LinkedList<String>();
private int version;
public Migration() {
this(1);
}
public Migration(int version) {
this.version = version;
}
@Override
public List<String> getSql() {
return(sql);
}
@Override
public void addStatement(String sql) {
this.sql.add(sql);
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public int getVersion() {
return(version);
}
}
| bsd-2-clause |
yangcha/cmake-modules | README.md | 1133 | # cmake-modules
A collection of CMake utility functions for setting runtime library paths, environmental variables, working directory for Visual C++. And function for adding unit tests using google test with cmake.
```
SET_PROGRAM_ENV(<name>
[WORKING_DIRECTORY <dir>]
[RUNTIME_DIRS <dirs>...]
[ENVIRONMENT <VAR=value>...]
[COMMAND_ARGS <value>]
)
```
The WORKING_DIRECTORY specifies the program working directory. RUNTIME_DIRS specifies the dynamic library directories. ENVIRONMENT sets the environmental variables and command arguments. See the following example:
```
include(SetProgramEnv)
set_program_env( Example1
WORKING_DIRECTORY
"${CMAKE_BINARY_DIR}/bin"
RUNTIME_DIRS
"${CMAKE_BINARY_DIR}/bin"
"C:\\Users\\Documents\\Visual Studio 2010"
ENVIRONMENT
"BINROOT=${CMAKE_BINARY_DIR}"
"SRCROOT=${CMAKE_SOURCE_DIR}"
COMMAND_ARGS
"input output"
)
```
To add an unit test with Google test, use function:
```
ADD_GTEST(<name>
source1 [source2 ...])
```
See the following example to add unit test using cmake with google test framework:
```
include(gtest)
add_gtest(unitTest test_example.cpp)
```
| bsd-2-clause |
fabiang/mink-javascript-errors | src/ErrorHandler.js | 3639 | /**
* Copyright 2015 Fabian Grutschus. 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 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the copyright holders.
*
* @author Fabian Grutschus <[email protected]>
* @copyright 2015 Fabian Grutschus. All rights reserved.
* @license BSD-2-Clause
*/
;(function (global, storage) {
var originalOnError = function () {};
if (typeof global.onerror === "function") {
originalOnError = global.onerror;
}
var E = {
storageKey: "fabiang_error_handler",
register: function () {
global.onerror = function () {
var args = Array.prototype.slice.call(arguments);
E.handle.apply(null, args);
originalOnError.apply(null, args);
};
E.registerForjQuery();
},
registerForjQuery: function () {
if (typeof global.jQuery === "function") {
jQuery(global.document).ajaxError(function (e, xhr, settings, message) {
var error = {
message: message.length > 0 ? message : "Unknown error",
method: settings.type,
url: settings.url,
type: "ajaxError"
};
E.store(error);
});
}
},
handle: function (message, file, lineno, column) {
var error = {
message: message,
file: file,
lineno: lineno,
column: column,
type: "error"
};
E.store(error);
},
store: function (error) {
var errors = E.get();
errors.push(error);
storage.setItem(E.storageKey, JSON.stringify(errors));
},
get: function () {
if (null !== storage.getItem(E.storageKey)) {
return JSON.parse(storage.getItem(E.storageKey));
}
return [];
},
clear: function () {
storage.setItem(E.storageKey, "[]");
}
};
global.ErrorHandler = E;
E.register();
}(this, localStorage)); | bsd-2-clause |
kolyvan/kxutils | readme.md | 62 | ##KxUtils
A sets of useful components and categories for iOS. | bsd-2-clause |
sivrit/TracingAgent | Agent/src/test/java/fr/sivrit/traceragent/options/AgentOptionsTest.java | 2935 | package fr.sivrit.traceragent.options;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import fr.sivrit.tracingagent.options.AgentOptions;
public class AgentOptionsTest {
private void assertDefaults(final AgentOptions options) {
assertFalse(options.enhanceAtStartup);
assertFalse(options.logAtStartup);
assertTrue(options.enableJmx);
assertEquals(System.getProperty("user.home") + "/log.gz",
options.outputFile);
assertNull(options.ruleFile);
}
@Test
public void noArgsMeansDefaultValues() {
final AgentOptions opt = AgentOptions.parseOptions("");
assertDefaults(opt);
}
@Test
public void nullArgsMeansDefaultValues() {
final AgentOptions opt = AgentOptions.parseOptions(null);
assertDefaults(opt);
}
@Test
public void unknownArgsAreTolerated() {
final AgentOptions opt = AgentOptions
.parseOptions("strangeArg,moar=args,and=mo-re");
assertDefaults(opt);
}
@Test
public void emtyArgsAreTolerated() {
final AgentOptions opt = AgentOptions.parseOptions(",,,");
assertDefaults(opt);
}
@Test
public void setEnhanceToTrue() {
final AgentOptions opt = AgentOptions.parseOptions("enhance=true");
assertTrue(opt.enhanceAtStartup);
}
@Test
public void setEnhanceToFalse() {
final AgentOptions opt = AgentOptions.parseOptions("enhance=false");
assertFalse(opt.enhanceAtStartup);
}
@Test
public void setLogToTrue() {
final AgentOptions opt = AgentOptions.parseOptions("log=true");
assertTrue(opt.logAtStartup);
}
@Test
public void setLogToFalse() {
final AgentOptions opt = AgentOptions.parseOptions("log=false");
assertFalse(opt.logAtStartup);
}
@Test
public void setJmxToTrue() {
final AgentOptions opt = AgentOptions.parseOptions("jmx=true");
assertTrue(opt.enableJmx);
}
@Test
public void setJmxToFalse() {
final AgentOptions opt = AgentOptions.parseOptions("jmx=false");
assertFalse(opt.enableJmx);
}
@Test
public void setOutputDir() {
final AgentOptions opt = AgentOptions.parseOptions("output=./someFile");
assertEquals("./someFile", opt.outputFile);
}
@Test
public void setRulesFile() {
final AgentOptions opt = AgentOptions.parseOptions("rules=./rules.txt");
assertEquals("./rules.txt", opt.ruleFile);
}
@Test
public void setMultipleOptions() {
final AgentOptions opt = AgentOptions
.parseOptions("log=true,output=./someFile,rules=./rules.txt,jmx=true,");
assertEquals("./someFile", opt.outputFile);
assertEquals("./rules.txt", opt.ruleFile);
assertTrue(opt.enableJmx);
assertTrue(opt.logAtStartup);
}
}
| bsd-2-clause |
bradleyjford/entr | src/Entr.Domain/EntityNotFoundException.cs | 594 | using System;
using System.Runtime.Serialization;
namespace Entr.Domain
{
[Serializable]
public class EntityNotFoundException : Exception
{
public EntityNotFoundException()
{
}
public EntityNotFoundException(string message) : base(message)
{
}
public EntityNotFoundException(string message, Exception inner) : base(message, inner)
{
}
protected EntityNotFoundException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
}
| bsd-2-clause |
wushuyi/PolygonTest | readme.md | 55 | # PolygonTest
一个用于勾勒PIXI多边形的测试 | bsd-2-clause |
steinwurf/petro | src/petro/box/tfhd.cpp | 260 | // Copyright (c) Steinwurf ApS 2016.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#include "tfhd.hpp"
#include <string>
namespace petro
{
namespace box
{
const std::string tfhd::TYPE = "tfhd";
}
}
| bsd-3-clause |
quantmind/jflib | include/boost/numeric/bindings/blas/level3.hpp | 356 | //
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_NUMERIC_BINDINGS_BLAS_LEVEL3_HPP
#define BOOST_NUMERIC_BINDINGS_BLAS_LEVEL3_HPP
#include <boost/numeric/bindings/blas/solve.hpp>
#endif
| bsd-3-clause |
MarginC/kame | netbsd/sys/arch/shark/stand/ofwboot/Locore.c | 9497 | /* $NetBSD: Locore.c,v 1.1 2002/02/10 01:58:15 thorpej Exp $ */
/*
* Copyright (C) 1995, 1996 Wolfgang Solfrank.
* Copyright (C) 1995, 1996 TooLs GmbH.
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by TooLs GmbH.
* 4. The name of TooLs GmbH may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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 <lib/libsa/stand.h>
#include <machine/cpu.h>
#include <arm/armreg.h>
#include "cache.h"
#include "openfirm.h"
static int (*openfirmware_entry) __P((void *));
static int openfirmware __P((void *));
void startup __P((int (*)(void *), char *, int));
static void setup __P((void));
void (*cache_syncI)(void);
void abort(void);
void abort(void)
{
/* Stupid compiler (__dead). */
for (;;) ;
}
static int
openfirmware(arg)
void *arg;
{
openfirmware_entry(arg);
}
static vaddr_t
ofw_getcleaninfo(void)
{
int cpu, vclean;
if ((cpu = OF_finddevice("/cpu")) == -1)
panic("no /cpu from OFW");
if (OF_getprop(cpu, "d-cache-flush-address", &vclean,
sizeof(vclean)) != sizeof(vclean)) {
printf("WARNING: no OFW d-cache-flush-address property\n");
return (RELOC);
}
return (of_decode_int((unsigned char *)&vclean));
}
void
startup(openfirm, arg, argl)
int (*openfirm)(void *);
char *arg;
int argl;
{
u_int cputype = cpufunc_id() & CPU_ID_CPU_MASK;
openfirmware_entry = openfirm;
setup();
/*
* Determine the CPU type, and set up the appropriate
* I$ sync routine.
*/
if (cputype == CPU_ID_SA110 || cputype == CPU_ID_SA1100 ||
cputype == CPU_ID_SA1110) {
extern vaddr_t sa110_cache_clean_addr;
cache_syncI = sa110_cache_syncI;
sa110_cache_clean_addr = ofw_getcleaninfo();
} else {
printf("WARNING: no I$ sync routine for CPU 0x%x\n",
cputype);
}
main();
OF_exit();
}
int
of_decode_int(const u_char *p)
{
unsigned int i = *p++ << 8;
i = (i + *p++) << 8;
i = (i + *p++) << 8;
return (i + *p);
}
__dead void
OF_exit()
{
static struct {
char *name;
int nargs;
int nreturns;
} args = {
"exit",
0,
0
};
openfirmware(&args);
for (;;); /* just in case */
}
int
OF_finddevice(name)
char *name;
{
static struct {
char *name;
int nargs;
int nreturns;
char *device;
int phandle;
} args = {
"finddevice",
1,
1,
};
args.device = name;
if (openfirmware(&args) == -1)
return -1;
return args.phandle;
}
int
OF_instance_to_package(ihandle)
int ihandle;
{
static struct {
char *name;
int nargs;
int nreturns;
int ihandle;
int phandle;
} args = {
"instance-to-package",
1,
1,
};
args.ihandle = ihandle;
if (openfirmware(&args) == -1)
return -1;
return args.phandle;
}
int
OF_getprop(handle, prop, buf, buflen)
int handle;
char *prop;
void *buf;
int buflen;
{
static struct {
char *name;
int nargs;
int nreturns;
int phandle;
char *prop;
void *buf;
int buflen;
int size;
} args = {
"getprop",
4,
1,
};
args.phandle = handle;
args.prop = prop;
args.buf = buf;
args.buflen = buflen;
if (openfirmware(&args) == -1)
return -1;
return args.size;
}
#ifdef __notyet__ /* Has a bug on FirePower */
int
OF_setprop(handle, prop, buf, len)
int handle;
char *prop;
void *buf;
int len;
{
static struct {
char *name;
int nargs;
int nreturns;
int phandle;
char *prop;
void *buf;
int len;
int size;
} args = {
"setprop",
4,
1,
};
args.phandle = handle;
args.prop = prop;
args.buf = buf;
args.len = len;
if (openfirmware(&args) == -1)
return -1;
return args.size;
}
#endif
int
OF_open(dname)
char *dname;
{
static struct {
char *name;
int nargs;
int nreturns;
char *dname;
int handle;
} args = {
"open",
1,
1,
};
#ifdef OFW_DEBUG
printf("OF_open(%s) -> ", dname);
#endif
args.dname = dname;
if (openfirmware(&args) == -1 ||
args.handle == 0) {
#ifdef OFW_DEBUG
printf("lose\n");
#endif
return -1;
}
#ifdef OFW_DEBUG
printf("%d\n", args.handle);
#endif
return args.handle;
}
void
OF_close(handle)
int handle;
{
static struct {
char *name;
int nargs;
int nreturns;
int handle;
} args = {
"close",
1,
0,
};
#ifdef OFW_DEBUG
printf("OF_close(%d)\n", handle);
#endif
args.handle = handle;
openfirmware(&args);
}
int
OF_write(handle, addr, len)
int handle;
void *addr;
int len;
{
static struct {
char *name;
int nargs;
int nreturns;
int ihandle;
void *addr;
int len;
int actual;
} args = {
"write",
3,
1,
};
#ifdef OFW_DEBUG
if (len != 1)
printf("OF_write(%d, %x, %x) -> ", handle, addr, len);
#endif
args.ihandle = handle;
args.addr = addr;
args.len = len;
if (openfirmware(&args) == -1) {
#ifdef OFW_DEBUG
printf("lose\n");
#endif
return -1;
}
#ifdef OFW_DEBUG
if (len != 1)
printf("%x\n", args.actual);
#endif
return args.actual;
}
int
OF_read(handle, addr, len)
int handle;
void *addr;
int len;
{
static struct {
char *name;
int nargs;
int nreturns;
int ihandle;
void *addr;
int len;
int actual;
} args = {
"read",
3,
1,
};
#ifdef OFW_DEBUG
if (len != 1)
printf("OF_read(%d, %x, %x) -> ", handle, addr, len);
#endif
args.ihandle = handle;
args.addr = addr;
args.len = len;
if (openfirmware(&args) == -1) {
#ifdef OFW_DEBUG
printf("lose\n");
#endif
return -1;
}
#ifdef OFW_DEBUG
if (len != 1)
printf("%x\n", args.actual);
#endif
return args.actual;
}
int
OF_seek(handle, pos)
int handle;
u_quad_t pos;
{
static struct {
char *name;
int nargs;
int nreturns;
int handle;
int poshi;
int poslo;
int status;
} args = {
"seek",
3,
1,
};
#ifdef OFW_DEBUG
printf("OF_seek(%d, %x, %x) -> ", handle, (int)(pos >> 32), (int)pos);
#endif
args.handle = handle;
args.poshi = (int)(pos >> 32);
args.poslo = (int)pos;
if (openfirmware(&args) == -1) {
#ifdef OFW_DEBUG
printf("lose\n");
#endif
return -1;
}
#ifdef OFW_DEBUG
printf("%d\n", args.status);
#endif
return args.status;
}
void *
OF_claim(virt, size, align)
void *virt;
u_int size;
u_int align;
{
static struct {
char *name;
int nargs;
int nreturns;
void *virt;
u_int size;
u_int align;
void *baseaddr;
} args = {
"claim",
3,
1,
};
#ifdef OFW_DEBUG
printf("OF_claim(%x, %x, %x) -> ", virt, size, align);
#endif
args.virt = virt;
args.size = size;
args.align = align;
if (openfirmware(&args) == -1) {
#ifdef OFW_DEBUG
printf("lose\n");
#endif
return (void *)-1;
}
#ifdef OFW_DEBUG
printf("%x\n", args.baseaddr);
#endif
return args.baseaddr;
}
void
OF_release(virt, size)
void *virt;
u_int size;
{
static struct {
char *name;
int nargs;
int nreturns;
void *virt;
u_int size;
} args = {
"release",
2,
0,
};
#ifdef OFW_DEBUG
printf("OF_release(%x, %x)\n", virt, size);
#endif
args.virt = virt;
args.size = size;
openfirmware(&args);
}
int
OF_milliseconds()
{
static struct {
char *name;
int nargs;
int nreturns;
int ms;
} args = {
"milliseconds",
0,
1,
};
openfirmware(&args);
return args.ms;
}
void
OF_chain(virt, size, entry, arg, len)
void *virt;
u_int size;
void (*entry)();
void *arg;
u_int len;
{
struct {
char *name;
int nargs;
int nreturns;
void *virt;
u_int size;
void (*entry)();
void *arg;
u_int len;
} args;
args.name = "chain";
args.nargs = 5;
args.nreturns = 0;
args.virt = virt;
args.size = size;
args.entry = entry;
args.arg = arg;
args.len = len;
#if 1
openfirmware(&args);
#else
entry(openfirmware_entry, arg, len);
#endif
}
static int stdin;
static int stdout;
static void
setup()
{
u_char buf[sizeof(int)];
int chosen;
if ((chosen = OF_finddevice("/chosen")) == -1)
OF_exit();
if (OF_getprop(chosen, "stdin", buf, sizeof(buf)) != sizeof(buf))
OF_exit();
stdin = of_decode_int(buf);
if (OF_getprop(chosen, "stdout", buf, sizeof(buf)) != sizeof(buf))
OF_exit();
stdout = of_decode_int(buf);
}
void
putchar(c)
int c;
{
char ch = c;
if (c == '\n')
putchar('\r');
OF_write(stdout, &ch, 1);
}
int
getchar()
{
unsigned char ch = '\0';
int l;
while ((l = OF_read(stdin, &ch, 1)) != 1)
if (l != -2 && l != 0)
return -1;
return ch;
}
| bsd-3-clause |
jinglinhu/cpp | backend/models/User.php | 3852 | <?php
namespace backend\models;
use Yii;
use yii\helpers\ArrayHelper;
use backend\models\Organization;
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
* @property string $password write-only password
*/
class User extends \common\models\User
{
public $password;
public $repassword;
private $_statusLabel;
/**
* @inheritdoc
*/
public function getStatusLabel()
{
if ($this->_statusLabel === null) {
$statuses = self::getArrayStatus();
$this->_statusLabel = $statuses[$this->status];
}
return $this->_statusLabel;
}
/**
* @inheritdoc
*/
public static function getArrayStatus()
{
return [
self::STATUS_ACTIVE => Yii::t('app', 'STATUS_ACTIVE'),
self::STATUS_INACTIVE => Yii::t('app', 'STATUS_INACTIVE'),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username','realname', 'email','oid'], 'required'],
[['password', 'repassword'], 'required', 'on' => ['admin-create']],
[['username', 'realname','position','mobile','email', 'password', 'repassword'], 'trim'],
[['password', 'repassword'], 'string', 'min' => 6, 'max' => 30],
// Unique
[['username', 'email'], 'unique'],
// Username
['username', 'match', 'pattern' => '/^[a-zA-Z0-9_-]+$/'],
['username', 'string', 'min' => 3, 'max' => 30],
// E-mail
['oid', 'integer', 'min' => 1],
['email', 'string', 'max' => 100],
['avatar_url', 'string', 'max' => 64],
[['realname','position','mobile'], 'string', 'max' => 20],
['mobile','match','pattern'=>'/^1[0-9]{10}$/'],
['email', 'email'],
// Repassword
['repassword', 'compare', 'compareAttribute' => 'password'],
//['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE]],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
return [
'admin-create' => ['username', 'email', 'password', 'repassword', 'status','avatar_url','oid','realname','position','mobile'],
'admin-update' => ['username', 'email', 'password', 'repassword', 'status','avatar_url','oid','realname','position','mobile']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
$labels = parent::attributeLabels();
return array_merge(
$labels,
[
'password' => Yii::t('app', 'Password'),
'repassword' => Yii::t('app', 'Repassword'),
'realname' => Yii::t('app', 'Realname'),
'position' => Yii::t('app', 'Position'),
'mobile' => Yii::t('app', 'Mobile'),
'oid' => Yii::t('app', 'Oid'),
]
);
}
public function getOrganization()
{
return $this->hasOne(Organization::className(), ['id' => 'oid']);
}
/**
* @inheritdoc
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord || (!$this->isNewRecord && $this->password)) {
$this->setPassword($this->password);
$this->generateAuthKey();
$this->generatePasswordResetToken();
}
return true;
}
return false;
}
}
| bsd-3-clause |
grigorisg9gr/menpo | menpo/shape/pointcloud.py | 48399 | import warnings
import numpy as np
import numbers
import collections
from warnings import warn
from scipy.sparse import csr_matrix
from scipy.spatial.distance import cdist
from menpo.transform import WithDims
from .base import Shape
def bounding_box(closest_to_origin, opposite_corner):
r"""
Return a bounding box from two corner points as a directed graph.
The the first point (0) should be nearest the origin.
In the case of an image, this ordering would appear as:
::
0<--3
| ^
| |
v |
1-->2
In the case of a pointcloud, the ordering will appear as:
::
3<--2
| ^
| |
v |
0-->1
Parameters
----------
closest_to_origin : (`float`, `float`)
Two floats representing the coordinates closest to the origin.
Represented by (0) in the graph above. For an image, this will
be the top left. For a pointcloud, this will be the bottom left.
opposite_corner : (`float`, `float`)
Two floats representing the coordinates opposite the corner closest
to the origin.
Represented by (2) in the graph above. For an image, this will
be the bottom right. For a pointcloud, this will be the top right.
Returns
-------
bounding_box : :map:`PointDirectedGraph`
The axis aligned bounding box from the two given corners.
"""
from .graph import PointDirectedGraph
if len(closest_to_origin) != 2 or len(opposite_corner) != 2:
raise ValueError('Only 2D bounding boxes can be created.')
adjacency_matrix = csr_matrix(([1] * 4, ([0, 1, 2, 3], [1, 2, 3, 0])),
shape=(4, 4))
box = np.array([closest_to_origin,
[opposite_corner[0], closest_to_origin[1]],
opposite_corner,
[closest_to_origin[0], opposite_corner[1]]], dtype=np.float)
return PointDirectedGraph(box, adjacency_matrix, copy=False)
def bounding_cuboid(near_closest_to_origin, far_opposite_corner):
r"""
Return a bounding cuboid from the near closest and far opposite
corners as a directed graph.
Parameters
----------
near_closest_to_origin : (`float`, `float`, `float`)
Three floats representing the coordinates of the near corner closest to
the origin.
far_opposite_corner : (`float`, `float`, `float`)
Three floats representing the coordinates of the far opposite corner
compared to near_closest_to_origin.
Returns
-------
bounding_box : :map:`PointDirectedGraph`
The axis aligned bounding cuboid from the two given corners.
"""
from .graph import PointDirectedGraph
if len(near_closest_to_origin) != 3 or len(far_opposite_corner) != 3:
raise ValueError('Only 3D bounding cuboids can be created.')
adjacency_matrix = csr_matrix(
([1] * 12,
([0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 0, 4, 5, 6, 7, 5, 6, 7, 4])), shape=(8, 8))
cuboid = np.array(
[near_closest_to_origin, [far_opposite_corner[0],
near_closest_to_origin[1],
near_closest_to_origin[2]],
[far_opposite_corner[0],
far_opposite_corner[1],
near_closest_to_origin[2]], [near_closest_to_origin[0],
far_opposite_corner[1],
near_closest_to_origin[2]],
[near_closest_to_origin[0],
near_closest_to_origin[1],
far_opposite_corner[2]], [far_opposite_corner[0],
near_closest_to_origin[1],
far_opposite_corner[2]],
far_opposite_corner, [near_closest_to_origin[0],
far_opposite_corner[1],
far_opposite_corner[2]]], dtype=np.float)
return PointDirectedGraph(cuboid, adjacency_matrix, copy=False)
class PointCloud(Shape):
r"""
An N-dimensional point cloud. This is internally represented as an `ndarray`
of shape ``(n_points, n_dims)``. This class is important for dealing
with complex functionality such as viewing and representing metadata such
as landmarks.
Currently only 2D and 3D pointclouds are viewable.
Parameters
----------
points : ``(n_points, n_dims)`` `ndarray`
The array representing the points.
copy : `bool`, optional
If ``False``, the points will not be copied on assignment. Note that
this will miss out on additional checks. Further note that we still
demand that the array is C-contiguous - if it isn't, a copy will be
generated anyway.
In general this should only be used if you know what you are doing.
"""
def __init__(self, points, copy=True):
super(PointCloud, self).__init__()
if not copy:
if not points.flags.c_contiguous:
warn('The copy flag was NOT honoured. A copy HAS been made. '
'Please ensure the data you pass is C-contiguous.')
points = np.array(points, copy=True, order='C')
else:
points = np.array(points, copy=True, order='C')
self.points = points
@classmethod
def init_2d_grid(cls, shape, spacing=None):
r"""
Create a pointcloud that exists on a regular 2D grid. The first
dimension is the number of rows in the grid and the second dimension
of the shape is the number of columns. ``spacing`` optionally allows
the definition of the distance between points (uniform over points).
The spacing may be different for rows and columns.
Parameters
----------
shape : `tuple` of 2 `int`
The size of the grid to create, this defines the number of points
across each dimension in the grid. The first element is the number
of rows and the second is the number of columns.
spacing : `int` or `tuple` of 2 `int`, optional
The spacing between points. If a single `int` is provided, this
is applied uniformly across each dimension. If a `tuple` is
provided, the spacing is applied non-uniformly as defined e.g.
``(2, 3)`` gives a spacing of 2 for the rows and 3 for the
columns.
Returns
-------
shape_cls : `type(cls)`
A PointCloud or subclass arranged in a grid.
"""
if len(shape) != 2:
raise ValueError('shape must be 2D.')
grid = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]),
indexing='ij')
points = np.require(np.concatenate(grid).reshape([2, -1]).T,
dtype=np.float64, requirements=['C'])
if spacing is not None:
if not (isinstance(spacing, numbers.Number) or
isinstance(spacing, collections.Sequence)):
raise ValueError('spacing must be either a single number '
'to be applied over each dimension, or a 2D '
'sequence of numbers.')
if isinstance(spacing, collections.Sequence) and len(spacing) != 2:
raise ValueError('spacing must be 2D.')
points *= np.asarray(spacing, dtype=np.float64)
return cls(points, copy=False)
@classmethod
def init_from_depth_image(cls, depth_image):
r"""
Return a 3D point cloud from the given depth image. The depth image
is assumed to represent height/depth values and the XY coordinates
are assumed to unit spaced and represent image coordinates. This is
particularly useful for visualising depth values that have been
recovered from images.
Parameters
----------
depth_image : :map:`Image` or subclass
A single channel image that contains depth values - as commonly
returned by RGBD cameras, for example.
Returns
-------
depth_cloud : ``type(cls)``
A new 3D PointCloud with unit XY coordinates and the given depth
values as Z coordinates.
"""
from menpo.image import MaskedImage
new_pcloud = cls.init_2d_grid(depth_image.shape)
if isinstance(depth_image, MaskedImage):
new_pcloud = new_pcloud.from_mask(depth_image.mask.as_vector())
return cls(np.hstack([new_pcloud.points,
depth_image.as_vector(keep_channels=True).T]),
copy=False)
def with_dims(self, dims):
r"""
Return a copy of this shape with only particular dimensions retained.
Parameters
----------
dims : valid numpy array slice
The slice that will be used on the dimensionality axis of the shape
under transform. For example, to go from a 3D shape to a 2D one,
[0, 1] could be provided or np.array([True, True, False]).
Returns
-------
copy of self, with only the requested dims
"""
return WithDims(dims).apply(self)
@property
def lms(self):
"""Deprecated.
Maintained for compatibility, will be removed in a future version.
Returns a copy of this object, which previously would have held
the 'underlying' :map:`PointCloud` subclass.
:type: self
"""
from menpo.base import MenpoDeprecationWarning
warnings.warn('The .lms property is deprecated. LandmarkGroups are '
'now shapes themselves - so you can use them directly '
'anywhere you previously used .lms.'
'Simply remove ".lms" from your code and things '
'will work as expected (and this warning will go away)',
MenpoDeprecationWarning)
return self.copy()
@property
def n_points(self):
r"""
The number of points in the pointcloud.
:type: `int`
"""
return self.points.shape[0]
@property
def n_dims(self):
r"""
The number of dimensions in the pointcloud.
:type: `int`
"""
return self.points.shape[1]
def h_points(self):
r"""
Convert poincloud to a homogeneous array: ``(n_dims + 1, n_points)``
:type: ``type(self)``
"""
return np.concatenate((self.points.T,
np.ones(self.n_points,
dtype=self.points.dtype)[None, :]))
def centre(self):
r"""
The mean of all the points in this PointCloud (centre of mass).
Returns
-------
centre : ``(n_dims)`` `ndarray`
The mean of this PointCloud's points.
"""
return np.mean(self.points, axis=0)
def centre_of_bounds(self):
r"""
The centre of the absolute bounds of this PointCloud. Contrast with
:meth:`centre`, which is the mean point position.
Returns
-------
centre : ``n_dims`` `ndarray`
The centre of the bounds of this PointCloud.
"""
min_b, max_b = self.bounds()
return (min_b + max_b) / 2.0
def _as_vector(self):
r"""
Returns a flattened representation of the pointcloud.
Note that the flattened representation is of the form
``[x0, y0, x1, y1, ....., xn, yn]`` for 2D.
Returns
-------
flattened : ``(n_points,)`` `ndarray`
The flattened points.
"""
return self.points.ravel()
def tojson(self):
r"""
Convert this :map:`PointCloud` to a dictionary representation suitable
for inclusion in the LJSON landmark format.
Returns
-------
json : `dict`
Dictionary with ``points`` keys.
"""
return {
'labels': [],
'landmarks': {
'points': self.points.tolist()
}
}
def _from_vector_inplace(self, vector):
r"""
Updates the points of this PointCloud in-place with the reshaped points
from the provided vector. Note that the vector should have the form
``[x0, y0, x1, y1, ....., xn, yn]`` for 2D.
Parameters
----------
vector : ``(n_points,)`` `ndarray`
The vector from which to create the points' array.
"""
self.points = vector.reshape([-1, self.n_dims])
def __str__(self):
return '{}: n_points: {}, n_dims: {}'.format(type(self).__name__,
self.n_points,
self.n_dims)
def bounds(self, boundary=0):
r"""
The minimum to maximum extent of the PointCloud. An optional boundary
argument can be provided to expand the bounds by a constant margin.
Parameters
----------
boundary : `float`
A optional padding distance that is added to the bounds. Default
is ``0``, meaning the max/min of tightest possible containing
square/cube/hypercube is returned.
Returns
-------
min_b : ``(n_dims,)`` `ndarray`
The minimum extent of the :map:`PointCloud` and boundary along
each dimension
max_b : ``(n_dims,)`` `ndarray`
The maximum extent of the :map:`PointCloud` and boundary along
each dimension
"""
min_b = np.min(self.points, axis=0) - boundary
max_b = np.max(self.points, axis=0) + boundary
return min_b, max_b
def range(self, boundary=0):
r"""
The range of the extent of the PointCloud.
Parameters
----------
boundary : `float`
A optional padding distance that is used to extend the bounds
from which the range is computed. Default is ``0``, no extension
is performed.
Returns
-------
range : ``(n_dims,)`` `ndarray`
The range of the :map:`PointCloud` extent in each dimension.
"""
min_b, max_b = self.bounds(boundary)
return max_b - min_b
def bounding_box(self):
r"""
Return a bounding box from two corner points as a directed graph.
In the case of a 2D pointcloud, first point (0) should be nearest the
origin. In the case of an image, this ordering would appear as:
::
0<--3
| ^
| |
v |
1-->2
In the case of a pointcloud, the ordering will appear as:
::
3<--2
| ^
| |
v |
0-->1
In the case of a 3D pointcloud, the first point (0) should be the
near closest to the origin and the second point is the far opposite
corner.
Returns
-------
bounding_box : :map:`PointDirectedGraph`
The axis aligned bounding box of the PointCloud.
"""
if self.n_dims != 2 and self.n_dims != 3:
raise ValueError('Bounding boxes are only supported for 2D or 3D '
'pointclouds.')
min_p, max_p = self.bounds()
if self.n_dims == 2:
return bounding_box(min_p, max_p)
elif self.n_dims == 3:
return bounding_cuboid(min_p, max_p)
def _view_2d(self, figure_id=None, new_figure=False, image_view=True,
render_markers=True, marker_style='o', marker_size=5,
marker_face_colour='r', marker_edge_colour='k',
marker_edge_width=1., render_numbering=False,
numbers_horizontal_align='center',
numbers_vertical_align='bottom',
numbers_font_name='sans-serif', numbers_font_size=10,
numbers_font_style='normal', numbers_font_weight='normal',
numbers_font_colour='k', render_axes=True,
axes_font_name='sans-serif', axes_font_size=10,
axes_font_style='normal', axes_font_weight='normal',
axes_x_limits=None, axes_y_limits=None, axes_x_ticks=None,
axes_y_ticks=None, figure_size=(10, 8), label=None, **kwargs):
r"""
Visualization of the PointCloud in 2D.
Returns
-------
figure_id : `object`, optional
The id of the figure to be used.
new_figure : `bool`, optional
If ``True``, a new figure is created.
image_view : `bool`, optional
If ``True`` the PointCloud will be viewed as if it is in the image
coordinate system.
render_markers : `bool`, optional
If ``True``, the markers will be rendered.
marker_style : See Below, optional
The style of the markers. Example options ::
{., ,, o, v, ^, <, >, +, x, D, d, s, p, *, h, H, 1, 2, 3, 4, 8}
marker_size : `int`, optional
The size of the markers in points.
marker_face_colour : See Below, optional
The face (filling) colour of the markers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_colour : See Below, optional
The edge colour of the markers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_width : `float`, optional
The width of the markers' edge.
render_numbering : `bool`, optional
If ``True``, the landmarks will be numbered.
numbers_horizontal_align : ``{center, right, left}``, optional
The horizontal alignment of the numbers' texts.
numbers_vertical_align : ``{center, top, bottom, baseline}``, optional
The vertical alignment of the numbers' texts.
numbers_font_name : See Below, optional
The font of the numbers. Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
numbers_font_size : `int`, optional
The font size of the numbers.
numbers_font_style : ``{normal, italic, oblique}``, optional
The font style of the numbers.
numbers_font_weight : See Below, optional
The font weight of the numbers.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold, demibold, demi, bold, heavy, extra bold, black}
numbers_font_colour : See Below, optional
The font colour of the numbers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
render_axes : `bool`, optional
If ``True``, the axes will be rendered.
axes_font_name : See Below, optional
The font of the axes.
Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
axes_font_size : `int`, optional
The font size of the axes.
axes_font_style : {``normal``, ``italic``, ``oblique``}, optional
The font style of the axes.
axes_font_weight : See Below, optional
The font weight of the axes.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold, demibold, demi, bold, heavy, extra bold, black}
axes_x_limits : `float` or (`float`, `float`) or ``None``, optional
The limits of the x axis. If `float`, then it sets padding on the
right and left of the PointCloud as a percentage of the PointCloud's
width. If `tuple` or `list`, then it defines the axis limits. If
``None``, then the limits are set automatically.
axes_y_limits : (`float`, `float`) `tuple` or ``None``, optional
The limits of the y axis. If `float`, then it sets padding on the
top and bottom of the PointCloud as a percentage of the PointCloud's
height. If `tuple` or `list`, then it defines the axis limits. If
``None``, then the limits are set automatically.
axes_x_ticks : `list` or `tuple` or ``None``, optional
The ticks of the x axis.
axes_y_ticks : `list` or `tuple` or ``None``, optional
The ticks of the y axis.
figure_size : (`float`, `float`) `tuple` or ``None``, optional
The size of the figure in inches.
label : `str`, optional
The name entry in case of a legend.
Returns
-------
viewer : :map:`PointGraphViewer2d`
The viewer object.
"""
from menpo.visualize.base import PointGraphViewer2d
adjacency_array = np.empty(0)
renderer = PointGraphViewer2d(figure_id, new_figure,
self.points, adjacency_array)
renderer.render(
image_view=image_view, render_lines=False, line_colour='b',
line_style='-', line_width=1., render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_face_colour=marker_face_colour,
marker_edge_colour=marker_edge_colour,
marker_edge_width=marker_edge_width,
render_numbering=render_numbering,
numbers_horizontal_align=numbers_horizontal_align,
numbers_vertical_align=numbers_vertical_align,
numbers_font_name=numbers_font_name,
numbers_font_size=numbers_font_size,
numbers_font_style=numbers_font_style,
numbers_font_weight=numbers_font_weight,
numbers_font_colour=numbers_font_colour, render_axes=render_axes,
axes_font_name=axes_font_name, axes_font_size=axes_font_size,
axes_font_style=axes_font_style, axes_font_weight=axes_font_weight,
axes_x_limits=axes_x_limits, axes_y_limits=axes_y_limits,
axes_x_ticks=axes_x_ticks, axes_y_ticks=axes_y_ticks,
figure_size=figure_size, label=label)
return renderer
def _view_landmarks_2d(self, group=None, with_labels=None,
without_labels=None, figure_id=None,
new_figure=False, image_view=True, render_lines=True,
line_colour=None, line_style='-', line_width=1,
render_markers=True, marker_style='o',
marker_size=5, marker_face_colour=None,
marker_edge_colour=None, marker_edge_width=1.,
render_numbering=False,
numbers_horizontal_align='center',
numbers_vertical_align='bottom',
numbers_font_name='sans-serif', numbers_font_size=10,
numbers_font_style='normal',
numbers_font_weight='normal',
numbers_font_colour='k', render_legend=False,
legend_title='', legend_font_name='sans-serif',
legend_font_style='normal', legend_font_size=10,
legend_font_weight='normal',
legend_marker_scale=None, legend_location=2,
legend_bbox_to_anchor=(1.05, 1.),
legend_border_axes_pad=None, legend_n_columns=1,
legend_horizontal_spacing=None,
legend_vertical_spacing=None, legend_border=True,
legend_border_padding=None, legend_shadow=False,
legend_rounded_corners=False, render_axes=False,
axes_font_name='sans-serif', axes_font_size=10,
axes_font_style='normal', axes_font_weight='normal',
axes_x_limits=None, axes_y_limits=None,
axes_x_ticks=None, axes_y_ticks=None,
figure_size=(10, 8)):
"""
Visualize the landmarks. This method will appear on the Image as
``view_landmarks`` if the Image is 2D.
Parameters
----------
group : `str` or``None`` optional
The landmark group to be visualized. If ``None`` and there are more
than one landmark groups, an error is raised.
with_labels : ``None`` or `str` or `list` of `str`, optional
If not ``None``, only show the given label(s). Should **not** be
used with the ``without_labels`` kwarg.
without_labels : ``None`` or `str` or `list` of `str`, optional
If not ``None``, show all except the given label(s). Should **not**
be used with the ``with_labels`` kwarg.
figure_id : `object`, optional
The id of the figure to be used.
new_figure : `bool`, optional
If ``True``, a new figure is created.
image_view : `bool`, optional
If ``True`` the PointCloud will be viewed as if it is in the image
coordinate system.
render_lines : `bool`, optional
If ``True``, the edges will be rendered.
line_colour : See Below, optional
The colour of the lines.
Example options::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
line_style : ``{-, --, -., :}``, optional
The style of the lines.
line_width : `float`, optional
The width of the lines.
render_markers : `bool`, optional
If ``True``, the markers will be rendered.
marker_style : See Below, optional
The style of the markers. Example options ::
{., ,, o, v, ^, <, >, +, x, D, d, s, p, *, h, H, 1, 2, 3, 4, 8}
marker_size : `int`, optional
The size of the markers in points.
marker_face_colour : See Below, optional
The face (filling) colour of the markers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_colour : See Below, optional
The edge colour of the markers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_width : `float`, optional
The width of the markers' edge.
render_numbering : `bool`, optional
If ``True``, the landmarks will be numbered.
numbers_horizontal_align : ``{center, right, left}``, optional
The horizontal alignment of the numbers' texts.
numbers_vertical_align : ``{center, top, bottom, baseline}``, optional
The vertical alignment of the numbers' texts.
numbers_font_name : See Below, optional
The font of the numbers. Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
numbers_font_size : `int`, optional
The font size of the numbers.
numbers_font_style : ``{normal, italic, oblique}``, optional
The font style of the numbers.
numbers_font_weight : See Below, optional
The font weight of the numbers.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold, demibold, demi, bold, heavy, extra bold, black}
numbers_font_colour : See Below, optional
The font colour of the numbers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
render_legend : `bool`, optional
If ``True``, the legend will be rendered.
legend_title : `str`, optional
The title of the legend.
legend_font_name : See below, optional
The font of the legend. Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
legend_font_style : ``{normal, italic, oblique}``, optional
The font style of the legend.
legend_font_size : `int`, optional
The font size of the legend.
legend_font_weight : See Below, optional
The font weight of the legend.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold, demibold, demi, bold, heavy, extra bold, black}
legend_marker_scale : `float`, optional
The relative size of the legend markers with respect to the original
legend_location : `int`, optional
The location of the legend. The predefined values are:
=============== ==
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== ==
legend_bbox_to_anchor : (`float`, `float`) `tuple`, optional
The bbox that the legend will be anchored.
legend_border_axes_pad : `float`, optional
The pad between the axes and legend border.
legend_n_columns : `int`, optional
The number of the legend's columns.
legend_horizontal_spacing : `float`, optional
The spacing between the columns.
legend_vertical_spacing : `float`, optional
The vertical space between the legend entries.
legend_border : `bool`, optional
If ``True``, a frame will be drawn around the legend.
legend_border_padding : `float`, optional
The fractional whitespace inside the legend border.
legend_shadow : `bool`, optional
If ``True``, a shadow will be drawn behind legend.
legend_rounded_corners : `bool`, optional
If ``True``, the frame's corners will be rounded (fancybox).
render_axes : `bool`, optional
If ``True``, the axes will be rendered.
axes_font_name : See Below, optional
The font of the axes. Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
axes_font_size : `int`, optional
The font size of the axes.
axes_font_style : ``{normal, italic, oblique}``, optional
The font style of the axes.
axes_font_weight : See Below, optional
The font weight of the axes.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold,demibold, demi, bold, heavy, extra bold, black}
axes_x_limits : `float` or (`float`, `float`) or ``None``, optional
The limits of the x axis. If `float`, then it sets padding on the
right and left of the PointCloud as a percentage of the PointCloud's
width. If `tuple` or `list`, then it defines the axis limits. If
``None``, then the limits are set automatically.
axes_y_limits : (`float`, `float`) `tuple` or ``None``, optional
The limits of the y axis. If `float`, then it sets padding on the
top and bottom of the PointCloud as a percentage of the PointCloud's
height. If `tuple` or `list`, then it defines the axis limits. If
``None``, then the limits are set automatically.
axes_x_ticks : `list` or `tuple` or ``None``, optional
The ticks of the x axis.
axes_y_ticks : `list` or `tuple` or ``None``, optional
The ticks of the y axis.
figure_size : (`float`, `float`) `tuple` or ``None`` optional
The size of the figure in inches.
Raises
------
ValueError
If both ``with_labels`` and ``without_labels`` are passed.
ValueError
If the landmark manager doesn't contain the provided group label.
"""
if not self.has_landmarks:
raise ValueError('PointCloud does not have landmarks attached, '
'unable to view landmarks.')
self_view = self.view(figure_id=figure_id, new_figure=new_figure,
image_view=image_view, figure_size=figure_size)
landmark_view = self.landmarks[group].view(
with_labels=with_labels, without_labels=without_labels,
figure_id=self_view.figure_id, new_figure=False,
image_view=image_view, render_lines=render_lines,
line_colour=line_colour, line_style=line_style,
line_width=line_width, render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_face_colour=marker_face_colour,
marker_edge_colour=marker_edge_colour,
marker_edge_width=marker_edge_width,
render_numbering=render_numbering,
numbers_horizontal_align=numbers_horizontal_align,
numbers_vertical_align=numbers_vertical_align,
numbers_font_name=numbers_font_name,
numbers_font_size=numbers_font_size,
numbers_font_style=numbers_font_style,
numbers_font_weight=numbers_font_weight,
numbers_font_colour=numbers_font_colour,
render_legend=render_legend, legend_title=legend_title,
legend_font_name=legend_font_name,
legend_font_style=legend_font_style,
legend_font_size=legend_font_size,
legend_font_weight=legend_font_weight,
legend_marker_scale=legend_marker_scale,
legend_location=legend_location,
legend_bbox_to_anchor=legend_bbox_to_anchor,
legend_border_axes_pad=legend_border_axes_pad,
legend_n_columns=legend_n_columns,
legend_horizontal_spacing=legend_horizontal_spacing,
legend_vertical_spacing=legend_vertical_spacing,
legend_border=legend_border,
legend_border_padding=legend_border_padding,
legend_shadow=legend_shadow,
legend_rounded_corners=legend_rounded_corners,
render_axes=render_axes, axes_font_name=axes_font_name,
axes_font_size=axes_font_size, axes_font_style=axes_font_style,
axes_font_weight=axes_font_weight, axes_x_limits=axes_x_limits,
axes_y_limits=axes_y_limits, axes_x_ticks=axes_x_ticks,
axes_y_ticks=axes_y_ticks, figure_size=figure_size)
return landmark_view
def _view_3d(self, figure_id=None, new_figure=True, render_markers=True,
marker_style='sphere', marker_size=None, marker_colour='r',
marker_resolution=8, step=None, alpha=1.0,
render_numbering=False, numbers_colour='k', numbers_size=None,
**kwargs):
r"""
Visualization of the PointCloud in 3D.
Parameters
----------
figure_id : `object`, optional
The id of the figure to be used.
new_figure : `bool`, optional
If ``True``, a new figure is created.
render_markers : `bool`, optional
If ``True``, the markers will be rendered.
marker_style : `str`, optional
The style of the markers.
Example options ::
{2darrow, 2dcircle, 2dcross, 2ddash, 2ddiamond, 2dhooked_arrow,
2dsquare, 2dthick_arrow, 2dthick_cross, 2dtriangle, 2dvertex,
arrow, axes, cone, cube, cylinder, point, sphere}
marker_size : `float` or ``None``, optional
The size of the markers. This size can be seen as a scale factor
applied to the size markers, which is by default calculated from
the inter-marker spacing. If ``None``, then an optimal marker size
value will be set automatically.
marker_colour : See Below, optional
The colour of the markers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_resolution : `int`, optional
The resolution of the markers. For spheres, for instance, this is
the number of divisions along theta and phi.
step : `int` or ``None``, optional
If `int`, then one every `step` vertexes will be rendered.
If ``None``, then all vertexes will be rendered.
alpha : `float`, optional
Defines the transparency (opacity) of the object.
render_numbering : `bool`, optional
If ``True``, the points will be numbered.
numbers_colour : See Below, optional
The colour of the numbers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
numbers_size : `float` or ``None``, optional
The size of the numbers. This size can be seen as a scale factor
applied to the numbers, which is by default calculated from
the inter-marker spacing. If ``None``, then an optimal numbers size
value will be set automatically.
Returns
-------
renderer : `menpo3d.visualize.PointGraphViewer3d`
The Menpo3D rendering object.
"""
try:
from menpo3d.visualize import PointGraphViewer3d
edges = np.empty(0)
renderer = PointGraphViewer3d(figure_id, new_figure,
self.points, edges)
renderer.render(
render_lines=False, render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_colour=marker_colour, marker_resolution=marker_resolution,
step=step, alpha=alpha, render_numbering=render_numbering,
numbers_colour=numbers_colour, numbers_size=numbers_size)
return renderer
except ImportError:
from menpo.visualize import Menpo3dMissingError
raise Menpo3dMissingError()
def _view_landmarks_3d(self, group=None, with_labels=None,
without_labels=None, figure_id=None,
new_figure=True, render_lines=True,
line_colour=None, line_width=4, render_markers=True,
marker_style='sphere', marker_size=None,
marker_colour=None, marker_resolution=8,
step=None, alpha=1.0, render_numbering=False,
numbers_colour='k', numbers_size=None):
r"""
Visualization of the PointCloud landmarks in 3D.
Parameters
----------
with_labels : ``None`` or `str` or `list` of `str`, optional
If not ``None``, only show the given label(s). Should **not** be
used with the ``without_labels`` kwarg.
without_labels : ``None`` or `str` or `list` of `str`, optional
If not ``None``, show all except the given label(s). Should **not**
be used with the ``with_labels`` kwarg.
group : `str` or `None`, optional
The landmark group to be visualized. If ``None`` and there are more
than one landmark groups, an error is raised.
figure_id : `object`, optional
The id of the figure to be used.
new_figure : `bool`, optional
If ``True``, a new figure is created.
render_lines : `bool`, optional
If ``True``, then the lines will be rendered.
line_colour : See Below, optional
The colour of the lines. If ``None``, a different colour will be
automatically selected for each label.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
or
None
line_width : `float`, optional
The width of the lines.
render_markers : `bool`, optional
If ``True``, then the markers will be rendered.
marker_style : `str`, optional
The style of the markers.
Example options ::
{2darrow, 2dcircle, 2dcross, 2ddash, 2ddiamond, 2dhooked_arrow,
2dsquare, 2dthick_arrow, 2dthick_cross, 2dtriangle, 2dvertex,
arrow, axes, cone, cube, cylinder, point, sphere}
marker_size : `float` or ``None``, optional
The size of the markers. This size can be seen as a scale factor
applied to the size markers, which is by default calculated from
the inter-marker spacing. If ``None``, then an optimal marker size
value will be set automatically.
marker_colour : See Below, optional
The colour of the markers. If ``None``, a different colour will be
automatically selected for each label.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
or
None
marker_resolution : `int`, optional
The resolution of the markers. For spheres, for instance, this is
the number of divisions along theta and phi.
step : `int` or ``None``, optional
If `int`, then one every `step` vertexes will be rendered.
If ``None``, then all vertexes will be rendered.
alpha : `float`, optional
Defines the transparency (opacity) of the object.
render_numbering : `bool`, optional
If ``True``, the points will be numbered.
numbers_colour : See Below, optional
The colour of the numbers.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
numbers_size : `float` or ``None``, optional
The size of the numbers. This size can be seen as a scale factor
applied to the numbers, which is by default calculated from
the inter-marker spacing. If ``None``, then an optimal numbers size
value will be set automatically.
Returns
-------
renderer : `menpo3d.visualize.LandmarkViewer3d`
The Menpo3D rendering object.
"""
if not self.has_landmarks:
raise ValueError('PointCloud does not have landmarks attached, '
'unable to view landmarks.')
self_view = self.view(figure_id=figure_id, new_figure=new_figure)
landmark_view = self.landmarks[group].view(
with_labels=with_labels, without_labels=without_labels,
figure_id=self_view.figure_id, new_figure=False,
render_lines=render_lines, line_colour=line_colour,
line_width=line_width, render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_colour=marker_colour, marker_resolution=marker_resolution,
step=step, alpha=alpha, render_numbering=render_numbering,
numbers_colour=numbers_colour, numbers_size=numbers_size)
return landmark_view
def view_widget(self, browser_style='buttons', figure_size=(10, 8),
style='coloured'):
r"""
Visualization of the PointCloud using an interactive widget.
Parameters
----------
browser_style : {``'buttons'``, ``'slider'``}, optional
It defines whether the selector of the objects will have the form of
plus/minus buttons or a slider.
figure_size : (`int`, `int`), optional
The initial size of the rendered figure.
style : {``'coloured'``, ``'minimal'``}, optional
If ``'coloured'``, then the style of the widget will be coloured. If
``minimal``, then the style is simple using black and white colours.
"""
try:
from menpowidgets import visualize_pointclouds
visualize_pointclouds(self, figure_size=figure_size, style=style,
browser_style=browser_style)
except ImportError:
from menpo.visualize.base import MenpowidgetsMissingError
raise MenpowidgetsMissingError()
def _transform_self_inplace(self, transform):
self.points = transform(self.points)
return self
def distance_to(self, pointcloud, **kwargs):
r"""
Returns a distance matrix between this PointCloud and another.
By default the Euclidean distance is calculated - see
`scipy.spatial.distance.cdist` for valid kwargs to change the metric
and other properties.
Parameters
----------
pointcloud : :map:`PointCloud`
The second pointcloud to compute distances between. This must be
of the same dimension as this PointCloud.
Returns
-------
distance_matrix: ``(n_points, n_points)`` `ndarray`
The symmetric pairwise distance matrix between the two PointClouds
s.t. ``distance_matrix[i, j]`` is the distance between the i'th
point of this PointCloud and the j'th point of the input
PointCloud.
"""
if self.n_dims != pointcloud.n_dims:
raise ValueError("The two PointClouds must be of the same "
"dimensionality.")
return cdist(self.points, pointcloud.points, **kwargs)
def norm(self, **kwargs):
r"""
Returns the norm of this PointCloud. This is a translation and
rotation invariant measure of the point cloud's intrinsic size - in
other words, it is always taken around the point cloud's centre.
By default, the Frobenius norm is taken, but this can be changed by
setting kwargs - see ``numpy.linalg.norm`` for valid options.
Returns
-------
norm : `float`
The norm of this :map:`PointCloud`
"""
return np.linalg.norm(self.points - self.centre(), **kwargs)
def from_mask(self, mask):
"""
A 1D boolean array with the same number of elements as the number of
points in the PointCloud. This is then broadcast across the dimensions
of the PointCloud and returns a new PointCloud containing only those
points that were ``True`` in the mask.
Parameters
----------
mask : ``(n_points,)`` `ndarray`
1D array of booleans
Returns
-------
pointcloud : :map:`PointCloud`
A new pointcloud that has been masked.
Raises
------
ValueError
Mask must have same number of points as pointcloud.
"""
if mask.shape[0] != self.n_points:
raise ValueError('Mask must be a 1D boolean array of the same '
'number of entries as points in this PointCloud.')
pc = self.copy()
pc.points = pc.points[mask, :]
return pc
def constrain_to_bounds(self, bounds):
r"""
Returns a copy of this PointCloud, constrained to lie exactly within
the given bounds. Any points outside the bounds will be 'snapped'
to lie *exactly* on the boundary.
Parameters
----------
bounds : ``(n_dims, n_dims)`` tuple of scalars
The bounds to constrain this pointcloud within.
Returns
-------
constrained : :map:`PointCloud`
The constrained pointcloud.
"""
pc = self.copy()
for k in range(pc.n_dims):
tmp = pc.points[:, k]
tmp[tmp < bounds[0][k]] = bounds[0][k]
tmp[tmp > bounds[1][k]] = bounds[1][k]
pc.points[:, k] = tmp
return pc
| bsd-3-clause |
rwatson/chromium-capsicum | chrome/browser/debugger/devtools_remote.h | 1333 | // Copyright (c) 2009 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 CHROME_BROWSER_DEBUGGER_DEVTOOLS_REMOTE_H_
#define CHROME_BROWSER_DEBUGGER_DEVTOOLS_REMOTE_H_
#include "base/basictypes.h"
#include "base/ref_counted.h"
class DevToolsRemoteMessage;
// This interface should be implemented by a class that wants to handle
// DevToolsRemoteMessages dispatched by some entity. It must extend
class DevToolsRemoteListener
: public base::RefCountedThreadSafe<DevToolsRemoteListener> {
public:
DevToolsRemoteListener() {}
virtual void HandleMessage(const DevToolsRemoteMessage& message) = 0;
// This method is invoked on the UI thread whenever the debugger connection
// has been lost.
virtual void OnConnectionLost() = 0;
protected:
friend class base::RefCountedThreadSafe<DevToolsRemoteListener>;
virtual ~DevToolsRemoteListener() {}
private:
DISALLOW_COPY_AND_ASSIGN(DevToolsRemoteListener);
};
// Interface exposed by DevToolsProtocolHandler to receive reply messages
// from registered tools.
class OutboundSocketDelegate {
public:
virtual ~OutboundSocketDelegate() {}
virtual void Send(const DevToolsRemoteMessage& message) = 0;
};
#endif // CHROME_BROWSER_DEBUGGER_DEVTOOLS_REMOTE_H_
| bsd-3-clause |
jonom/silverstripe-cms | client/lang/el.js | 1533 | // This file was generated by silverstripe/cow from client/lang/src/el.js.
// See https://github.com/tractorcow/cow for details
if (typeof(ss) === 'undefined' || typeof(ss.i18n) === 'undefined') {
if (typeof(console) !== 'undefined') { // eslint-disable-line no-console
console.error('Class ss.i18n not defined'); // eslint-disable-line no-console
}
} else {
ss.i18n.addDictionary('el', {
"CMS.ALERTCLASSNAME": "The page type will be updated after the page is saved",
"CMS.AddSubPage": "Προσθήκη νέας σελίδας εδώ",
"CMS.ConfirmRestoreFromLive": "Are you sure you want to revert draft to when the page was last published?",
"CMS.Duplicate": "Duplicate",
"CMS.EditPage": "Edit",
"CMS.ONLYSELECTTWO": "You can only compare two versions at this time.",
"CMS.Restore": "Are you sure you want to restore this page from archive?",
"CMS.RestoreToRoot": "Are you sure you want to restore this page from archive?\n\nBecause the parent page is not available this will be restored to the top level.",
"CMS.RollbackToVersion": "Do you really want to roll back to version #%s of this page?",
"CMS.ShowAsList": "Show children as list",
"CMS.ThisPageAndSubpages": "This page and subpages",
"CMS.ThisPageOnly": "Μόνο αυτή η σελίδα",
"CMS.Unpublish": "Are you sure you want to remove your page from the published site?\n\nThis page will still be available in the sitetree as draft.",
"CMS.UpdateURL": "Update URL",
"CMS.ViewPage": "View"
});
} | bsd-3-clause |
bastings/neuralmonkey | neuralmonkey/readers/string_vector_reader.py | 1449 | from typing import List, Iterable, Type
import gzip
import numpy as np
def get_string_vector_reader(dtype: Type = np.float32, columns: int = None):
"""Get a reader for vectors encoded as whitespace-separated numbers"""
def process_line(line: str, lineno: int, path: str) -> np.ndarray:
numbers = line.strip().split()
if columns is not None and len(numbers) != columns:
raise ValueError("Wrong number of columns ({}) on line {}, file {}"
.format(len(numbers), lineno, path))
return np.array(numbers, dtype=dtype)
def reader(files: List[str])-> Iterable[List[np.ndarray]]:
for path in files:
current_line = 0
if path.endswith(".gz"):
with gzip.open(path, 'r') as f_data:
for line in f_data:
current_line += 1
if line.strip():
yield process_line(str(line), current_line, path)
else:
with open(path) as f_data:
for line in f_data:
current_line += 1
if line.strip():
yield process_line(line, current_line, path)
return reader
# pylint: disable=invalid-name
FloatVectorReader = get_string_vector_reader(np.float32)
IntVectorReader = get_string_vector_reader(np.int32)
# pylint: enable=invalid-name
| bsd-3-clause |
pbrunet/pythran | pythran/pythonic/__builtin__/str/strip.hpp | 744 | #ifndef PYTHONIC_BUILTIN_STR_STRIP_HPP
#define PYTHONIC_BUILTIN_STR_STRIP_HPP
#include "pythonic/include/__builtin__/str/strip.hpp"
#include "pythonic/types/str.hpp"
#include "pythonic/utils/functor.hpp"
namespace pythonic
{
namespace __builtin__
{
namespace str
{
types::str strip(types::str const &self, types::str const &to_del)
{
if (not self)
return self;
auto first = self.find_first_not_of(to_del);
if (first == -1)
return types::str();
else
return types::str(self.begin() + first,
self.begin() + self.find_last_not_of(to_del) + 1);
}
DEFINE_FUNCTOR(pythonic::__builtin__::str, strip);
}
}
}
#endif
| bsd-3-clause |
avoropay/CurrencyRates | public/webstat/awstats.zend.pilipok.zp.ua.urlentry.012017.html | 5731 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta name="generator" content="AWStats 7.0 (build 1.971) from config file awstats.zend.pilipok.zp.ua.conf (http://awstats.sourceforge.net)">
<meta name="robots" content="noindex,nofollow">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="description" content="Awstats - Advanced Web Statistics for zend.pilipok.zp.ua (2017-01) - urlentry">
<title>Statistics for zend.pilipok.zp.ua (2017-01) - urlentry</title>
<style type="text/css">
body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; }
.aws_bodyl { }
.aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; }
.aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; }
.aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; }
.aws_data {
background-color: #FFFFFF;
border-top-width: 1px;
border-left-width: 0px;
border-right-width: 0px;
border-bottom-width: 0px;
}
.aws_formfield { font: 13px verdana, arial, helvetica; }
.aws_button {
font-family: arial,verdana,helvetica, sans-serif;
font-size: 12px;
border: 1px solid #ccd7e0;
background-image : url(/awstatsicons/other/button.gif);
}
th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; }
th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; }
td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; }
td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;}
td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; }
b { font-weight: bold; }
a { font: 11px verdana, arial, helvetica, sans-serif; }
a:link { color: #0011BB; text-decoration: none; }
a:visited { color: #0011BB; text-decoration: none; }
a:hover { color: #605040; text-decoration: underline; }
.currentday { font-weight: bold; }
</style>
</head>
<body style="margin-top: 0px">
<a name="top"></a>
<a name="menu"> </a>
<form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=zend.pilipok.zp.ua&output=urlentry" style="padding: 0px 0px 0px 0px; margin-top: 0">
<table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%">
<tr><td>
<table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%">
<tr><td class="aws" valign="middle"><b>Statistics for:</b> </td><td class="aws" valign="middle"><span style="font-size: 14px;">zend.pilipok.zp.ua</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstatsicons/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr>
<tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b> </td><td class="aws" valign="middle"><span style="font-size: 12px;">17 Jan 2017 - 04:48</span></td></tr>
<tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Jan 2017</span></td></tr>
</table>
</td></tr></table>
</form>
<table>
<tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr>
</table>
<a name="urls"> </a><br />
<table class="aws_border sortable" border="0" cellpadding="2" cellspacing="0" width="100%">
<tr><td class="aws_title" width="70%">Entry </td><td class="aws_blank"> </td></tr>
<tr><td colspan="2">
<table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%">
<tr bgcolor="#ECECEC"><th>Total: 1 different pages-url</th><th bgcolor="#4477DD" width="80">Viewed</th><th class="datasize" bgcolor="#2EA495" width="80">Average size</th><th bgcolor="#CEC2E8" width="80">Entry</th><th bgcolor="#C1B2E2" width="80">Exit</th><th> </th></tr>
<tr><td class="aws"><a href="http://zend.pilipok.zp.ua/" target="url">/</a></td><td>36</td><td>1.88 KB</td><td>5</td><td>4</td><td class="aws"><img src="/awstatsicons/other/hp.png" width="261" height="4" /><br /><img src="/awstatsicons/other/hk.png" width="261" height="4" /><br /><img src="/awstatsicons/other/he.png" width="37" height="4" /><br /><img src="/awstatsicons/other/hx.png" width="29" height="4" /></td></tr>
<tr><td class="aws"><span style="color: #666688">Others</span></td><td>52</td><td>52.31 KB</td><td> </td><td>1</td><td> </td></tr>
</table></td></tr></table><br />
<br /><br />
<span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 7.0 (build 1.971)</b> - <a href="http://awstats.sourceforge.net" target="awstatshome">Created by awstats</a></span><br />
<br />
</body>
</html>
| bsd-3-clause |
brandonprry/gray_hat_csharp_code | ch12_automating_arachni_rpc/ArachniRPCSession.cs | 3992 | using System;
using System.Net.Security;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using System.IO;
using System.IO.Compression;
using MsgPack.Serialization;
using MsgPack;
using zlib;
namespace ch14_automating_arachni_rpc
{
public class ArachniRPCSession : IDisposable
{
SslStream _stream = null;
public ArachniRPCSession (string host, int port, bool initiateInstance = false)
{
this.Host = host;
this.Port = port;
GetStream (host, port);
this.IsInstanceStream = false;
if (initiateInstance) {
this.InstanceName = Guid.NewGuid ().ToString ();
MessagePackObjectDictionary resp = this.ExecuteCommand ("dispatcher.dispatch", new object[] { this.InstanceName }).AsDictionary ();
string[] url = resp ["url"].AsString ().Split (':');
this.InstanceHost = url [0];
this.InstancePort = int.Parse (url [1]);
this.Token = resp ["token"].AsString ();
GetStream (this.InstanceHost, this.InstancePort);
bool aliveResp = this.ExecuteCommand ("service.alive?", new object[]{ }, this.Token).AsBoolean ();
this.IsInstanceStream = aliveResp;
}
}
public string Host { get; set; }
public int Port { get; set; }
public string Token { get; set; }
public bool IsInstanceStream { get; set; }
public string InstanceHost { get; set; }
public int InstancePort { get; set; }
public string InstanceName { get; set; }
public MessagePackObject ExecuteCommand (string command, object[] args, string token = null)
{
Dictionary<string, object> message = new Dictionary<string, object> ();
message ["message"] = command;
message ["args"] = args;
if (token != null)
message ["token"] = token;
byte[] packed;
using (MemoryStream stream = new MemoryStream ()) {
Packer packer = Packer.Create (stream);
packer.PackMap (message);
packed = stream.ToArray ();
}
byte[] packedLength = BitConverter.GetBytes (packed.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse (packedLength);
_stream.Write (packedLength);
_stream.Write (packed);
byte[] respBytes = ReadMessage (_stream);
MessagePackObjectDictionary resp = null;
try {
resp = Unpacking.UnpackObject (respBytes).Value.AsDictionary ();
} catch {
byte[] decompressed = DecompressData (respBytes);
resp = Unpacking.UnpackObject (decompressed).Value.AsDictionary ();
}
return resp.ContainsKey ("obj") ? resp ["obj"] : resp ["exception"];
}
public byte[] DecompressData (byte[] inData)
{
using (MemoryStream outMemoryStream = new MemoryStream ()) {
using (ZOutputStream outZStream = new ZOutputStream (outMemoryStream)){
outZStream.Write (inData, 0, inData.Length);
return outMemoryStream.ToArray ();
}
}
}
private byte[] ReadMessage (SslStream sslStream)
{
byte[] sizeBytes = new byte[4];
sslStream.Read (sizeBytes, 0, sizeBytes.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse (sizeBytes);
uint size = BitConverter.ToUInt32 (sizeBytes, 0);
byte[] buffer = new byte[size];
sslStream.Read (buffer, 0, buffer.Length);
return buffer;
}
private void GetStream (string host, int port)
{
TcpClient client = new TcpClient (host, port);
_stream = new SslStream (client.GetStream (), false, new RemoteCertificateValidationCallback (ValidateServerCertificate),
(sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => null);
_stream.AuthenticateAsClient ("arachni", null, SslProtocols.Tls, false);
}
private bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void Dispose ()
{
if (this.IsInstanceStream && _stream != null)
this.ExecuteCommand ("service.shutdown", new object[] { }, this.Token);
_stream = null;
}
}
}
| bsd-3-clause |
ma-si/aist-git-tools | config/module.config.php | 1607 | <?php
/**
* AistGitTools (http://mateuszsitek.com/projects/aist-git-tools)
*
* @link http://github.com/ma-si/aist-git-tools for the canonical source repository
* @copyright Copyright (c) 2006-2017 Aist Internet Technologies (http://aist.pl) All rights reserved.
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
*/
return [
'service_manager' => [
'invokables' => [
'git.toolbar' => 'AistGitTools\Collector\GitCollector',
],
],
'view_manager' => [
'template_path_stack' => [
__DIR__ . '/../view',
],
'template_map' => [
'zend-developer-tools/toolbar/git-data' => __DIR__ . '/../view/zend-developer-tools/toolbar/git-data.phtml',
],
],
'zenddevelopertools' => [
'profiler' => [
'collectors' => [
'git.toolbar' => 'git.toolbar',
],
],
'toolbar' => [
'entries' => [
'git.toolbar' => 'zend-developer-tools/toolbar/git-data',
],
],
],
'git' => [
'hooks' => [
'applypatch-msg',
'pre-applypatch',
'post-applypatch',
'pre-commit',
'prepare-commit-msg',
'commit-msg',
'post-commit',
'pre-rebase',
'post-checkout',
'post-merge',
'pre-receive',
'update',
'post-receive',
'post-update',
'pre-auto-gc',
'post-rewrite',
'pre-push',
],
],
];
| bsd-3-clause |
newsuk/times-components | packages/edition-slices/src/slices/leaders/masthead.js | 738 | import React from "react";
import Image from "@times-components/image";
import styleFactory from "./styles";
import propTypes from "./proptypes";
const MastHead = ({ publicationName, breakpoint }) => {
let uri = "https://www.thetimes.co.uk/d/img/leaders-masthead-d17db00289.png";
let aspectRatio = 1435 / 250;
let style = "mastheadStyleTimes";
const styles = styleFactory(breakpoint);
if (publicationName !== "TIMES") {
style = "mastheadStyleST";
aspectRatio = 243 / 45;
uri =
"https://www.thetimes.co.uk/d/img/logos/sundaytimes-with-crest-black-53d6e31fb8.png";
}
return <Image aspectRatio={aspectRatio} style={styles[style]} uri={uri} />;
};
MastHead.propTypes = propTypes;
export default MastHead;
| bsd-3-clause |
misli/django-domecek | domecek/migrations/0012_new_clubjournalentry.py | 2269 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import djangocms_text_ckeditor.fields
def migrate_club_journal(apps, schema_editor):
import re
ClubJournalEntry = apps.get_model('domecek', 'ClubJournalEntry')
for entry in ClubJournalEntry.objects.all():
entry.agenda = '<p>{}</p>'.format('<br />'.join(entry.agenda.split('\n')))
entry.participants = [reg.participant for reg in entry.registrations.all()]
entry.period = entry.club.periods.get(start__lte=entry.start, end__gte=entry.end)
entry.save()
class Migration(migrations.Migration):
dependencies = [
('domecek', '0011_remove_clubregistration_periods'),
]
operations = [
migrations.AlterField(
model_name='clubjournalentry',
name='agenda',
field=djangocms_text_ckeditor.fields.HTMLField(verbose_name='agenda'),
preserve_default=True,
),
migrations.RenameField(
model_name='clubjournalentry',
old_name='participants',
new_name='registrations',
),
migrations.AddField(
model_name='clubjournalentry',
name='participants',
field=models.ManyToManyField(related_name='journal_entries', verbose_name='participants', to='domecek.Participant', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='clubjournalentry',
name='period',
field=models.ForeignKey(related_name='journal_entries', verbose_name='period', to='domecek.ClubPeriod', null=True),
preserve_default=True,
),
migrations.RunPython(migrate_club_journal),
migrations.AlterField(
model_name='clubjournalentry',
name='period',
field=models.ForeignKey(related_name='journal_entries', verbose_name='period', to='domecek.ClubPeriod'),
preserve_default=True,
),
migrations.RemoveField(
model_name='clubjournalentry',
name='club',
),
migrations.RemoveField(
model_name='clubjournalentry',
name='registrations',
),
]
| bsd-3-clause |
zcbenz/cefode-chromium | chrome/browser/autofill/wallet/instrument_unittest.cc | 6679 | // Copyright (c) 2013 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 "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/wallet/instrument.h"
#include "chrome/browser/autofill/wallet/wallet_address.h"
#include "chrome/browser/autofill/wallet/wallet_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kPrimaryAccountNumber[] = "4444444444444448";
const char kCardVerificationNumber[] = "123";
const char kLastFourDigits[] = "4448";
}
namespace autofill {
namespace wallet {
TEST(Instrument, LastFourDigits) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_EQ(ASCIIToUTF16(kLastFourDigits), instrument.last_four_digits());
EXPECT_TRUE(instrument.IsValid());
}
TEST(Instrument, NoPrimaryAccountNumberIsInvalid) {
Instrument instrument(string16(),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooShortPrimaryAccountNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16("44447"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLongPrimaryAccountNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16("44444444444444444448"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, PrimaryAccountNumberNotPassingLuhnIsInvalid) {
Instrument instrument(ASCIIToUTF16("4444444444444444"),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, NoCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
string16(),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooShortCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16("12"),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLongCardVerificationNumberIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16("12345"),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, ZeroAsExpirationMonthIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
0,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLargeExpirationMonthIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
13,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooSmallExpirationYearIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
999,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, TooLargeExpirationYearIsInvalid) {
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
10000,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_FALSE(instrument.IsValid());
}
TEST(Instrument, ToDictionary) {
base::DictionaryValue expected;
expected.SetString("type", "CREDIT_CARD");
expected.SetInteger("credit_card.exp_month", 12);
expected.SetInteger("credit_card.exp_year", 2015);
expected.SetString("credit_card.last_4_digits", kLastFourDigits);
expected.SetString("credit_card.fop_type", "VISA");
expected.SetString("credit_card.address.country_name_code",
"ship_country_name_code");
expected.SetString("credit_card.address.recipient_name",
"ship_recipient_name");
expected.SetString("credit_card.address.locality_name",
"ship_locality_name");
expected.SetString("credit_card.address.administrative_area_name",
"ship_admin_area_name");
expected.SetString("credit_card.address.postal_code_number",
"ship_postal_code_number");
base::ListValue* address_lines = new base::ListValue();
address_lines->AppendString("ship_address_line_1");
address_lines->AppendString("ship_address_line_2");
expected.Set("credit_card.address.address_line", address_lines);
Instrument instrument(ASCIIToUTF16(kPrimaryAccountNumber),
ASCIIToUTF16(kCardVerificationNumber),
12,
2015,
Instrument::VISA,
GetTestShippingAddress().Pass());
EXPECT_TRUE(expected.Equals(instrument.ToDictionary().get()));
}
} // namespace wallet
} // namespace autofill
| bsd-3-clause |
smartdevicelink/sdl_core | src/components/security_manager/src/security_manager_impl.cc | 24474 | /*
* Copyright (c) 2018, Ford Motor Company
* 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 Ford Motor Company 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.
*/
#include "security_manager/security_manager_impl.h"
#include <functional>
#include "json/json.h"
#include "protocol_handler/protocol_packet.h"
#include "security_manager/crypto_manager_impl.h"
#include "utils/byte_order.h"
#include "utils/helpers.h"
#include "utils/jsoncpp_reader_wrapper.h"
#include "utils/logger.h"
namespace security_manager {
SDL_CREATE_LOG_VARIABLE("SecurityManager")
static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl(
std::unique_ptr<utils::SystemTimeHandler>&& system_time_handler)
: security_messages_("SecurityManager", this)
, session_observer_(NULL)
, crypto_manager_(NULL)
, protocol_handler_(NULL)
, system_time_handler_(std::move(system_time_handler))
, current_seq_number_(0)
, waiting_for_certificate_(false)
, waiting_for_time_(false) {
DCHECK(system_time_handler_);
system_time_handler_->SubscribeOnSystemTime(this);
}
SecurityManagerImpl::~SecurityManagerImpl() {
system_time_handler_->UnsubscribeFromSystemTime(this);
}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
if (message->service_type() != protocol_handler::kControl) {
return;
}
SecurityMessage securityMessagePtr(std::make_shared<SecurityQuery>());
const bool result =
securityMessagePtr->SerializeQuery(message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
SDL_LOG_ERROR(error_text);
SendInternalError(
message->connection_key(), ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
// Post message to message query for next processing in thread
security_messages_.PostMessage(securityMessagePtr);
}
void SecurityManagerImpl::OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr) {}
void SecurityManagerImpl::set_session_observer(
protocol_handler::SessionObserver* observer) {
if (!observer) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SessionObserver.");
return;
}
session_observer_ = observer;
}
void SecurityManagerImpl::set_protocol_handler(
protocol_handler::ProtocolHandler* handler) {
if (!handler) {
SDL_LOG_ERROR("Invalid (NULL) pointer to ProtocolHandler.");
return;
}
protocol_handler_ = handler;
}
void SecurityManagerImpl::set_crypto_manager(CryptoManager* crypto_manager) {
if (!crypto_manager) {
SDL_LOG_ERROR("Invalid (NULL) pointer to CryptoManager.");
return;
}
crypto_manager_ = crypto_manager;
}
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
SDL_LOG_INFO("Received Security message from Mobile side");
if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
SDL_LOG_ERROR(error_text);
SendInternalError(
message->get_connection_key(), ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
case SecurityQuery::SEND_HANDSHAKE_DATA:
if (!ProcessHandshakeData(message)) {
SDL_LOG_ERROR("Process HandshakeData failed");
}
break;
case SecurityQuery::SEND_INTERNAL_ERROR:
if (!ProcessInternalError(message)) {
SDL_LOG_ERROR("Processing income InternalError failed");
}
break;
default: {
// SecurityQuery::InvalidQuery
const std::string error_text("Unknown query identifier.");
SDL_LOG_ERROR(error_text);
SendInternalError(message->get_connection_key(),
ERROR_INVALID_QUERY_ID,
error_text,
message->get_header().seq_number);
} break;
}
}
security_manager::SSLContext* SecurityManagerImpl::CreateSSLContext(
const uint32_t& connection_key, ContextCreationStrategy cc_strategy) {
SDL_LOG_INFO("ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
if (kUseExisting == cc_strategy) {
security_manager::SSLContext* ssl_context =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
// If SSLContext for current connection/session exists - return it
if (ssl_context) {
return ssl_context;
}
}
security_manager::SSLContext* ssl_context =
crypto_manager_->CreateSSLContext();
if (!ssl_context) {
const std::string error_text("CryptoManager could not create SSL context.");
SDL_LOG_ERROR(error_text);
// Generate response query and post to security_messages_
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
return NULL;
}
const int result =
session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
SendInternalError(connection_key, result, "");
return NULL;
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
SDL_LOG_DEBUG("Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::PostponeHandshake(const uint32_t connection_key) {
SDL_LOG_TRACE("Handshake postponed");
sync_primitives::AutoLock lock(connections_lock_);
if (waiting_for_certificate_) {
awaiting_certificate_connections_.insert(connection_key);
}
if (waiting_for_time_) {
awaiting_time_connections_.insert(connection_key);
}
}
void SecurityManagerImpl::ResumeHandshake(uint32_t connection_key) {
SDL_LOG_TRACE("Handshake resumed");
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kForceRecreation);
if (!ssl_context) {
SDL_LOG_WARN("Unable to resume handshake. No SSL context for key "
<< connection_key);
return;
}
SDL_LOG_DEBUG("Connection key : "
<< connection_key << " is waiting for certificate: "
<< std::boolalpha << waiting_for_certificate_
<< " and has certificate: " << ssl_context->HasCertificate());
ssl_context->ResetConnection();
if (!waiting_for_certificate_ && !ssl_context->HasCertificate()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
ProceedHandshake(ssl_context, connection_key);
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
SDL_LOG_INFO("StartHandshake: connection_key " << connection_key);
security_manager::SSLContext* ssl_context = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!ssl_context) {
const std::string error_text(
"StartHandshake failed, "
"connection is not protected");
SDL_LOG_ERROR(error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
if (!ssl_context->HasCertificate()) {
SDL_LOG_ERROR("Security certificate is absent");
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
NotifyOnCertificateUpdateRequired();
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = true;
}
PostponeHandshake(connection_key);
system_time_handler_->QuerySystemTime();
}
bool SecurityManagerImpl::IsSystemTimeProviderReady() const {
return system_time_handler_->system_time_can_be_received();
}
void SecurityManagerImpl::ProceedHandshake(
security_manager::SSLContext* ssl_context, uint32_t connection_key) {
SDL_LOG_AUTO_TRACE();
if (!ssl_context) {
SDL_LOG_WARN("Unable to process handshake. No SSL context for key "
<< connection_key);
return;
}
if (ssl_context->IsInitCompleted()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
return;
}
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
SDL_LOG_ERROR("Failed to get certificate due date!");
PostponeHandshake(connection_key);
return;
}
if (crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date)) {
SDL_LOG_DEBUG("Host certificate update required");
if (helpers::in_range(awaiting_certificate_connections_, connection_key)) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_CertExpired);
return;
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
}
PostponeHandshake(connection_key);
NotifyOnCertificateUpdateRequired();
return;
}
SSLContext::HandshakeContext handshake_context =
session_observer_->GetHandshakeContext(connection_key);
handshake_context.system_time = system_time_handler_->GetUTCTime();
ssl_context->SetHandshakeContext(handshake_context);
size_t data_size = 0;
const uint8_t* data = NULL;
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
SDL_LOG_ERROR(error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
if (data != NULL && data_size != 0) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
bool SecurityManagerImpl::IsCertificateUpdateRequired(
const uint32_t connection_key) {
SDL_LOG_AUTO_TRACE();
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kUseExisting);
DCHECK_OR_RETURN(ssl_context, true);
SDL_LOG_DEBUG("Set SSL context to connection_key " << connection_key);
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
SDL_LOG_ERROR("Failed to get certificate due date!");
return true;
}
return crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date);
}
void SecurityManagerImpl::AddListener(SecurityManagerListener* const listener) {
if (!listener) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
void SecurityManagerImpl::RemoveListener(
SecurityManagerListener* const listener) {
if (!listener) {
SDL_LOG_ERROR("Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
bool SecurityManagerImpl::OnCertificateUpdated(const std::string& data) {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = false;
}
crypto_manager_->OnCertificateUpdated(data);
std::for_each(
awaiting_certificate_connections_.begin(),
awaiting_certificate_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_certificate_connections_.clear();
return true;
}
void SecurityManagerImpl::OnSystemTimeArrived(const time_t utc_time) {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = false;
}
std::for_each(
awaiting_time_connections_.begin(),
awaiting_time_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_time_connections_.clear();
}
void SecurityManagerImpl::OnSystemTimeFailed() {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = false;
}
NotifyListenersOnGetSystemTimeFailed();
awaiting_time_connections_.clear();
}
void SecurityManagerImpl::ProcessFailedPTU() {
SDL_LOG_AUTO_TRACE();
if (listeners_.empty()) {
SDL_LOG_DEBUG("listeners arrays IS EMPTY!");
return;
}
std::list<SecurityManagerListener*> listeners_to_remove;
for (auto listener : listeners_) {
if (listener->OnPTUFailed()) {
listeners_to_remove.push_back(listener);
}
}
for (auto& listener : listeners_to_remove) {
auto it = std::find(listeners_.begin(), listeners_.end(), listener);
DCHECK(it != listeners_.end());
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
listeners_.erase(it);
}
}
#if defined(EXTERNAL_PROPRIETARY_MODE) && defined(ENABLE_SECURITY)
void SecurityManagerImpl::ProcessFailedCertDecrypt() {
SDL_LOG_AUTO_TRACE();
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = false;
}
std::list<SecurityManagerListener*> listeners_to_remove;
for (auto listener : listeners_) {
if (listener->OnCertDecryptFailed()) {
listeners_to_remove.push_back(listener);
}
}
for (auto& listener : listeners_to_remove) {
auto it = std::find(listeners_.begin(), listeners_.end(), listener);
DCHECK(it != listeners_.end());
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
listeners_.erase(it);
}
awaiting_certificate_connections_.clear();
}
#endif
void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
const uint32_t& connection_key, SSLContext::HandshakeResult error) {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeDone(connection_key, error)) {
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
void SecurityManagerImpl::NotifyOnCertificateUpdateRequired() {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
(*it)->OnCertificateUpdateRequired();
++it;
}
}
void SecurityManagerImpl::ResetPendingSystemTimeRequests() {
system_time_handler_->ResetPendingSystemTimeRequests();
}
void SecurityManagerImpl::NotifyListenersOnGetSystemTimeFailed() {
SDL_LOG_AUTO_TRACE();
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnGetSystemTimeFailed()) {
SDL_LOG_DEBUG("Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
bool SecurityManagerImpl::IsPolicyCertificateDataEmpty() {
SDL_LOG_AUTO_TRACE();
std::string certificate_data;
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
if ((*it)->GetPolicyCertificateData(certificate_data)) {
SDL_LOG_DEBUG("Certificate data received from listener");
return certificate_data.empty();
}
}
return false;
}
bool SecurityManagerImpl::ProcessHandshakeData(
const SecurityMessage& inMessage) {
SDL_LOG_INFO("SendHandshakeData processing");
DCHECK(inMessage);
DCHECK(inMessage->get_header().query_id ==
SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
SDL_LOG_DEBUG("Received " << inMessage->get_data_size()
<< " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
SDL_LOG_ERROR(error_text);
SendInternalError(
connection_key, ERROR_INVALID_QUERY_SIZE, error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
SSLContext* sslContext = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
SDL_LOG_ERROR(error_text);
SendInternalError(
connection_key, ERROR_SERVICE_NOT_PROTECTED, error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
const uint8_t* out_data;
const SSLContext::HandshakeResult handshake_result =
sslContext->DoHandshakeStep(inMessage->get_data(),
inMessage->get_data_size(),
&out_data,
&out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string error_text(sslContext->LastError());
SDL_LOG_ERROR("SendHandshakeData: Handshake failed: " << error_text);
SendInternalError(
connection_key, ERROR_SSL_INVALID_DATA, error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
SDL_LOG_DEBUG("SSL initialization finished success.");
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
} else if (handshake_result != SSLContext::Handshake_Result_Success) {
// On handshake fail
SDL_LOG_WARN("SSL initialization finished with fail.");
int32_t error_code = ERROR_HANDSHAKE_FAILED;
std::string error_text = "Handshake failed";
switch (handshake_result) {
case SSLContext::Handshake_Result_CertExpired:
error_code = ERROR_EXPIRED_CERT;
error_text = "Certificate is expired";
break;
case SSLContext::Handshake_Result_NotYetValid:
error_code = ERROR_INVALID_CERT;
error_text = "Certificate is not yet valid";
break;
case SSLContext::Handshake_Result_CertNotSigned:
error_code = ERROR_INVALID_CERT;
error_text = "Certificate is not signed";
break;
case SSLContext::Handshake_Result_AppIDMismatch:
error_code = ERROR_INVALID_CERT;
error_text = "App ID does not match certificate";
break;
default:
break;
}
SendInternalError(connection_key, error_code, error_text);
NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
SendHandshakeBinData(connection_key, out_data, out_data_size, seqNumber);
}
return true;
}
bool SecurityManagerImpl::ProcessInternalError(
const SecurityMessage& inMessage) {
std::string str = inMessage->get_json_message();
const uint32_t connection_key = inMessage->get_connection_key();
SDL_LOG_INFO("Received InternalError with Json message" << str);
Json::Value root;
utils::JsonReader reader;
if (!reader.parse(str, &root)) {
SDL_LOG_DEBUG("Json parsing fails.");
return false;
}
uint8_t id = root[kErrId].asInt();
SDL_LOG_DEBUG("Received InternalError id " << std::to_string(id) << ", text: "
<< root[kErrText].asString());
if (ERROR_SSL_INVALID_DATA == id || ERROR_NOT_SUPPORTED == id) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
}
return true;
}
uint32_t SecurityManagerImpl::NextSequentialNumber() {
if (current_seq_number_ >= std::numeric_limits<uint32_t>::max()) {
current_seq_number_ = 0;
}
current_seq_number_++;
return current_seq_number_;
}
void SecurityManagerImpl::SendHandshakeBinData(
const uint32_t connection_key,
const uint8_t* const data,
const size_t data_size,
const uint32_t custom_seq_number) {
uint32_t seq_number =
(0 == custom_seq_number) ? NextSequentialNumber() : custom_seq_number;
const SecurityQuery::QueryHeader header(
SecurityQuery::REQUEST, SecurityQuery::SEND_HANDSHAKE_DATA, seq_number);
DCHECK(data_size < 1024 * 1024 * 1024);
const SecurityQuery query =
SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
SDL_LOG_DEBUG("Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
const uint8_t& error_id,
const std::string& error_text,
const uint32_t seq_number) {
Json::Value value;
value[kErrId] = error_id;
value[kErrText] = error_text;
const std::string error_str = value.toStyledString();
SecurityQuery::QueryHeader header(
SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_INTERNAL_ERROR,
// header save json size only (exclude last byte)
seq_number,
error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
data_sending[data_sending.size() - 1] = error_id;
const SecurityQuery query(
header, connection_key, &data_sending[0], data_sending.size());
SendQuery(query, connection_key);
SDL_LOG_DEBUG("Sent Internal error id " << static_cast<int>(error_id)
<< " : \"" << error_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
session_observer_->PairFromKey(
connection_key, &connection_handle, &sessionID);
if (session_observer_->ProtocolVersionUsed(
connection_handle, sessionID, protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
new protocol_handler::RawMessage(connection_key,
protocol_version,
&data_sending[0],
data_sending.size(),
false,
protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false, false);
}
}
const char* SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
} // namespace security_manager
| bsd-3-clause |
motech/perf | instance-info/src/main/resources/webapp/js/app.js | 399 | (function () {
'use strict';
angular.module('instance-info', ['motech-dashboard', 'instance-info.controllers', 'ngCookies', 'ui.bootstrap']).config(
['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/instance-info/info', {templateUrl: '../instance-info/resources/partials/info.html', controller: 'InfoController'});
}]);
}());
| bsd-3-clause |
NevilleS/relay | src/traversal/__tests__/writeRelayQueryPayload_defaultNull-test.js | 4160 | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+relay
*/
'use strict';
require('configureForRelayOSS');
jest
.dontMock('GraphQLRange')
.dontMock('GraphQLSegment');
const Relay = require('Relay');
const RelayRecordStore = require('RelayRecordStore');
const RelayRecordWriter = require('RelayRecordWriter');
const RelayTestUtils = require('RelayTestUtils');
describe('writeRelayQueryPayload()', () => {
const {getNode, writePayload} = RelayTestUtils;
beforeEach(() => {
jest.resetModuleRegistry();
});
describe('default null', () => {
it('writes missing scalar field as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
id,
name
}
}
`);
const payload = {
node: {
__typename: 'User',
id: '123',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'123': true,
},
updated: {},
});
expect(store.getField('123', 'name')).toBe(null);
});
it('writes missing linked field as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
viewer {
actor {
id
}
}
}
`);
const payload = {
viewer: {},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'client:1': true,
},
updated: {},
});
expect(store.getRecordState('client:1')).toBe('EXISTENT');
expect(store.getLinkedRecordID('client:1', 'actor')).toBe(null);
});
it('writes missing plural linked field as null', () => {
const records = {
'123': {
__dataID__: '123',
id: '123',
},
};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
allPhones {
phoneNumber {
displayNumber
}
}
}
}
`);
const payload = {
node: {
__typename: 'User',
id: '123',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {},
updated: {
'123': true,
},
});
const phoneIDs = store.getLinkedRecordIDs('123', 'allPhones');
expect(phoneIDs).toEqual(null);
});
it('writes missing connection as null', () => {
const records = {};
const store = new RelayRecordStore({records});
const writer = new RelayRecordWriter(records, {}, false);
const query = getNode(Relay.QL`
query {
node(id:"123") {
friends(first:"3") {
edges {
cursor,
node {
id
},
},
pageInfo {
hasNextPage,
hasPreviousPage,
}
}
}
}
`);
const payload = {
node: {
id: '123',
__typename: 'User',
},
};
const results = writePayload(store, writer, query, payload);
expect(results).toEqual({
created: {
'123': true,
},
updated: {},
});
expect(store.getField('123', 'friends')).toBe(null);
});
});
});
| bsd-3-clause |
aufflick/core-plot | documentation/html/iOS/protocol_c_p_t_plot_delegate-p.html | 11642 | <!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Core Plot (iOS): <CPTPlotDelegate> Protocol Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="customdoxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="core-plot-logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Core Plot (iOS)
</div>
<div id="projectbrief">Cocoa plotting framework for Mac OS X and iOS</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.1.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Animation & Constants</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('protocol_c_p_t_plot_delegate-p.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title"><CPTPlotDelegate> Protocol Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Plot delegate.
<a href="protocol_c_p_t_plot_delegate-p.html#details">More...</a></p>
<p><code>#import <<a class="el" href="_c_p_t_plot_8h_source.html">CPTPlot.h</a>></code></p>
<div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-0-trigger" src="closed.png" alt="+"/> Inheritance diagram for <CPTPlotDelegate>:</div>
<div id="dynsection-0-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-0-content" class="dyncontent" style="display:none;">
<div class="center"><img src="protocol_c_p_t_plot_delegate-p__inherit__graph.png" border="0" usemap="#_3_c_p_t_plot_delegate_4_inherit__map" alt="Inheritance graph"/></div>
<map name="_3_c_p_t_plot_delegate_4_inherit__map" id="_3_c_p_t_plot_delegate_4_inherit__map">
<area shape="rect" id="node5" href="protocol_c_p_t_bar_plot_delegate-p.html" title="Bar plot delegate." alt="" coords="403,5,573,35"/><area shape="rect" id="node7" href="protocol_c_p_t_pie_chart_delegate-p.html" title="Pie chart delegate." alt="" coords="399,59,577,90"/><area shape="rect" id="node9" href="protocol_c_p_t_range_plot_delegate-p.html" title="Range plot delegate." alt="" coords="394,114,582,145"/><area shape="rect" id="node11" href="protocol_c_p_t_scatter_plot_delegate-p.html" title="Scatter plot delegate." alt="" coords="392,169,584,199"/><area shape="rect" id="node13" href="protocol_c_p_t_trading_range_plot_delegate-p.html" title="Trading range plot delegate." alt="" coords="369,223,607,254"/><area shape="rect" id="node2" href="http://developer.apple.com/iPhone/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html" title="\<NSObject-p\>" alt="" coords="5,114,123,145"/></map>
<center><span class="legend">[<a target="top" href="graph_legend.html">legend</a>]</span></center></div>
<div id="dynsection-1" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-1-trigger" src="closed.png" alt="+"/> Collaboration diagram for <CPTPlotDelegate>:</div>
<div id="dynsection-1-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-1-content" class="dyncontent" style="display:none;">
<div class="center"><img src="protocol_c_p_t_plot_delegate-p__coll__graph.png" border="0" usemap="#_3_c_p_t_plot_delegate_4_coll__map" alt="Collaboration graph"/></div>
<map name="_3_c_p_t_plot_delegate_4_coll__map" id="_3_c_p_t_plot_delegate_4_coll__map">
<area shape="rect" id="node2" href="http://developer.apple.com/iPhone/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html" title="\<NSObject-p\>" alt="" coords="20,6,137,37"/></map>
<center><span class="legend">[<a target="top" href="graph_legend.html">legend</a>]</span></center></div>
<p><a href="protocol_c_p_t_plot_delegate-p-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2><a name="pub-methods"></a>
Public Instance Methods</h2></td></tr>
<tr><td colspan="2"><div class="groupHeader">Point Selection</div></td></tr>
<tr class="memitem:ad6ca9ed72b54b2715f01c95d086eb78b"><td class="memItemLeft" align="right" valign="top">(void) </td><td class="memItemRight" valign="bottom">- <a class="el" href="protocol_c_p_t_plot_delegate-p.html#ad6ca9ed72b54b2715f01c95d086eb78b">plot:dataLabelWasSelectedAtRecordIndex:</a></td></tr>
<tr class="memdesc:ad6ca9ed72b54b2715f01c95d086eb78b"><td class="mdescLeft"> </td><td class="mdescRight">(Optional) Informs the delegate that a data label was touched. <a href="#ad6ca9ed72b54b2715f01c95d086eb78b"></a><br/></td></tr>
<tr class="memitem:aca6e11525937a7d62f66694d5915eb9e"><td class="memItemLeft" align="right" valign="top">(void) </td><td class="memItemRight" valign="bottom">- <a class="el" href="protocol_c_p_t_plot_delegate-p.html#aca6e11525937a7d62f66694d5915eb9e">plot:dataLabelWasSelectedAtRecordIndex:withEvent:</a></td></tr>
<tr class="memdesc:aca6e11525937a7d62f66694d5915eb9e"><td class="mdescLeft"> </td><td class="mdescRight">(Optional) Informs the delegate that a data label was touched. <a href="#aca6e11525937a7d62f66694d5915eb9e"></a><br/></td></tr>
<tr><td colspan="2"><div class="groupHeader">Drawing</div></td></tr>
<tr class="memitem:af68ded0e9746646e581c32b1aa999573"><td class="memItemLeft" align="right" valign="top">(void) </td><td class="memItemRight" valign="bottom">- <a class="el" href="protocol_c_p_t_plot_delegate-p.html#af68ded0e9746646e581c32b1aa999573">didFinishDrawing:</a></td></tr>
<tr class="memdesc:af68ded0e9746646e581c32b1aa999573"><td class="mdescLeft"> </td><td class="mdescRight">Informs the delegate that plot drawing is finished. <a href="#af68ded0e9746646e581c32b1aa999573"></a><br/></td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Plot delegate. </p>
</div><hr/><h2>Method Documentation</h2>
<a class="anchor" id="af68ded0e9746646e581c32b1aa999573"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (void) didFinishDrawing: </td>
<td></td>
<td class="paramtype">(<a class="el" href="interface_c_p_t_plot.html">CPTPlot</a> *) </td>
<td class="paramname"><em>plot</em></td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Informs the delegate that plot drawing is finished. </p>
<dl class="params"><dt>Parameters:</dt><dd>
<table class="params">
<tr><td class="paramname">plot</td><td>The plot. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="ad6ca9ed72b54b2715f01c95d086eb78b"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (void) plot: </td>
<td></td>
<td class="paramtype">(<a class="el" href="interface_c_p_t_plot.html">CPTPlot</a> *) </td>
<td class="paramname"><em>plot</em></td>
</tr>
<tr>
<td class="paramkey">dataLabelWasSelectedAtRecordIndex:</td>
<td></td>
<td class="paramtype">(<a class="elRef" href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html">NSUInteger</a>) </td>
<td class="paramname"><em>index</em> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>(Optional) Informs the delegate that a data label was touched. </p>
<dl class="params"><dt>Parameters:</dt><dd>
<table class="params">
<tr><td class="paramname">plot</td><td>The plot. </td></tr>
<tr><td class="paramname">index</td><td>The index of the touched data label. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="aca6e11525937a7d62f66694d5915eb9e"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (void) plot: </td>
<td></td>
<td class="paramtype">(<a class="el" href="interface_c_p_t_plot.html">CPTPlot</a> *) </td>
<td class="paramname"><em>plot</em></td>
</tr>
<tr>
<td class="paramkey">dataLabelWasSelectedAtRecordIndex:</td>
<td></td>
<td class="paramtype">(<a class="elRef" href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html">NSUInteger</a>) </td>
<td class="paramname"><em>index</em></td>
</tr>
<tr>
<td class="paramkey">withEvent:</td>
<td></td>
<td class="paramtype">(<a class="el" href="_c_p_t_platform_specific_defines_8h.html#a11ae78e634b63fe8bbf175f8db715c26">CPTNativeEvent</a> *) </td>
<td class="paramname"><em>event</em> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>(Optional) Informs the delegate that a data label was touched. </p>
<dl class="params"><dt>Parameters:</dt><dd>
<table class="params">
<tr><td class="paramname">plot</td><td>The plot. </td></tr>
<tr><td class="paramname">index</td><td>The index of the touched data label. </td></tr>
<tr><td class="paramname">event</td><td>The event that triggered the selection. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<hr/>The documentation for this protocol was generated from the following file:<ul>
<li>Source/<a class="el" href="_c_p_t_plot_8h_source.html">CPTPlot.h</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<li class="footer">Generated by <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a></li>
</ul>
</div>
</body>
</html>
| bsd-3-clause |
dCache/CDMI | cdmi-core/src/main/java/org/snia/cdmiserver/exception/BadRequestException.java | 2136 | /*
* Copyright (c) 2010, Sun Microsystems, Inc.
* Copyright (c) 2010, The Storage Networking Industry Association.
*
* 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 Storage Networking Industry Association (SNIA) 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 org.snia.cdmiserver.exception;
/**
* <p>
* Exception that should be mapped to an HTTP Status 400 Response
* </p>
*/
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public BadRequestException(Throwable cause) {
super(cause);
}
}
| bsd-3-clause |
djrosl/travel | backend/models/EventCategorySearch.php | 1683 | <?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\EventCategory;
/**
* EventCategorySearch represents the model behind the search form about `common\models\EventCategory`.
*/
class EventCategorySearch extends EventCategory
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'status'], 'integer'],
[['title_ru', 'created_at', 'updated_at'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = EventCategory::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'title_ru', $this->title_ru]);
return $dataProvider;
}
}
| bsd-3-clause |
n3bukadn3zar/reservo | reservo/reader/views.py | 263 | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from .models import Story
def index(request):
stories = Story.objects.order_by('score')
return render(request, 'reader/stories.html', {'stories': stories})
| bsd-3-clause |
artpol84/slurm-pmix-test | prepare_host/prepare_tools/prepare.sh | 946 | #!/bin/bash -xeE
TOOLS_BASE_PATH=$1
. ./env.sh
rm -Rf $DISTR_PATH
mkdir -p $DISTR_PATH
wget -P $DISTR_PATH $M4_URL
wget -P $DISTR_PATH $AUTOCONF_URL
wget -P $DISTR_PATH $AUTOMAKE_URL
wget -P $DISTR_PATH $LIBTOOL_URL
# Use as much processors
# as we can to speedup
NPROC=`nproc`
export MAKE_JOBS=$NPROC
. ./env.sh
rm -Rf $SRC_PATH $PREFIX
mkdir $SRC_PATH
export PATH="$PREFIX/bin/":$PATH
export LD_LIBRARY_PATH="$PREFIX/bin/":$LD_LIBRARY_PATH
tar -xjvf $DISTR_PATH/$M4_DISTR -C $SRC_PATH
cd $SRC_PATH/$M4_NAME
./configure --prefix=$PREFIX
make
make install
tar -xzvf $DISTR_PATH/$AUTOCONF_DISTR -C $SRC_PATH
cd $SRC_PATH/$AUTOCONF_NAME
./configure --prefix=$PREFIX
make
make install
tar -xzvf $DISTR_PATH/$AUTOMAKE_DISTR -C $SRC_PATH
cd $SRC_PATH/$AUTOMAKE_NAME
./configure --prefix=$PREFIX
make
make install
tar -xzvf $DISTR_PATH/$LIBTOOL_DISTR -C $SRC_PATH
cd $SRC_PATH/$LIBTOOL_NAME
./configure --prefix=$PREFIX
make
make install
| bsd-3-clause |
rust-lang/rust-bindgen | tests/expectations/tests/derive-hash-and-blocklist.rs | 1217 | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub struct BlocklistMe(u8);
/// Because this type contains a blocklisted type, it should not derive Hash.
#[repr(C)]
pub struct ShouldNotDeriveHash {
pub a: BlocklistMe,
}
#[test]
fn bindgen_test_layout_ShouldNotDeriveHash() {
assert_eq!(
::std::mem::size_of::<ShouldNotDeriveHash>(),
1usize,
concat!("Size of: ", stringify!(ShouldNotDeriveHash))
);
assert_eq!(
::std::mem::align_of::<ShouldNotDeriveHash>(),
1usize,
concat!("Alignment of ", stringify!(ShouldNotDeriveHash))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<ShouldNotDeriveHash>())).a as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(ShouldNotDeriveHash),
"::",
stringify!(a)
)
);
}
impl Default for ShouldNotDeriveHash {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
| bsd-3-clause |
statsmodels/statsmodels.github.io | 0.8.0/generated/statsmodels.genmod.families.family.NegativeBinomial.predict.html | 7138 |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.genmod.families.family.NegativeBinomial.predict — statsmodels 0.8.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.8.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</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>
<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.genmod.families.family.NegativeBinomial.resid_anscombe" href="statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe.html" />
<link rel="prev" title="statsmodels.genmod.families.family.NegativeBinomial.loglike" href="statsmodels.genmod.families.family.NegativeBinomial.loglike.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>
</head>
<body role="document">
<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.genmod.families.family.NegativeBinomial.resid_anscombe.html" title="statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.NegativeBinomial.loglike.html" title="statsmodels.genmod.families.family.NegativeBinomial.loglike"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/group/pystatsmodels?hl=en">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="../glm.html" >Generalized Linear Models</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.genmod.families.family.NegativeBinomial.html" accesskey="U">statsmodels.genmod.families.family.NegativeBinomial</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-genmod-families-family-negativebinomial-predict">
<h1>statsmodels.genmod.families.family.NegativeBinomial.predict<a class="headerlink" href="#statsmodels-genmod-families-family-negativebinomial-predict" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.genmod.families.family.NegativeBinomial.predict">
<code class="descclassname">NegativeBinomial.</code><code class="descname">predict</code><span class="sig-paren">(</span><em>mu</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.genmod.families.family.NegativeBinomial.predict" title="Permalink to this definition">¶</a></dt>
<dd><p>Linear predictors based on given mu values.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>mu</strong> : array</p>
<blockquote>
<div><p>The mean response variables</p>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>lin_pred</strong> : array</p>
<blockquote class="last">
<div><p>Linear predictors based on the mean response variables. The value
of the link function at the given mu.</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
</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.genmod.families.family.NegativeBinomial.loglike.html"
title="previous chapter">statsmodels.genmod.families.family.NegativeBinomial.loglike</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe.html"
title="next chapter">statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.genmod.families.family.NegativeBinomial.predict.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.3.
</div>
</body>
</html> | bsd-3-clause |
cooperhewitt/go-ucd | Makefile | 876 | CWD=$(shell pwd)
GOPATH := $(CWD)/vendor:$(CWD)
prep:
if test -d pkg; then rm -rf pkg; fi
self: prep
if test -d src/github.com/cooperhewitt/go-ucd; then rm -rf src/github.com/cooperhewitt/go-ucd; fi
mkdir -p src/github.com/cooperhewitt/go-ucd/unicodedata
mkdir -p src/github.com/cooperhewitt/go-ucd/unihan
cp ucd.go src/github.com/cooperhewitt/go-ucd/
cp unicodedata/unicodedata.go src/github.com/cooperhewitt/go-ucd/unicodedata/
cp unihan/unihan.go src/github.com/cooperhewitt/go-ucd/unihan/
fmt:
go fmt *.go
go fmt unicodedata/*.go
go fmt unihan/*.go
go fmt cmd/*.go
data:
@GOPATH=$(GOPATH) go run cmd/ucd-build-unicodedata.go > unicodedata/unicodedata.go
@GOPATH=$(GOPATH) go run cmd/ucd-build-unihan.go > unihan/unihan.go
build: fmt self
@GOPATH=$(GOPATH) go build -o bin/ucd cmd/ucd.go
@GOPATH=$(GOPATH) go build -o bin/ucd-server cmd/ucd-server.go
| bsd-3-clause |
Tulitomaatti/edice | scrap/asdf.c | 105 | #define _BV(x) (1 << x)
#define bitmask (_BV(3) | _BV 4)
int main() {
int i = 0;
i += bitmask;
} | bsd-3-clause |
eltonoliveira/curso.zend2 | module/Livraria/src/Livraria/Model/CategoriaService.php | 784 | <?php
namespace Livraria\Model;
class CategoriaService
{
/**
* @var Livraria\Model\CategoriaTable
*/
protected $categoriaTable;
/** ------------------------------------------------------------------------------------------------------------- */
/**
* @name __construct
* @return void
*
*/
public function __construct(CategoriaTable $table)
{
$this->categoriaTable = $table;
}
/** ------------------------------------------------------------------------------------------------------------- */
/**
* @name getTodosOsRegistros
* @return array
*
*/
public function retornarTodosOsRegistros()
{
return $this->categoriaTable->select();
}
/** ------------------------------------------------------------------------------------------------------------- */
} | bsd-3-clause |
wakatime/chrome-wakatime | src/utils/isProd.ts | 70 | export default (): boolean => process.env.NODE_ENV !== 'development';
| bsd-3-clause |
seyedmaysamlavasani/GorillaPP | chisel/chisel/src/main/scala/Mem.scala | 6887 | package Chisel
import ChiselError._
import Node._
import scala.collection.mutable.{ArrayBuffer, HashMap}
object Mem {
def apply[T <: Data](n: Int, seqRead: Boolean = false)(gen: => T): Mem[T] = {
Reg.validateGen(gen)
new Mem(n, seqRead, () => gen)
}
Component.backend.transforms.prepend { c =>
c.bfs { n =>
if (n.isInstanceOf[MemAccess])
n.asInstanceOf[MemAccess].referenced = true
}
c.bfs { n =>
if (n.isInstanceOf[Mem[_]])
n.asInstanceOf[Mem[_]].computePorts
}
}
}
abstract class AccessTracker extends Delay {
def writeAccesses: ArrayBuffer[_ <: MemAccess]
def readAccesses: ArrayBuffer[_ <: MemAccess]
}
class Mem[T <: Data](val n: Int, val seqRead: Boolean, gen: () => T) extends AccessTracker {
def writeAccesses = writes ++ readwrites.map(_.write)
def readAccesses = reads ++ seqreads ++ readwrites.map(_.read)
def ports = writes ++ reads ++ seqreads ++ readwrites
val writes = ArrayBuffer[MemWrite]()
val seqreads = ArrayBuffer[MemSeqRead]()
val reads = ArrayBuffer[MemRead]()
val readwrites = ArrayBuffer[MemReadWrite]()
val data = gen().toNode
inferWidth = fixWidth(data.getWidth)
private val readPortCache = HashMap[Bits, T]()
def doRead(addr: Bits): T = {
if (readPortCache.contains(addr))
return readPortCache(addr)
val addrIsReg = addr.isInstanceOf[Bits] && addr.inputs.length == 1 && addr.inputs(0).isInstanceOf[Reg]
val rd = if (seqRead && !Component.isInlineMem && addrIsReg)
(seqreads += new MemSeqRead(this, addr.inputs(0))).last
else
(reads += new MemRead(this, addr)).last
val data = gen().fromNode(rd).asInstanceOf[T]
data.setIsTypeNode
readPortCache += (addr -> data)
data
}
def doWrite(addr: Bits, condIn: Bool, wdata: Node, wmask: Bits) = {
val cond = // add bounds check if depth is not a power of 2
if (isPow2(n)) condIn
else condIn && addr(log2Up(n)-1,0) < UFix(n)
def doit(addr: Bits, cond: Bool, wdata: Node, wmask: Bits) = {
val wr = new MemWrite(this, cond, addr, wdata, wmask)
writes += wr
inputs += wr
wr
}
if (seqRead && Component.backend.isInstanceOf[CppBackend]) {
// generate bogus data when reading & writing same address on same cycle
val reg_data = Reg{gen()}
reg_data.comp procAssign wdata
val reg_wmask = if (wmask == null) null else Reg(wmask)
val random16 = LFSR16()
val random_data = Cat(random16, Array.fill((width-1)/16){random16}:_*)
doit(Reg(addr), Reg(cond), reg_data, reg_wmask)
doit(addr, cond, gen().fromBits(random_data), wmask)
reg_data.comp
} else
doit(addr, cond, wdata, wmask)
}
def read(addr: Bits): T = doRead(addr)
def write(addr: Bits, data: T) = doWrite(addr, conds.top, data.toBits, null.asInstanceOf[Bits])
def write(addr: Bits, data: T, wmask: Bits) = doWrite(addr, conds.top, data.toBits, wmask)
def apply(addr: Bits) = {
val rdata = doRead(addr)
rdata.comp = new PutativeMemWrite(this, addr)
rdata
}
override def isInVCD = false
override def toString: String = "TMEM(" + ")"
override def clone = new Mem(n, seqRead, gen)
def computePorts = {
reads --= reads.filterNot(_.used)
seqreads --= seqreads.filterNot(_.used)
writes --= writes.filterNot(_.used)
// try to extract RW ports
for (w <- writes; r <- seqreads)
if (!w.emitRWEnable(r).isEmpty && !readwrites.contains((rw: MemReadWrite) => rw.read == r || rw.write == w))
readwrites += new MemReadWrite(r, w)
writes --= readwrites.map(_.write)
seqreads --= readwrites.map(_.read)
}
def isInline = Component.isInlineMem || !reads.isEmpty
}
abstract class MemAccess(val mem: Mem[_], addri: Node) extends Node {
def addr = inputs(0)
def cond: Node
inputs += addri
var referenced = false
def used = referenced
def getPortType: String
override def forceMatchingWidths =
if (addr.width != log2Up(mem.n)) inputs(0) = addr.matchWidth(log2Up(mem.n))
}
class MemRead(mem: Mem[_], addri: Node) extends MemAccess(mem, addri) {
override def cond = Bool(true)
inputs += mem
inferWidth = fixWidth(mem.data.getWidth)
override def toString: String = mem + "[" + addr + "]"
override def getPortType: String = "cread"
}
class MemSeqRead(mem: Mem[_], addri: Node) extends MemAccess(mem, addri) {
val addrReg = addri.asInstanceOf[Reg]
override def cond = if (addrReg.isEnable) addrReg.enableSignal else Bool(true)
override def isReg = true
override def addr = inputs(2)
override def forceMatchingWidths = {
val forced = addrReg.updateVal.matchWidth(log2Up(mem.n))
inputs += forced
assert(addr == forced)
}
inputs += mem
inferWidth = fixWidth(mem.data.getWidth)
override def toString: String = mem + "[" + addr + "]"
override def getPortType: String = "read"
override def isRamWriteInput(n: Node) = addrReg.isEnable && addrReg.enableSignal == n || addr == n
}
class PutativeMemWrite(mem: Mem[_], addri: Bits) extends Node with proc {
override def procAssign(src: Node) =
mem.doWrite(addri, conds.top, src, null.asInstanceOf[Bits])
}
class MemReadWrite(val read: MemSeqRead, val write: MemWrite) extends MemAccess(read.mem, null)
{
override def cond = throw new Exception("")
override def getPortType = if (write.isMasked) "mrw" else "rw"
}
class MemWrite(mem: Mem[_], condi: Bool, addri: Node, datai: Node, maski: Node) extends MemAccess(mem, addri) {
inputs += condi
override def cond = inputs(1)
if (datai != null) {
def wrap(x: Node) = { // prevent Verilog syntax errors when indexing constants
val b = Bits()
b.inputs += x
b
}
inputs += wrap(datai)
if (maski != null)
inputs += wrap(maski)
}
override def forceMatchingWidths = {
val w = mem.width
super.forceMatchingWidths
if(inputs.length >= 3 && inputs(2).width != w) inputs(2) = inputs(2).matchWidth(w)
if(inputs.length >= 4 && inputs(3).width != w) inputs(3) = inputs(3).matchWidth(w)
}
var pairedRead: MemSeqRead = null
def emitRWEnable(r: MemSeqRead) = {
def getProducts(x: Node): List[Node] = {
if (x.isInstanceOf[Op] && x.asInstanceOf[Op].op == "&&")
List(x) ++ getProducts(x.inputs(0)) ++ getProducts(x.inputs(1))
else
List(x)
}
def isNegOf(x: Node, y: Node) = x.isInstanceOf[Op] && x.asInstanceOf[Op].op == "!" && x.inputs(0) == y
val wp = getProducts(cond)
val rp = getProducts(r.cond)
wp.find(wc => rp.exists(rc => isNegOf(rc, wc) || isNegOf(wc, rc)))
}
def data = inputs(2)
def mask = inputs(3)
def isMasked = inputs.length > 3
override def toString: String = mem + "[" + addr + "] = " + data + " COND " + cond
override def getPortType: String = if (isMasked) "mwrite" else "write"
override def isRamWriteInput(n: Node) = inputs.contains(n)
}
| bsd-3-clause |
lemon24/rap | rap/__init__.py | 5176 |
__version__ = '0.1dev'
import argparse
import string
import re
from rap.processing_unit import ProcessingUnit
from rap.program import Program, ProgramError
input_pair_regex = re.compile("^\s*([a-zA-Z0-9]+)\s*:\s*([0-9]+)\s*$")
def parse_input(string, sep=',', pair_regex=input_pair_regex):
registers = {}
for pair in string.split(','):
if not pair.strip():
continue
match = pair_regex.match(pair)
if not match:
raise ValueError('ass')
register, value = match.groups()
registers[register] = int(value)
return registers
class Formatter(string.Formatter):
"""Slightly modified string.Formatter.
The differences are:
- field names are considered strings (i.e. only kwargs are used)
- field names / attributes / items that are not found are silently
ignored and their corresponding replacement fields are preserved
- invalid replacement fields are are also silently preserved
"""
def get_field(self, field_name, args, kwargs):
first, rest = string._string.formatter_field_name_split(field_name)
obj = self.get_value(str(first), args, kwargs)
for is_attr, i in rest:
if is_attr:
obj = getattr(obj, i)
else:
obj = obj[str(i)]
return obj, first
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
original_format_spec = format_spec
if literal_text:
result.append(literal_text)
if field_name is not None:
used_args_copy = used_args.copy()
try:
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args_copy.add(arg_used)
obj = self.convert_field(obj, conversion)
format_spec = self._vformat(format_spec, args, kwargs,
used_args_copy, recursion_depth-1)
formatted = self.format_field(obj, format_spec)
result.append(formatted)
used_args.update(used_args_copy)
except (AttributeError, KeyError, ValueError):
result.append("{" + field_name)
if conversion:
result.append("!" + conversion)
if original_format_spec:
result.append(":" + original_format_spec)
result.append("}")
return ''.join(result)
def make_parser():
parser = argparse.ArgumentParser('rap',
description="Register Assembly Programming")
parser.add_argument('file', type=argparse.FileType('r'),
help="a file containing a RAP program")
parser.add_argument('-i', '--input', metavar='input', type=parse_input,
help="set the initial register values (e.g. \"a: 1, b: 2\")")
parser.add_argument('-o', '--output', metavar='format', nargs='?',
const=True, help="""
print the register values after the program ends; if format is
given, register names between braces will be replaced with
their values (e.g. "a: {a}")
""")
parser.add_argument('-t', '--trace', metavar='format', nargs='?',
const=True, help="""
print the register values before every executed instruction;
behaves like --output
""")
parser.add_argument('-s', '--start', metavar='step', type=int,
help="start from instruction step instead of the beginning")
parser.add_argument('-c', '--check', action='store_true',
help="only check the syntax (don't execute the program)")
return parser
def make_printer(what):
if what is None:
return None
if what is True:
return lambda pu: print(pu.registers)
formatter = Formatter()
def printer(pu):
names = dict(pu.registers)
print(formatter.vformat(what, (), names))
return printer
def main(args=None):
parser = make_parser()
args = parser.parse_args(args)
# TODO: validate args.output and args.trace
# TODO: decode character escapes for args.output and args.trace
try:
with args.file as f:
program = Program.load(f)
for error in program.check():
raise error
except ProgramError as e:
parser.error("{} (on line {})".format(e.message, e.line_no))
if args.check:
parser.exit(message=str(program))
if args.start is None:
start = program.start
elif args.start in program:
start = args.start
else:
parser.error("step {} not in program".format(args.start))
trace = make_printer(args.trace)
output = make_printer(args.output)
pu = ProcessingUnit()
pu.registers.update(args.input)
pu.run_program(program, start, trace)
if output:
output(pu)
| bsd-3-clause |
mysticflute/blue | src/menu/menubar.js | 891 | // menubar.js
// top menubar icon
const path = require('path');
const db = require('../lib/db');
const switcher = require('../lib/switcher');
const {Tray, Menu} = require('electron').remote;
const iconPath = path.join(__dirname, '../../resources/menubar-alt2.png');
let menubar = null; // prevent GC
module.exports = function() {
db.getCards().then(cards => {
let template = [];
cards.forEach(card => {
template.push({
label: `Switch to ${card.nickname}`,
click() {
switcher.switchTo(card.address, card.username);
}
});
});
template = template.concat([
{
type: 'separator'
},
{
label: 'Quit',
selector: 'terminate:'
}
]);
menubar = new Tray(iconPath);
menubar.setToolTip('Blue');
menubar.setContextMenu(Menu.buildFromTemplate(template));
})
.done();
};
| bsd-3-clause |
maxhutch/magma | src/sgels_gpu.cpp | 4464 | /*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@generated from src/zgels_gpu.cpp, normal z -> s, Tue Aug 30 09:38:06 2016
*/
#include "magma_internal.h"
/***************************************************************************//**
Purpose
-------
SGELS solves the overdetermined, least squares problem
min || A*X - C ||
using the QR factorization A.
The underdetermined problem (m < n) is not currently handled.
Arguments
---------
@param[in]
trans magma_trans_t
- = MagmaNoTrans: the linear system involves A.
Only TRANS=MagmaNoTrans is currently handled.
@param[in]
m INTEGER
The number of rows of the matrix A. M >= 0.
@param[in]
n INTEGER
The number of columns of the matrix A. M >= N >= 0.
@param[in]
nrhs INTEGER
The number of columns of the matrix C. NRHS >= 0.
@param[in,out]
dA REAL array on the GPU, dimension (LDDA,N)
On entry, the M-by-N matrix A.
On exit, A is overwritten by details of its QR
factorization as returned by SGEQRF.
@param[in]
ldda INTEGER
The leading dimension of the array A, LDDA >= M.
@param[in,out]
dB REAL array on the GPU, dimension (LDDB,NRHS)
On entry, the M-by-NRHS matrix C.
On exit, the N-by-NRHS solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array dB. LDDB >= M.
@param[out]
hwork (workspace) REAL array, dimension MAX(1,LWORK).
On exit, if INFO = 0, HWORK[0] returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array HWORK,
LWORK >= (M - N + NB)*(NRHS + NB) + NRHS*NB,
where NB is the blocksize given by magma_get_sgeqrf_nb( M, N ).
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the HWORK array, returns
this value as the first entry of the HWORK array.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_gels
*******************************************************************************/
extern "C" magma_int_t
magma_sgels_gpu(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
magmaFloat_ptr dA, magma_int_t ldda,
magmaFloat_ptr dB, magma_int_t lddb,
float *hwork, magma_int_t lwork,
magma_int_t *info)
{
magmaFloat_ptr dT;
float *tau;
magma_int_t min_mn;
magma_int_t nb = magma_get_sgeqrf_nb( m, n );
magma_int_t lwkopt = (m - n + nb)*(nrhs + nb) + nrhs*nb;
bool lquery = (lwork == -1);
hwork[0] = magma_smake_lwork( lwkopt );
*info = 0;
/* For now, N is the only case working */
if ( trans != MagmaNoTrans )
*info = -1;
else if (m < 0)
*info = -2;
else if (n < 0 || m < n) /* LQ is not handle for now*/
*info = -3;
else if (nrhs < 0)
*info = -4;
else if (ldda < max(1,m))
*info = -6;
else if (lddb < max(1,m))
*info = -8;
else if (lwork < lwkopt && ! lquery)
*info = -10;
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery)
return *info;
min_mn = min(m,n);
if (min_mn == 0) {
hwork[0] = MAGMA_S_ONE;
return *info;
}
/*
* Allocate temporary buffers
*/
magma_int_t ldtwork = ( 2*min_mn + magma_roundup( n, 32 ) )*nb;
if (nb < nrhs)
ldtwork = ( 2*min_mn + magma_roundup( n, 32 ) )*nrhs;
if (MAGMA_SUCCESS != magma_smalloc( &dT, ldtwork )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
magma_smalloc_cpu( &tau, min_mn );
if ( tau == NULL ) {
magma_free( dT );
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_sgeqrf_gpu( m, n, dA, ldda, tau, dT, info );
if ( *info == 0 ) {
magma_sgeqrs_gpu( m, n, nrhs,
dA, ldda, tau, dT,
dB, lddb, hwork, lwork, info );
}
magma_free( dT );
magma_free_cpu( tau );
return *info;
}
| bsd-3-clause |
ixjlyons/pygesture | pygesture/ui/templates/process_widget_template.py | 3894 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pygesture/ui/templates/process_widget_template.ui'
#
# Created by: PyQt5 UI code generator 5.4.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ProcessWidget(object):
def setupUi(self, ProcessWidget):
ProcessWidget.setObjectName("ProcessWidget")
ProcessWidget.resize(823, 539)
self.gridLayout_2 = QtWidgets.QGridLayout(ProcessWidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.titleLabel = QtWidgets.QLabel(ProcessWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.titleLabel.sizePolicy().hasHeightForWidth())
self.titleLabel.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.titleLabel.setFont(font)
self.titleLabel.setText("")
self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
self.titleLabel.setObjectName("titleLabel")
self.verticalLayout.addWidget(self.titleLabel)
self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(ProcessWidget)
self.groupBox.setMinimumSize(QtCore.QSize(250, 0))
self.groupBox.setObjectName("groupBox")
self.gridLayout = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout.setObjectName("gridLayout")
self.sessionBrowser = SessionBrowser(self.groupBox)
self.sessionBrowser.setObjectName("sessionBrowser")
self.gridLayout.addWidget(self.sessionBrowser, 0, 0, 1, 1)
self.processButton = QtWidgets.QPushButton(self.groupBox)
self.processButton.setEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.processButton.sizePolicy().hasHeightForWidth())
self.processButton.setSizePolicy(sizePolicy)
self.processButton.setObjectName("processButton")
self.gridLayout.addWidget(self.processButton, 1, 0, 1, 1)
self.progressBar = QtWidgets.QProgressBar(self.groupBox)
self.progressBar.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
self.progressBar.setSizePolicy(sizePolicy)
self.progressBar.setMaximum(1)
self.progressBar.setProperty("value", 1)
self.progressBar.setTextVisible(True)
self.progressBar.setOrientation(QtCore.Qt.Horizontal)
self.progressBar.setInvertedAppearance(False)
self.progressBar.setFormat("")
self.progressBar.setObjectName("progressBar")
self.gridLayout.addWidget(self.progressBar, 2, 0, 1, 1)
self.gridLayout_2.addWidget(self.groupBox, 0, 1, 1, 1)
self.retranslateUi(ProcessWidget)
QtCore.QMetaObject.connectSlotsByName(ProcessWidget)
def retranslateUi(self, ProcessWidget):
_translate = QtCore.QCoreApplication.translate
ProcessWidget.setWindowTitle(_translate("ProcessWidget", "Form"))
self.groupBox.setTitle(_translate("ProcessWidget", "Sessions"))
self.processButton.setText(_translate("ProcessWidget", "Process"))
from pygesture.ui.widgets import SessionBrowser
| bsd-3-clause |
EventStore/EventStore.JVM | core/src/test/scala/eventstore/core/operations/TransactionStartInspectionSpec.scala | 1418 | package eventstore
package core
package operations
import scala.util.{ Failure, Success }
import org.specs2.mutable.Specification
import OperationError._
import Inspection.Decision.{Retry, Stop, Fail}
import TestData._
class TransactionStartInspectionSpec extends Specification {
val inspection = TransactionStartInspection(transactionStart).pf
"TransactionStartInspection" should {
"handle TransactionStartCompleted" in {
inspection(Success(transactionStartCompleted)) mustEqual Stop
}
"handle CommitTimeout" in {
inspection(Failure(CommitTimeout)) mustEqual Retry
}
"handle ForwardTimeout" in {
inspection(Failure(ForwardTimeout)) mustEqual Retry
}
"handle PrepareTimeout" in {
inspection(Failure(PrepareTimeout)) mustEqual Retry
}
"handle WrongExpectedVersion" in {
inspection(Failure(WrongExpectedVersion)) must beLike {
case Fail(_: WrongExpectedVersionException) => ok
}
}
"handle StreamDeleted" in {
inspection(Failure(StreamDeleted)) must beLike {
case Fail(_: StreamDeletedException) => ok
}
}
"handle InvalidTransaction" in {
inspection(Failure(InvalidTransaction)) mustEqual Fail(InvalidTransactionException)
}
"handle AccessDenied" in {
inspection(Failure(AccessDenied)) must beLike {
case Fail(_: AccessDeniedException) => ok
}
}
}
}
| bsd-3-clause |
Fryday80/SRzA | module/Application/src/Application/Factory/DefaultTableGatewayFactory.php | 1295 | <?php
namespace Application\Factory;
use Exception;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class DefaultTableGatewayFactory implements AbstractFactoryInterface
{
/**
* Determine if we can create a service with name
*
* @param ServiceLocatorInterface $serviceLocator
* @param $name
* @param $requestedName
* @return bool
*/
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$nameSpace = explode( '\\', $requestedName);
return (isset($nameSpace[1]) && $nameSpace[1] == 'Model' )? true: false;
}
/**
* Create service with name
*
* @param ServiceLocatorInterface $serviceLocator
* @param $name
* @param $requestedName
* @return mixed
* @throws Exception
*/
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$nameSpace = explode( '\\', $requestedName);
$nameSpace [3] = $nameSpace[2];
$nameSpace[2] = 'Tables';
$requestedName = implode('\\', $nameSpace);
$adapter = $serviceLocator->get('Zend\Db\Adapter\Adapter');
$new = new $requestedName($adapter);
return $new;
}
} | bsd-3-clause |
django-leonardo/django-leonardo | leonardo/module/web/widget/feedreader/models.py | 888 | # -#- coding: utf-8 -#-
import feedparser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import ContentProxyWidgetMixin
from leonardo.module.web.models import Widget
from leonardo.module.web.widgets.mixins import JSONContentMixin
from leonardo.module.web.widgets.mixins import ListWidgetMixin
class FeedReaderWidget(Widget, JSONContentMixin, ContentProxyWidgetMixin,
ListWidgetMixin):
max_items = models.IntegerField(_('max. items'), default=5)
class Meta:
abstract = True
verbose_name = _("feed reader")
verbose_name_plural = _('feed readers')
def update_cache_data(self, save=True):
pass
def get_data(self):
feed = feedparser.parse(self.source_address)
entries = feed['entries'][:self.max_items]
return entries
| bsd-3-clause |
sfalkner/random_forest_run | docs/regression.html | 199001 | <!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Regression — pyrfr 0.5 documentation</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.5',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</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>
<link rel="top" title="pyrfr 0.5 documentation" href="index.html" />
<link rel="prev" title="About pyRFR" href="installation.html" />
</head>
<body role="document">
<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="installation.html" title="About pyRFR"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">pyrfr 0.5 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="module-pyrfr.regression">
<span id="regression"></span><h1>Regression<a class="headerlink" href="#module-pyrfr.regression" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="pyrfr.regression.SwigPyIterator">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">SwigPyIterator</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.advance">
<code class="descname">advance</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.advance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.advance" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.copy">
<code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.copy"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.copy" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.decr">
<code class="descname">decr</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.decr"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.decr" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.distance">
<code class="descname">distance</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.distance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.distance" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.equal">
<code class="descname">equal</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.equal"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.equal" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.incr">
<code class="descname">incr</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.incr"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.incr" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.next">
<code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.next"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.next" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.previous">
<code class="descname">previous</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.previous"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.previous" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.SwigPyIterator.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.SwigPyIterator.value">
<code class="descname">value</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#SwigPyIterator.value"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.SwigPyIterator.value" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.base_tree">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">base_tree</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.base_tree.depth">
<code class="descname">depth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.depth"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.depth" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>depth() const =0 -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.fit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id1"><span class="problematic" id="id2">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data,</dt>
<dd>rfr::trees::tree_options< num_t, response_t, index_t > tree_opts, const
std::vector< num_t > &sample_weights, rng_type &rng)=0`</dd>
</dl>
<p>fits a (possibly randomized) decision tree to a subset of the data</p>
<p>At each node, if it is ‘splitworthy’, a random subset of all features is
considered for the split. Depending on the split_type provided, greedy or
randomized choices can be made. Just make sure the max_features in tree_opts to
a number smaller than the number of features!</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the container holding the training data</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>tree_opts</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a tree_options opject that controls certain aspects of “growing” the tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_weights</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">vector containing the weights of all datapoints, can be used for subsampling
(no checks are done here!)</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a (pseudo) random number generator</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.leaf_entries">
<code class="descname">leaf_entries</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.leaf_entries"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.leaf_entries" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id3"><span class="problematic" id="id4">`</span></a>leaf_entries(const std::vector< num_t > &feature_vector) const =0 -></dt>
<dd>std::vector< response_t > const &`</dd>
</dl>
<p>returns all response values in the leaf into which the given feature vector
falls</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_vector</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">an array containing a valid (in terms of size and values!) feature vector</p>
</dd>
</dl>
</li>
</ul>
<p>std::vector<response_t> all response values in that leaf</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.number_of_leafs">
<code class="descname">number_of_leafs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.number_of_leafs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.number_of_leafs" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>number_of_leafs() const =0 -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.number_of_nodes">
<code class="descname">number_of_nodes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.number_of_nodes"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.number_of_nodes" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>number_of_nodes() const =0 -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.predict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const =0 -> response_t</cite></p>
<p>predicts the response value for a single feature vector</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_vector</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">an array containing a valid (in terms of size and values!) feature vector</p>
</dd>
</dl>
</li>
</ul>
<p>num_t the prediction of the response value (usually the mean of all responses in
the corresponding leaf)</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.base_tree.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#base_tree.save_latex_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.base_tree.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const char *filename) const =0</cite></p>
<p>creates a LaTeX document visualizing the tree</p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.base_tree.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.base_tree.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.binary_full_tree_rss">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">binary_full_tree_rss</code><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#pyrfr.regression.base_tree" title="pyrfr.regression.base_tree"><code class="xref py py-class docutils literal"><span class="pre">pyrfr.regression.base_tree</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.check_split_fractions">
<code class="descname">check_split_fractions</code><span class="sig-paren">(</span><em>epsilon=1e-06</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.check_split_fractions"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.check_split_fractions" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>check_split_fractions(num_t epsilon=1e-6) const -> bool</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.depth">
<code class="descname">depth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.depth"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.depth" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>depth() const -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.find_leaf_index">
<code class="descname">find_leaf_index</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.find_leaf_index"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.find_leaf_index" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>find_leaf_index(const std::vector< num_t > &feature_vector) const -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>data</em>, <em>tree_opts</em>, <em>sample_weights</em>, <em>rng</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.fit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id5"><span class="problematic" id="id6">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data,</dt>
<dd>rfr::trees::tree_options< num_t, response_t, index_t > tree_opts, const
std::vector< num_t > &sample_weights, rng_type &rng)`</dd>
</dl>
<p>fits a randomized decision tree to a subset of the data</p>
<p>At each node, if it is ‘splitworthy’, a random subset of all features is
considered for the split. Depending on the split_type provided, greedy or
randomized choices can be made. Just make sure the max_features in tree_opts to
a number smaller than the number of features!</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the container holding the training data</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>tree_opts</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a tree_options object that controls certain aspects of “growing” the tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_weights</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">vector containing the weights of all allowed datapoints (set to individual
entries to zero for subsampling), no checks are done here!</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the random number generator to be used</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.get_leaf">
<code class="descname">get_leaf</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.get_leaf"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.get_leaf" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id7"><span class="problematic" id="id8">`</span></a>get_leaf(const std::vector< num_t > &feature_vector) const -> const node_type</dt>
<dd>&`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.leaf_entries">
<code class="descname">leaf_entries</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.leaf_entries"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.leaf_entries" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id9"><span class="problematic" id="id10">`</span></a>leaf_entries(const std::vector< num_t > &feature_vector) const -> std::vector<</dt>
<dd>response_t > const &`</dd>
</dl>
<p>returns all response values in the leaf into which the given feature vector
falls</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_vector</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">an array containing a valid (in terms of size and values!) feature vector</p>
</dd>
</dl>
</li>
</ul>
<p>std::vector<response_t> all response values in that leaf</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.leaf_statistic">
<code class="descname">leaf_statistic</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.leaf_statistic"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.leaf_statistic" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id11"><span class="problematic" id="id12">`</span></a>leaf_statistic(const std::vector< num_t > &feature_vector) const -></dt>
<dd>rfr::util::weighted_running_statistics< num_t > const &`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.marginalized_mean_prediction">
<code class="descname">marginalized_mean_prediction</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>node_index=0</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.marginalized_mean_prediction"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.marginalized_mean_prediction" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id13"><span class="problematic" id="id14">`</span></a>marginalized_mean_prediction(const std::vector< num_t > &feature_vector,</dt>
<dd>index_t node_index=0) const -> num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.number_of_leafs">
<code class="descname">number_of_leafs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.number_of_leafs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.number_of_leafs" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>number_of_leafs() const -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.number_of_nodes">
<code class="descname">number_of_nodes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.number_of_nodes"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.number_of_nodes" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>number_of_nodes() const -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.partition">
<code class="descname">partition</code><span class="sig-paren">(</span><em>pcs</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.partition"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.partition" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id15"><span class="problematic" id="id16">`</span></a>partition(std::vector< std::vector< num_t > > pcs) const -> std::vector<</dt>
<dd>std::vector< std::vector< num_t > > >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.partition_recursor">
<code class="descname">partition_recursor</code><span class="sig-paren">(</span><em>the_partition</em>, <em>subspace</em>, <em>node_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.partition_recursor"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.partition_recursor" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id17"><span class="problematic" id="id18">`</span></a>partition_recursor(std::vector< std::vector< std::vector< num_t > > ></dt>
<dd>&the_partition, std::vector< std::vector< num_t > > &subspace, num_t
node_index) const`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.predict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const -> response_t</cite></p>
<p>predicts the response value for a single feature vector</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_vector</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">an array containing a valid (in terms of size and values!) feature vector</p>
</dd>
</dl>
</li>
</ul>
<p>num_t the prediction of the response value (usually the mean of all responses in
the corresponding leaf)</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.print_info">
<code class="descname">print_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.print_info"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.print_info" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_info() const</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.pseudo_downdate">
<code class="descname">pseudo_downdate</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.pseudo_downdate"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.pseudo_downdate" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id19"><span class="problematic" id="id20">`</span></a>pseudo_downdate(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.pseudo_update">
<code class="descname">pseudo_update</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.pseudo_update"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.pseudo_update" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id21"><span class="problematic" id="id22">`</span></a>pseudo_update(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.save_latex_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const char *filename) const</cite></p>
<p>a visualization by generating a LaTeX document that can be compiled</p>
<ul>
<li><dl class="first docutils">
<dt><cite>filename</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">Name of the file that will be used. Note that any existing file will be
silently overwritten!</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.binary_full_tree_rss.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_full_tree_rss.total_weight_in_subtree">
<code class="descname">total_weight_in_subtree</code><span class="sig-paren">(</span><em>node_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_full_tree_rss.total_weight_in_subtree"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_full_tree_rss.total_weight_in_subtree" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>total_weight_in_subtree(index_t node_index) const -> num_t</cite></p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.binary_rss_forest">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">binary_rss_forest</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<ul class="simple">
<li><cite>options</cite> : <cite>forest_options< num_t, response_t, index_t ></cite></li>
</ul>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.all_leaf_values">
<code class="descname">all_leaf_values</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.all_leaf_values"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.all_leaf_values" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id23"><span class="problematic" id="id24">`</span></a>all_leaf_values(const std::vector< num_t > &feature_vector) const -></dt>
<dd>std::vector< std::vector< num_t > >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.ascii_string_representation">
<code class="descname">ascii_string_representation</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.ascii_string_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.ascii_string_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>ascii_string_representation() -> std::string</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.covariance">
<code class="descname">covariance</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.covariance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.covariance" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id25"><span class="problematic" id="id26">`</span></a>covariance(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>data</em>, <em>rng</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.fit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id27"><span class="problematic" id="id28">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data,</dt>
<dd>rng_type &rng)`</dd>
</dl>
<p>growing the random forest for a given data set</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a filled data container</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the random number generator to be used</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.kernel">
<code class="descname">kernel</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.kernel"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.kernel" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id29"><span class="problematic" id="id30">`</span></a>kernel(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.load_from_ascii_string">
<code class="descname">load_from_ascii_string</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.load_from_ascii_string"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.load_from_ascii_string" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_ascii_string(std::string const &str)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.load_from_binary_file">
<code class="descname">load_from_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.load_from_binary_file"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.load_from_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.num_trees">
<code class="descname">num_trees</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.num_trees"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.num_trees" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_trees() -> unsigned int</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.binary_rss_forest.options">
<code class="descname">options</code><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.options" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.out_of_bag_error">
<code class="descname">out_of_bag_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.out_of_bag_error"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.out_of_bag_error" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>out_of_bag_error() -> num_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.predict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const -> response_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.predict_mean_var">
<code class="descname">predict_mean_var</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>weighted_data=False</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.predict_mean_var"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.predict_mean_var" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id31"><span class="problematic" id="id32">`</span></a>predict_mean_var(const std::vector< num_t > &feature_vector, bool</dt>
<dd>weighted_data=false) -> std::pair< num_t, num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.print_info">
<code class="descname">print_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.print_info"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.print_info" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_info()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.pseudo_downdate">
<code class="descname">pseudo_downdate</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.pseudo_downdate"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.pseudo_downdate" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id33"><span class="problematic" id="id34">`</span></a>pseudo_downdate(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.pseudo_update">
<code class="descname">pseudo_update</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.pseudo_update"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.pseudo_update" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id35"><span class="problematic" id="id36">`</span></a>pseudo_update(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename_template</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.save_latex_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const std::string filename_template)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.binary_rss_forest.save_to_binary_file">
<code class="descname">save_to_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#binary_rss_forest.save_to_binary_file"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.save_to_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_to_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.binary_rss_forest.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.binary_rss_forest.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.data_base">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">data_base</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<p>The interface for any data container with the minimal functionality.</p>
<p>C++ includes: data_container.hpp</p>
<dl class="method">
<dt id="pyrfr.regression.data_base.add_data_point">
<code class="descname">add_data_point</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.add_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.add_data_point" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id37"><span class="problematic" id="id38">`</span></a>add_data_point(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)=0`</dd>
</dl>
<p>method to add a single data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>features</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a vector containing the features</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>response</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the corresponding response value</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>weight</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the weight of the data point</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.feature">
<code class="descname">feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>feature(index_t feature_index, index_t sample_index) const =0 -> num_t</cite></p>
<p>Function for accessing a single feature value, consistency checks might be
omitted for performance.</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.features">
<code class="descname">features</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_indices</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.features" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id39"><span class="problematic" id="id40">`</span></a>features(index_t feature_index, const std::vector< index_t > &sample_indices)</dt>
<dd>const =0 -> std::vector< num_t >`</dd>
</dl>
<p>member function for accessing the feature values of multiple data points at
once, consistency checks might be omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_indices</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The indices of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.get_bounds_of_feature">
<code class="descname">get_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.get_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.get_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id41"><span class="problematic" id="id42">`</span></a>get_bounds_of_feature(index_t feature_index) const =0 -> std::pair< num_t,</dt>
<dd>num_t >`</dd>
</dl>
<p>query the allowed interval for a feature; applies only to continuous variables</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>std::pair<num_t,num_t> interval of allowed values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.get_type_of_feature">
<code class="descname">get_type_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.get_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.get_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_feature(index_t feature_index) const =0 -> index_t</cite></p>
<p>query the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>int type of the feature: 0 - numerical value (float or int); n>0 - categorical
value with n different values {0,1,...,n-1}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.get_type_of_response">
<code class="descname">get_type_of_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.get_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.get_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_response() const =0 -> index_t</cite></p>
<p>query the type of the response</p>
<p>index_t type of the response: 0 - numerical value (float or int); n>0 -
categorical value with n different values {0,1,...,n-1}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.num_data_points">
<code class="descname">num_data_points</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.num_data_points"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.num_data_points" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_data_points() const =0 -> index_t</cite></p>
<p>the number of data points in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.num_features">
<code class="descname">num_features</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.num_features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.num_features" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_features() const =0 -> index_t</cite></p>
<p>the number of features of every datapoint in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.response">
<code class="descname">response</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>response(index_t sample_index) const =0 -> response_t</cite></p>
<p>member function to query a single response value, consistency checks might be
omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the response of which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the response value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.retrieve_data_point">
<code class="descname">retrieve_data_point</code><span class="sig-paren">(</span><em>index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.retrieve_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.retrieve_data_point" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>retrieve_data_point(index_t index) const =0 -> std::vector< num_t ></cite></p>
<p>method to retrieve a data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">index of the datapoint to extract</p>
</dd>
</dl>
</li>
</ul>
<p>std::vector<num_t> the features of the data point</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.set_bounds_of_feature">
<code class="descname">set_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>min</em>, <em>max</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.set_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.set_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_bounds_of_feature(index_t feature_index, num_t min, num_t max)=0</cite></p>
<p>specifies the interval of allowed values for a feature</p>
<p>To marginalize out certain feature dimensions using non-i.i.d. data, the
numerical bounds on each variable have to be known. This only applies to
numerical features.</p>
<p>Note: The forest will not check if a datapoint is consistent with the specified
bounds!</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">feature_index the index of the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the smallest value for the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the largest value for the feature</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.set_type_of_feature">
<code class="descname">set_type_of_feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>feature_type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.set_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.set_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_feature(index_t feature_index, index_t feature_type)=0</cite></p>
<p>specifying the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature whose type is specified</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>feature_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.set_type_of_response">
<code class="descname">set_type_of_response</code><span class="sig-paren">(</span><em>response_type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.set_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.set_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_response(index_t response_type)=0</cite></p>
<p>specifying the type of the response</p>
<ul>
<li><dl class="first docutils">
<dt><cite>response_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.data_base.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.data_base.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.data_base.weight">
<code class="descname">weight</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#data_base.weight"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.data_base.weight" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>weight(index_t sample_index) const =0 -> num_t</cite></p>
<p>function to access the weight attributed to a single data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the weigth of that sample</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.default_data_container">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">default_data_container</code><span class="sig-paren">(</span><em>num_f</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#pyrfr.regression.data_base" title="pyrfr.regression.data_base"><code class="xref py py-class docutils literal"><span class="pre">pyrfr.regression.data_base</span></code></a></p>
<p>A data container for mostly continuous data.</p>
<p>It might happen that only a small fraction of all features is categorical. In
that case it would be wasteful to store the type of every feature separately.
Instead, this data_container only stores the non-continuous ones in a hash-map.</p>
<p>C++ includes: default_data_container.hpp</p>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.add_data_point">
<code class="descname">add_data_point</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight=1</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.add_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.add_data_point" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id43"><span class="problematic" id="id44">`</span></a>add_data_point(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight=1)`</dd>
</dl>
<p>method to add a single data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>features</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a vector containing the features</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>response</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the corresponding response value</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>weight</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the weight of the data point</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.check_consistency">
<code class="descname">check_consistency</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.check_consistency"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.check_consistency" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>check_consistency() -> bool</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.feature">
<code class="descname">feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>feature(index_t feature_index, index_t sample_index) const -> num_t</cite></p>
<p>Function for accessing a single feature value, consistency checks might be
omitted for performance.</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.features">
<code class="descname">features</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_indices</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.features" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id45"><span class="problematic" id="id46">`</span></a>features(index_t feature_index, const std::vector< index_t > &sample_indices)</dt>
<dd>const -> std::vector< num_t >`</dd>
</dl>
<p>member function for accessing the feature values of multiple data points at
once, consistency checks might be omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_indices</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The indices of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.get_bounds_of_feature">
<code class="descname">get_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.get_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.get_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id47"><span class="problematic" id="id48">`</span></a>get_bounds_of_feature(index_t feature_index) const -> std::pair< num_t, num_t</dt>
<dd>>`</dd>
</dl>
<p>query the allowed interval for a feature; applies only to continuous variables</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>std::pair<num_t,num_t> interval of allowed values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.get_min_max_of_feature">
<code class="descname">get_min_max_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.get_min_max_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.get_min_max_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id49"><span class="problematic" id="id50">`</span></a>get_min_max_of_feature(index_t feature_index) const -> std::pair< num_t, num_t</dt>
<dd>>`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.get_type_of_feature">
<code class="descname">get_type_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.get_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.get_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_feature(index_t feature_index) const -> index_t</cite></p>
<p>query the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>int type of the feature: 0 - numerical value (float or int); n>0 - categorical
value with n different values {0,1,...,n-1}</p>
<p>As most features are assumed to be numerical, it is actually beneficial to store
only the categorical exceptions in a hash-map. Type = 0 means continuous, and
Type = n >= 1 means categorical with options in {0, n-1}.</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>int type of the feature: 0 - numerical value (float or int); n>0 - categorical
value with n different values {1,2,...,n}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.get_type_of_response">
<code class="descname">get_type_of_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.get_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.get_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_response() const -> index_t</cite></p>
<p>query the type of the response</p>
<p>index_t type of the response: 0 - numerical value (float or int); n>0 -
categorical value with n different values {0,1,...,n-1}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.guess_bounds_from_data">
<code class="descname">guess_bounds_from_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.guess_bounds_from_data"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.guess_bounds_from_data" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>guess_bounds_from_data()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.import_csv_files">
<code class="descname">import_csv_files</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.import_csv_files"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.import_csv_files" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id51"><span class="problematic" id="id52">`</span></a>import_csv_files(const std::string &feature_file, const std::string</dt>
<dd>&response_file, std::string weight_file=””) -> int`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.init_protected">
<code class="descname">init_protected</code><span class="sig-paren">(</span><em>num_f</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.init_protected"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.init_protected" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>init_protected(index_t num_f)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.num_data_points">
<code class="descname">num_data_points</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.num_data_points"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.num_data_points" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_data_points() const -> index_t</cite></p>
<p>the number of data points in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.num_features">
<code class="descname">num_features</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.num_features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.num_features" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_features() const -> index_t</cite></p>
<p>the number of features of every datapoint in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.print_data">
<code class="descname">print_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.print_data"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.print_data" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_data()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.response">
<code class="descname">response</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>response(index_t sample_index) const -> response_t</cite></p>
<p>member function to query a single response value, consistency checks might be
omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the response of which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the response value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.retrieve_data_point">
<code class="descname">retrieve_data_point</code><span class="sig-paren">(</span><em>index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.retrieve_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.retrieve_data_point" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>retrieve_data_point(index_t index) const -> std::vector< num_t ></cite></p>
<p>method to retrieve a data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">index of the datapoint to extract</p>
</dd>
</dl>
</li>
</ul>
<p>std::vector<num_t> the features of the data point</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.set_bounds_of_feature">
<code class="descname">set_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>min</em>, <em>max</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.set_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.set_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_bounds_of_feature(index_t feature_index, num_t min, num_t max)</cite></p>
<p>specifies the interval of allowed values for a feature</p>
<p>To marginalize out certain feature dimensions using non-i.i.d. data, the
numerical bounds on each variable have to be known. This only applies to
numerical features.</p>
<p>Note: The forest will not check if a datapoint is consistent with the specified
bounds!</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">feature_index the index of the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the smallest value for the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the largest value for the feature</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.set_type_of_feature">
<code class="descname">set_type_of_feature</code><span class="sig-paren">(</span><em>index</em>, <em>type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.set_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.set_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_feature(index_t index, index_t type)</cite></p>
<p>specifying the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature whose type is specified</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>feature_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.set_type_of_response">
<code class="descname">set_type_of_response</code><span class="sig-paren">(</span><em>resp_t</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.set_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.set_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_response(index_t resp_t)</cite></p>
<p>specifying the type of the response</p>
<ul>
<li><dl class="first docutils">
<dt><cite>response_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.default_data_container.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.default_data_container.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container.weight">
<code class="descname">weight</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container.weight"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container.weight" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>weight(index_t sample_index) const -> num_t</cite></p>
<p>function to access the weight attributed to a single data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the weigth of that sample</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.default_data_container_with_instances">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">default_data_container_with_instances</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#pyrfr.regression.data_base" title="pyrfr.regression.data_base"><code class="xref py py-class docutils literal"><span class="pre">pyrfr.regression.data_base</span></code></a></p>
<p>A data container for mostly continuous data with instances.</p>
<p>Similar to the mostly_continuous_data container, but with the capability to
handle instance features.</p>
<p>C++ includes: default_data_container_with_instances.hpp</p>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.add_configuration">
<code class="descname">add_configuration</code><span class="sig-paren">(</span><em>config_features</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.add_configuration"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.add_configuration" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>add_configuration(const std::vector< num_t > &config_features) -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.add_data_point">
<code class="descname">add_data_point</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.add_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.add_data_point" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id53"><span class="problematic" id="id54">`</span></a>add_data_point(index_t config_index, index_t instance_index, response_t r,</dt>
<dd>num_t weight=1)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.add_instance">
<code class="descname">add_instance</code><span class="sig-paren">(</span><em>instance_features</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.add_instance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.add_instance" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>add_instance(const std::vector< num_t > instance_features) -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.check_consistency">
<code class="descname">check_consistency</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.check_consistency"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.check_consistency" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>check_consistency()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.feature">
<code class="descname">feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>feature(index_t feature_index, index_t sample_index) const -> num_t</cite></p>
<p>Function for accessing a single feature value, consistency checks might be
omitted for performance.</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.features">
<code class="descname">features</code><span class="sig-paren">(</span><em>feature_index</em>, <em>sample_indices</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.features" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id55"><span class="problematic" id="id56">`</span></a>features(index_t feature_index, const std::vector< index_t > &sample_indices)</dt>
<dd>const -> std::vector< num_t >`</dd>
</dl>
<p>member function for accessing the feature values of multiple data points at
once, consistency checks might be omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The index of the feature requested</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>sample_indices</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">The indices of the data point.</p>
</dd>
</dl>
</li>
</ul>
<p>the stored values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_bounds_of_feature">
<code class="descname">get_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id57"><span class="problematic" id="id58">`</span></a>get_bounds_of_feature(index_t feature_index) const -> std::pair< num_t, num_t</dt>
<dd>>`</dd>
</dl>
<p>query the allowed interval for a feature; applies only to continuous variables</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>std::pair<num_t,num_t> interval of allowed values</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_configuration_set">
<code class="descname">get_configuration_set</code><span class="sig-paren">(</span><em>configuration_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_configuration_set"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_configuration_set" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_configuration_set(num_t configuration_index) -> std::vector< num_t ></cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_features_by_configuration_and_instance">
<code class="descname">get_features_by_configuration_and_instance</code><span class="sig-paren">(</span><em>configuration_index</em>, <em>instance_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_features_by_configuration_and_instance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_features_by_configuration_and_instance" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id59"><span class="problematic" id="id60">`</span></a>get_features_by_configuration_and_instance(num_t configuration_index, num_t</dt>
<dd>instance_index) -> std::vector< num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_instance_set">
<code class="descname">get_instance_set</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_instance_set"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_instance_set" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_instance_set() -> std::vector< num_t ></cite></p>
<p>method to get instance as set_feature for
predict_mean_var_of_mean_response_on_set method in regression forest</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_type_of_feature">
<code class="descname">get_type_of_feature</code><span class="sig-paren">(</span><em>feature_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_feature(index_t feature_index) const -> index_t</cite></p>
<p>query the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature</p>
</dd>
</dl>
</li>
</ul>
<p>int type of the feature: 0 - numerical value (float or int); n>0 - categorical
value with n different values {0,1,...,n-1}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.get_type_of_response">
<code class="descname">get_type_of_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.get_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.get_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_type_of_response() const -> index_t</cite></p>
<p>query the type of the response</p>
<p>index_t type of the response: 0 - numerical value (float or int); n>0 -
categorical value with n different values {0,1,...,n-1}</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.num_configurations">
<code class="descname">num_configurations</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.num_configurations"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.num_configurations" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_configurations() -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.num_data_points">
<code class="descname">num_data_points</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.num_data_points"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.num_data_points" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_data_points() const -> index_t</cite></p>
<p>the number of data points in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.num_features">
<code class="descname">num_features</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.num_features"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.num_features" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_features() const -> index_t</cite></p>
<p>the number of features of every datapoint in the container</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.num_instances">
<code class="descname">num_instances</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.num_instances"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.num_instances" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_instances() -> index_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.response">
<code class="descname">response</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>response(index_t sample_index) const -> response_t</cite></p>
<p>member function to query a single response value, consistency checks might be
omitted for performance</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the response of which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the response value</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.retrieve_data_point">
<code class="descname">retrieve_data_point</code><span class="sig-paren">(</span><em>index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.retrieve_data_point"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.retrieve_data_point" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>retrieve_data_point(index_t index) const -> std::vector< num_t ></cite></p>
<p>method to retrieve a data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">index of the datapoint to extract</p>
</dd>
</dl>
</li>
</ul>
<p>std::vector<num_t> the features of the data point</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.set_bounds_of_feature">
<code class="descname">set_bounds_of_feature</code><span class="sig-paren">(</span><em>feature_index</em>, <em>min</em>, <em>max</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.set_bounds_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.set_bounds_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_bounds_of_feature(index_t feature_index, num_t min, num_t max)</cite></p>
<p>specifies the interval of allowed values for a feature</p>
<p>To marginalize out certain feature dimensions using non-i.i.d. data, the
numerical bounds on each variable have to be known. This only applies to
numerical features.</p>
<p>Note: The forest will not check if a datapoint is consistent with the specified
bounds!</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">feature_index the index of the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the smallest value for the feature</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the largest value for the feature</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.set_type_of_configuration_feature">
<code class="descname">set_type_of_configuration_feature</code><span class="sig-paren">(</span><em>index</em>, <em>type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.set_type_of_configuration_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.set_type_of_configuration_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_configuration_feature(index_t index, index_t type)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.set_type_of_feature">
<code class="descname">set_type_of_feature</code><span class="sig-paren">(</span><em>index</em>, <em>type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.set_type_of_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.set_type_of_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_feature(index_t index, index_t type)</cite></p>
<p>specifying the type of a feature</p>
<ul>
<li><dl class="first docutils">
<dt><cite>feature_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the index of the feature whose type is specified</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>feature_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.set_type_of_instance_feature">
<code class="descname">set_type_of_instance_feature</code><span class="sig-paren">(</span><em>index</em>, <em>type</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.set_type_of_instance_feature"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.set_type_of_instance_feature" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_instance_feature(index_t index, index_t type)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.set_type_of_response">
<code class="descname">set_type_of_response</code><span class="sig-paren">(</span><em>resp_t</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.set_type_of_response"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.set_type_of_response" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_type_of_response(index_t resp_t)</cite></p>
<p>specifying the type of the response</p>
<ul>
<li><dl class="first docutils">
<dt><cite>response_type</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the actual type (0 - numerical, value >0 catergorical with values from
{0,1,...value-1}</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.default_data_container_with_instances.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.default_data_container_with_instances.weight">
<code class="descname">weight</code><span class="sig-paren">(</span><em>sample_index</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_data_container_with_instances.weight"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_data_container_with_instances.weight" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>weight(index_t sample_index) const -> num_t</cite></p>
<p>function to access the weight attributed to a single data point</p>
<ul>
<li><dl class="first docutils">
<dt><cite>sample_index</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">which data point</p>
</dd>
</dl>
</li>
</ul>
<p>the weigth of that sample</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.default_random_engine">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">default_random_engine</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_random_engine"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_random_engine" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.default_random_engine.seed">
<code class="descname">seed</code><span class="sig-paren">(</span><em>arg2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#default_random_engine.seed"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.default_random_engine.seed" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.default_random_engine.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.default_random_engine.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.fanova_forest">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">fanova_forest</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#pyrfr.regression.fanova_forest_prototype" title="pyrfr.regression.fanova_forest_prototype"><code class="xref py py-class docutils literal"><span class="pre">pyrfr.regression.fanova_forest_prototype</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.all_leaf_values">
<code class="descname">all_leaf_values</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.all_leaf_values" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id61"><span class="problematic" id="id62">`</span></a>all_leaf_values(const std::vector< num_t > &feature_vector) const -></dt>
<dd>std::vector< std::vector< num_t > >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.all_split_values">
<code class="descname">all_split_values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.all_split_values"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.all_split_values" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>all_split_values() -> std::vector< std::vector< std::vector< num_t > > ></cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.ascii_string_representation">
<code class="descname">ascii_string_representation</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.ascii_string_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>ascii_string_representation() -> std::string</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.covariance">
<code class="descname">covariance</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.covariance" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id63"><span class="problematic" id="id64">`</span></a>covariance(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>data</em>, <em>rng</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.fit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id65"><span class="problematic" id="id66">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data, rng_t</dt>
<dd>&rng)`</dd>
</dl>
<p>growing the random forest for a given data set</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a filled data container</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the random number generator to be used</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.get_cutoffs">
<code class="descname">get_cutoffs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.get_cutoffs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.get_cutoffs" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_cutoffs() -> std::pair< num_t, num_t ></cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.get_trees_total_variances">
<code class="descname">get_trees_total_variances</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.get_trees_total_variances"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.get_trees_total_variances" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>get_trees_total_variances() -> std::vector< num_t ></cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.kernel">
<code class="descname">kernel</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.kernel" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id67"><span class="problematic" id="id68">`</span></a>kernel(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.load_from_ascii_string">
<code class="descname">load_from_ascii_string</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.load_from_ascii_string" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_ascii_string(std::string const &str)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.load_from_binary_file">
<code class="descname">load_from_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.load_from_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.marginal_mean_prediction">
<code class="descname">marginal_mean_prediction</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.marginal_mean_prediction"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.marginal_mean_prediction" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>marginal_mean_prediction(const std::vector< num_t > &feature_vector) -> num_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.marginal_mean_variance_prediction">
<code class="descname">marginal_mean_variance_prediction</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.marginal_mean_variance_prediction"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.marginal_mean_variance_prediction" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id69"><span class="problematic" id="id70">`</span></a>marginal_mean_variance_prediction(const std::vector< num_t > &feature_vector)</dt>
<dd>-> std::pair< num_t, num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.marginal_prediction_stat_of_tree">
<code class="descname">marginal_prediction_stat_of_tree</code><span class="sig-paren">(</span><em>tree_index</em>, <em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.marginal_prediction_stat_of_tree"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.marginal_prediction_stat_of_tree" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id71"><span class="problematic" id="id72">`</span></a>marginal_prediction_stat_of_tree(index_t tree_index, const std::vector< num_t ></dt>
<dd>&feature_vector) -> rfr::util::weighted_running_statistics< num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.num_trees">
<code class="descname">num_trees</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.num_trees" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_trees() -> unsigned int</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.fanova_forest.options">
<code class="descname">options</code><a class="headerlink" href="#pyrfr.regression.fanova_forest.options" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.out_of_bag_error">
<code class="descname">out_of_bag_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.out_of_bag_error" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>out_of_bag_error() -> num_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.precompute_marginals">
<code class="descname">precompute_marginals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.precompute_marginals"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.precompute_marginals" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>precompute_marginals()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const -> response_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.predict_mean_var">
<code class="descname">predict_mean_var</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>weighted_data=False</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.predict_mean_var" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id73"><span class="problematic" id="id74">`</span></a>predict_mean_var(const std::vector< num_t > &feature_vector, bool</dt>
<dd>weighted_data=false) -> std::pair< num_t, num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.print_info">
<code class="descname">print_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.print_info" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_info()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.pseudo_downdate">
<code class="descname">pseudo_downdate</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.pseudo_downdate" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id75"><span class="problematic" id="id76">`</span></a>pseudo_downdate(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.pseudo_update">
<code class="descname">pseudo_update</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.pseudo_update" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id77"><span class="problematic" id="id78">`</span></a>pseudo_update(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename_template</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const std::string filename_template)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.save_to_binary_file">
<code class="descname">save_to_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.fanova_forest.save_to_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_to_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest.set_cutoffs">
<code class="descname">set_cutoffs</code><span class="sig-paren">(</span><em>lower</em>, <em>upper</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest.set_cutoffs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest.set_cutoffs" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_cutoffs(num_t lower, num_t upper)</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.fanova_forest.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.fanova_forest.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.fanova_forest_prototype">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">fanova_forest_prototype</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<ul class="simple">
<li><cite>options</cite> : <cite>forest_options< num_t, response_t, index_t ></cite></li>
</ul>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.all_leaf_values">
<code class="descname">all_leaf_values</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.all_leaf_values"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.all_leaf_values" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id79"><span class="problematic" id="id80">`</span></a>all_leaf_values(const std::vector< num_t > &feature_vector) const -></dt>
<dd>std::vector< std::vector< num_t > >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.ascii_string_representation">
<code class="descname">ascii_string_representation</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.ascii_string_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.ascii_string_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>ascii_string_representation() -> std::string</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.covariance">
<code class="descname">covariance</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.covariance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.covariance" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id81"><span class="problematic" id="id82">`</span></a>covariance(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>data</em>, <em>rng</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.fit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id83"><span class="problematic" id="id84">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data,</dt>
<dd>rng_type &rng)`</dd>
</dl>
<p>growing the random forest for a given data set</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a filled data container</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the random number generator to be used</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.kernel">
<code class="descname">kernel</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.kernel"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.kernel" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id85"><span class="problematic" id="id86">`</span></a>kernel(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.load_from_ascii_string">
<code class="descname">load_from_ascii_string</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.load_from_ascii_string"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.load_from_ascii_string" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_ascii_string(std::string const &str)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.load_from_binary_file">
<code class="descname">load_from_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.load_from_binary_file"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.load_from_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.num_trees">
<code class="descname">num_trees</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.num_trees"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.num_trees" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_trees() -> unsigned int</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.fanova_forest_prototype.options">
<code class="descname">options</code><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.options" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.out_of_bag_error">
<code class="descname">out_of_bag_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.out_of_bag_error"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.out_of_bag_error" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>out_of_bag_error() -> num_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.predict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const -> response_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.predict_mean_var">
<code class="descname">predict_mean_var</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>weighted_data=False</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.predict_mean_var"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.predict_mean_var" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id87"><span class="problematic" id="id88">`</span></a>predict_mean_var(const std::vector< num_t > &feature_vector, bool</dt>
<dd>weighted_data=false) -> std::pair< num_t, num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.print_info">
<code class="descname">print_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.print_info"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.print_info" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_info()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.pseudo_downdate">
<code class="descname">pseudo_downdate</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.pseudo_downdate"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.pseudo_downdate" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id89"><span class="problematic" id="id90">`</span></a>pseudo_downdate(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.pseudo_update">
<code class="descname">pseudo_update</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.pseudo_update"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.pseudo_update" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id91"><span class="problematic" id="id92">`</span></a>pseudo_update(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename_template</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.save_latex_representation"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const std::string filename_template)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.fanova_forest_prototype.save_to_binary_file">
<code class="descname">save_to_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#fanova_forest_prototype.save_to_binary_file"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.save_to_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_to_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.fanova_forest_prototype.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.fanova_forest_prototype.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.forest_opts">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">forest_opts</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#forest_opts"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.forest_opts" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<ul>
<li><dl class="first docutils">
<dt><cite>num_trees</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_t</cite> </span></dt>
<dd><p class="first last">number of trees in the forest</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>num_data_points_per_tree</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_t</cite> </span></dt>
<dd><p class="first last">number of datapoints used in each tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>do_bootstrapping</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>bool</cite> </span></dt>
<dd><p class="first last">flag to toggle bootstrapping</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>compute_oob_error</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>bool</cite> </span></dt>
<dd><p class="first last">flag to enable/disable computing the out-of-bag error</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>tree_opts</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>rfr::trees::tree_options< num_t, response_t, index_t ></cite> </span></dt>
<dd><p class="first last">the options for each tree</p>
</dd>
</dl>
</li>
</ul>
<dl class="method">
<dt id="pyrfr.regression.forest_opts.adjust_limits_to_data">
<code class="descname">adjust_limits_to_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#forest_opts.adjust_limits_to_data"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.forest_opts.adjust_limits_to_data" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id93"><span class="problematic" id="id94">`</span></a>adjust_limits_to_data(const rfr::data_containers::base< num_t, response_t,</dt>
<dd>index_t > &data)`</dd>
</dl>
<p>adjusts all relevant variables to the data</p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.compute_oob_error">
<code class="descname">compute_oob_error</code><a class="headerlink" href="#pyrfr.regression.forest_opts.compute_oob_error" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.do_bootstrapping">
<code class="descname">do_bootstrapping</code><a class="headerlink" href="#pyrfr.regression.forest_opts.do_bootstrapping" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.num_data_points_per_tree">
<code class="descname">num_data_points_per_tree</code><a class="headerlink" href="#pyrfr.regression.forest_opts.num_data_points_per_tree" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.num_trees">
<code class="descname">num_trees</code><a class="headerlink" href="#pyrfr.regression.forest_opts.num_trees" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.forest_opts.set_default_values">
<code class="descname">set_default_values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#forest_opts.set_default_values"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.forest_opts.set_default_values" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_default_values()</cite></p>
<p>(Re)set to default values for the forest.</p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.forest_opts.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.forest_opts.tree_opts">
<code class="descname">tree_opts</code><a class="headerlink" href="#pyrfr.regression.forest_opts.tree_opts" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.idx_vector">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">idx_vector</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.append"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.append" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.assign">
<code class="descname">assign</code><span class="sig-paren">(</span><em>n</em>, <em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.assign"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.assign" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.back">
<code class="descname">back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.begin">
<code class="descname">begin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.begin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.begin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.capacity">
<code class="descname">capacity</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.capacity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.capacity" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.clear"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.empty"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.empty" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.end">
<code class="descname">end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.end"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.end" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.erase">
<code class="descname">erase</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.erase"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.erase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.front">
<code class="descname">front</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.front"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.front" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.get_allocator">
<code class="descname">get_allocator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.get_allocator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.get_allocator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.insert"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.insert" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.iterator">
<code class="descname">iterator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.iterator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.pop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.pop" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.pop_back">
<code class="descname">pop_back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.pop_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.pop_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.push_back">
<code class="descname">push_back</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.push_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.push_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.rbegin">
<code class="descname">rbegin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.rbegin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.rbegin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.rend">
<code class="descname">rend</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.rend"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.rend" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.reserve">
<code class="descname">reserve</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.reserve"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.reserve" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.resize">
<code class="descname">resize</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.resize"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.resize" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.size">
<code class="descname">size</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.size"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.size" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.idx_vector.swap">
<code class="descname">swap</code><span class="sig-paren">(</span><em>v</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#idx_vector.swap"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.idx_vector.swap" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.idx_vector.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.idx_vector.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.num_num_pair">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">num_num_pair</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_num_pair"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_num_pair" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="attribute">
<dt id="pyrfr.regression.num_num_pair.first">
<code class="descname">first</code><a class="headerlink" href="#pyrfr.regression.num_num_pair.first" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.num_num_pair.second">
<code class="descname">second</code><a class="headerlink" href="#pyrfr.regression.num_num_pair.second" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.num_num_pair.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.num_num_pair.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.num_vector">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">num_vector</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.num_vector.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.append"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.append" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.assign">
<code class="descname">assign</code><span class="sig-paren">(</span><em>n</em>, <em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.assign"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.assign" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.back">
<code class="descname">back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.begin">
<code class="descname">begin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.begin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.begin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.capacity">
<code class="descname">capacity</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.capacity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.capacity" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.clear"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.empty"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.empty" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.end">
<code class="descname">end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.end"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.end" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.erase">
<code class="descname">erase</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.erase"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.erase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.front">
<code class="descname">front</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.front"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.front" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.get_allocator">
<code class="descname">get_allocator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.get_allocator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.get_allocator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.insert"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.insert" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.iterator">
<code class="descname">iterator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.iterator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.pop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.pop" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.pop_back">
<code class="descname">pop_back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.pop_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.pop_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.push_back">
<code class="descname">push_back</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.push_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.push_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.rbegin">
<code class="descname">rbegin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.rbegin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.rbegin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.rend">
<code class="descname">rend</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.rend"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.rend" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.reserve">
<code class="descname">reserve</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.reserve"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.reserve" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.resize">
<code class="descname">resize</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.resize"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.resize" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.size">
<code class="descname">size</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.size"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.size" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector.swap">
<code class="descname">swap</code><span class="sig-paren">(</span><em>v</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector.swap"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector.swap" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.num_vector.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.num_vector.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.num_vector_vector">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">num_vector_vector</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.append"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.append" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.assign">
<code class="descname">assign</code><span class="sig-paren">(</span><em>n</em>, <em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.assign"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.assign" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.back">
<code class="descname">back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.begin">
<code class="descname">begin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.begin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.begin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.capacity">
<code class="descname">capacity</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.capacity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.capacity" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.clear"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.empty"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.empty" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.end">
<code class="descname">end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.end"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.end" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.erase">
<code class="descname">erase</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.erase"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.erase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.front">
<code class="descname">front</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.front"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.front" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.get_allocator">
<code class="descname">get_allocator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.get_allocator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.get_allocator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.insert"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.insert" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.iterator">
<code class="descname">iterator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.iterator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.pop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.pop" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.pop_back">
<code class="descname">pop_back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.pop_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.pop_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.push_back">
<code class="descname">push_back</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.push_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.push_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.rbegin">
<code class="descname">rbegin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.rbegin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.rbegin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.rend">
<code class="descname">rend</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.rend"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.rend" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.reserve">
<code class="descname">reserve</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.reserve"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.reserve" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.resize">
<code class="descname">resize</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.resize"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.resize" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.size">
<code class="descname">size</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.size"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.size" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector.swap">
<code class="descname">swap</code><span class="sig-paren">(</span><em>v</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector.swap"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector.swap" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.num_vector_vector.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.num_vector_vector.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.num_vector_vector_vector">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">num_vector_vector_vector</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.append"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.append" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.assign">
<code class="descname">assign</code><span class="sig-paren">(</span><em>n</em>, <em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.assign"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.assign" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.back">
<code class="descname">back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.begin">
<code class="descname">begin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.begin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.begin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.capacity">
<code class="descname">capacity</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.capacity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.capacity" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.clear"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.empty"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.empty" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.end">
<code class="descname">end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.end"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.end" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.erase">
<code class="descname">erase</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.erase"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.erase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.front">
<code class="descname">front</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.front"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.front" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.get_allocator">
<code class="descname">get_allocator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.get_allocator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.get_allocator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.insert"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.insert" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.iterator">
<code class="descname">iterator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.iterator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.pop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.pop" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.pop_back">
<code class="descname">pop_back</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.pop_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.pop_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.push_back">
<code class="descname">push_back</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.push_back"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.push_back" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.rbegin">
<code class="descname">rbegin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.rbegin"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.rbegin" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.rend">
<code class="descname">rend</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.rend"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.rend" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.reserve">
<code class="descname">reserve</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.reserve"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.reserve" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.resize">
<code class="descname">resize</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.resize"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.resize" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.size">
<code class="descname">size</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.size"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.size" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.num_vector_vector_vector.swap">
<code class="descname">swap</code><span class="sig-paren">(</span><em>v</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#num_vector_vector_vector.swap"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.swap" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.num_vector_vector_vector.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.num_vector_vector_vector.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.qr_forest">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">qr_forest</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#qr_forest"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.qr_forest" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="#pyrfr.regression.binary_rss_forest" title="pyrfr.regression.binary_rss_forest"><code class="xref py py-class docutils literal"><span class="pre">pyrfr.regression.binary_rss_forest</span></code></a></p>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.all_leaf_values">
<code class="descname">all_leaf_values</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.all_leaf_values" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id95"><span class="problematic" id="id96">`</span></a>all_leaf_values(const std::vector< num_t > &feature_vector) const -></dt>
<dd>std::vector< std::vector< num_t > >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.ascii_string_representation">
<code class="descname">ascii_string_representation</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.ascii_string_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>ascii_string_representation() -> std::string</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.covariance">
<code class="descname">covariance</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.covariance" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id97"><span class="problematic" id="id98">`</span></a>covariance(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.fit">
<code class="descname">fit</code><span class="sig-paren">(</span><em>data</em>, <em>rng</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.fit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id99"><span class="problematic" id="id100">`</span></a>fit(const rfr::data_containers::base< num_t, response_t, index_t > &data,</dt>
<dd>rng_type &rng)`</dd>
</dl>
<p>growing the random forest for a given data set</p>
<ul>
<li><dl class="first docutils">
<dt><cite>data</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">a filled data container</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>rng</cite> <span class="classifier-delimiter">:</span> <span class="classifier"></span></dt>
<dd><p class="first last">the random number generator to be used</p>
</dd>
</dl>
</li>
</ul>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.kernel">
<code class="descname">kernel</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.kernel" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id101"><span class="problematic" id="id102">`</span></a>kernel(const std::vector< num_t > &f1, const std::vector< num_t > &f2) -></dt>
<dd>num_t`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.load_from_ascii_string">
<code class="descname">load_from_ascii_string</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.load_from_ascii_string" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_ascii_string(std::string const &str)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.load_from_binary_file">
<code class="descname">load_from_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.load_from_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>load_from_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.num_trees">
<code class="descname">num_trees</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.num_trees" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>num_trees() -> unsigned int</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.qr_forest.options">
<code class="descname">options</code><a class="headerlink" href="#pyrfr.regression.qr_forest.options" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.out_of_bag_error">
<code class="descname">out_of_bag_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.out_of_bag_error" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>out_of_bag_error() -> num_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.predict">
<code class="descname">predict</code><span class="sig-paren">(</span><em>feature_vector</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.predict" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>predict(const std::vector< num_t > &feature_vector) const -> response_t</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.predict_mean_var">
<code class="descname">predict_mean_var</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>weighted_data=False</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.predict_mean_var" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id103"><span class="problematic" id="id104">`</span></a>predict_mean_var(const std::vector< num_t > &feature_vector, bool</dt>
<dd>weighted_data=false) -> std::pair< num_t, num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.predict_quantiles">
<code class="descname">predict_quantiles</code><span class="sig-paren">(</span><em>feature_vector</em>, <em>quantiles</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#qr_forest.predict_quantiles"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.qr_forest.predict_quantiles" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id105"><span class="problematic" id="id106">`</span></a>predict_quantiles(const std::vector< num_t > &feature_vector, std::vector<</dt>
<dd>num_t > quantiles) const -> std::vector< num_t >`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.print_info">
<code class="descname">print_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.print_info" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>print_info()</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.pseudo_downdate">
<code class="descname">pseudo_downdate</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.pseudo_downdate" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id107"><span class="problematic" id="id108">`</span></a>pseudo_downdate(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.pseudo_update">
<code class="descname">pseudo_update</code><span class="sig-paren">(</span><em>features</em>, <em>response</em>, <em>weight</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.pseudo_update" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id109"><span class="problematic" id="id110">`</span></a>pseudo_update(std::vector< num_t > features, response_t response, num_t</dt>
<dd>weight)`</dd>
</dl>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.save_latex_representation">
<code class="descname">save_latex_representation</code><span class="sig-paren">(</span><em>filename_template</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.save_latex_representation" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_latex_representation(const std::string filename_template)</cite></p>
</dd></dl>
<dl class="method">
<dt id="pyrfr.regression.qr_forest.save_to_binary_file">
<code class="descname">save_to_binary_file</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#pyrfr.regression.qr_forest.save_to_binary_file" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>save_to_binary_file(const std::string filename)</cite></p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.qr_forest.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.qr_forest.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="pyrfr.regression.tree_opts">
<em class="property">class </em><code class="descclassname">pyrfr.regression.</code><code class="descname">tree_opts</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#tree_opts"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.tree_opts" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference external" href="http://docs.python.org/library/functions.html#object" title="(in Python v2.7)"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a></p>
<ul>
<li><dl class="first docutils">
<dt><cite>max_features</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">number of features to consider for each split</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max_depth</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">maximum depth for the tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min_samples_to_split</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">minumum number of samples to try splitting</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min_samples_in_leaf</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">minimum number of samples in a leaf</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>min_weight_in_leaf</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>num_type</cite> </span></dt>
<dd><p class="first last">minimum total sample weights in a leaf</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max_num_nodes</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">maxmimum total number of nodes in the tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>max_num_leaves</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>index_type</cite> </span></dt>
<dd><p class="first last">maxmimum total number of leaves in the tree</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><cite>epsilon_purity</cite> <span class="classifier-delimiter">:</span> <span class="classifier"><cite>response_type</cite> </span></dt>
<dd><p class="first last">minimum difference between two response values to be considered different*/</p>
</dd>
</dl>
</li>
</ul>
<dl class="method">
<dt id="pyrfr.regression.tree_opts.adjust_limits_to_data">
<code class="descname">adjust_limits_to_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#tree_opts.adjust_limits_to_data"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.tree_opts.adjust_limits_to_data" title="Permalink to this definition">¶</a></dt>
<dd><dl class="docutils">
<dt><a href="#id111"><span class="problematic" id="id112">`</span></a>adjust_limits_to_data(const rfr::data_containers::base< num_type,</dt>
<dd>response_type, index_type > &data)`</dd>
</dl>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.epsilon_purity">
<code class="descname">epsilon_purity</code><a class="headerlink" href="#pyrfr.regression.tree_opts.epsilon_purity" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.max_depth">
<code class="descname">max_depth</code><a class="headerlink" href="#pyrfr.regression.tree_opts.max_depth" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.max_features">
<code class="descname">max_features</code><a class="headerlink" href="#pyrfr.regression.tree_opts.max_features" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.max_num_leaves">
<code class="descname">max_num_leaves</code><a class="headerlink" href="#pyrfr.regression.tree_opts.max_num_leaves" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.max_num_nodes">
<code class="descname">max_num_nodes</code><a class="headerlink" href="#pyrfr.regression.tree_opts.max_num_nodes" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.min_samples_in_leaf">
<code class="descname">min_samples_in_leaf</code><a class="headerlink" href="#pyrfr.regression.tree_opts.min_samples_in_leaf" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.min_samples_to_split">
<code class="descname">min_samples_to_split</code><a class="headerlink" href="#pyrfr.regression.tree_opts.min_samples_to_split" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.min_weight_in_leaf">
<code class="descname">min_weight_in_leaf</code><a class="headerlink" href="#pyrfr.regression.tree_opts.min_weight_in_leaf" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="pyrfr.regression.tree_opts.set_default_values">
<code class="descname">set_default_values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pyrfr/regression.html#tree_opts.set_default_values"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pyrfr.regression.tree_opts.set_default_values" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>set_default_values()</cite></p>
<p>(Re)set to default values with no limits on the size of the tree</p>
<p>If nothing is know about the data, this member can be used to get a valid
setting for the tree_options struct. But beware this setting could lead to a
huge tree depending on the amount of data. There is no limit to the size, and
nodes are split into pure leafs. For each split, every feature is considered!
This not only slows the training down, but also makes this tree deterministic!</p>
</dd></dl>
<dl class="attribute">
<dt id="pyrfr.regression.tree_opts.thisown">
<code class="descname">thisown</code><a class="headerlink" href="#pyrfr.regression.tree_opts.thisown" title="Permalink to this definition">¶</a></dt>
<dd><p>The membership flag</p>
</dd></dl>
</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="installation.html"
title="previous chapter">About pyRFR</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/regression.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></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"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="installation.html" title="About pyRFR"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">pyrfr 0.5 documentation</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2015, Stefan Falkner.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
</div>
</body>
</html> | bsd-3-clause |
grrr-amsterdam/garp-functional | functions/not.php | 692 | <?php
declare(strict_types=1);
/**
* @package Garp\Functional
* @author Harmen Janssen <[email protected]>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Creates a negative version of an existing function.
*
* Example:
* $a = ['a', 'b', 'c'];
* in_array('a', $a); // true
*
* not('in_array')('a'); // false
* not('in_array')('d'); // true
*
* @param callable $fn Anything that call_user_func_array accepts
* @return callable
*/
function not(callable $fn): callable {
return function (...$args) use ($fn) {
return !$fn(...$args);
};
}
const not = '\Garp\Functional\not'; | bsd-3-clause |
kbc-developers/Mozc | src/rewriter/gen_usage_rewriter_dictionary_main.cc | 10507 | // Copyright 2010-2016, Google 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:
//
// * 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 Google 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.
// Usage dictionary generator:
// % gen_usage_rewriter_dictionary_main
// --usage_data_file=usage_data.txt
// --cforms_file=cforms.def
// --output=output_header
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "base/file_stream.h"
#include "base/flags.h"
#include "base/init_mozc.h"
#include "base/logging.h"
#include "base/util.h"
DEFINE_string(usage_data_file, "", "usage data file");
DEFINE_string(cforms_file, "", "cforms file");
DEFINE_string(output, "", "output header file");
namespace mozc {
namespace {
struct ConjugationType {
string form;
string value_suffix;
string key_suffix;
};
struct UsageItem {
string key;
string value;
string conjugation;
int conjugation_id;
string meaning;
};
bool UsageItemKeynameCmp(const UsageItem& l, const UsageItem& r) {
return l.key < r.key;
}
// Load cforms_file
void LoadConjugation(const string &filename,
map<string, vector<ConjugationType> > *output,
map<string, ConjugationType> *baseform_map) {
InputFileStream ifs(filename.c_str());
CHECK(ifs.good());
string line;
vector<string> fields;
while (!getline(ifs, line).fail()) {
if (line.empty() || line[0] == '#') {
continue;
}
fields.clear();
Util::SplitStringUsing(line, "\t ", &fields);
CHECK_GE(fields.size(), 4) << "format error: " << line;
ConjugationType tmp;
tmp.form = fields[1];
tmp.value_suffix = ((fields[2] == "*") ? "" : fields[2]);
tmp.key_suffix = ((fields[3] == "*") ? "" : fields[3]);
(*output)[fields[0]].push_back(tmp); // insert
if (tmp.form == "\xE5\x9F\xBA\xE6\x9C\xAC\xE5\xBD\xA2") { // 基本形
(*baseform_map)[fields[0]] = tmp;
}
}
}
// Load usage_data_file
void LoadUsage(const string &filename,
vector<UsageItem> *usage_entries,
vector<string> *conjugation_list) {
InputFileStream ifs(filename.c_str());
if (!ifs.good()) {
LOG(WARNING) << "Can't open file:" << filename;
return;
}
string line;
vector<string> fields;
map<string, int> conjugation_id_map;
int conjugation_id = 0;
while (!getline(ifs, line).fail()) {
if (line.empty() || line[0] == '#') {
// starting with '#' is a comment line.
continue;
}
fields.clear();
Util::SplitStringAllowEmpty(line, "\t", &fields);
CHECK_GE(fields.size(), 4) << "format error: " << line;
UsageItem item;
item.key = ((fields[0] == "*") ? "" : fields[0]);
item.value = ((fields[1] == "*") ? "" : fields[1]);
item.conjugation = ((fields[2] == "*") ? "" : fields[2]);
string tmp = ((fields[3] == "*") ? "" : fields[3]);
Util::StringReplace(tmp, "\\n", "\n", true, &item.meaning);
map<string, int>::iterator it = conjugation_id_map.find(item.conjugation);
if (it == conjugation_id_map.end()) {
conjugation_id_map.insert(
pair<string, int>(item.conjugation, conjugation_id));
item.conjugation_id = conjugation_id;
conjugation_list->push_back(item.conjugation);
++conjugation_id;
} else {
item.conjugation_id = it->second;
}
usage_entries->push_back(item);
}
}
// remove "基本形"'s conjugation suffix
void RemoveBaseformConjugationSuffix(
const map<string, ConjugationType> &baseform_map,
vector<UsageItem> *usage_entries) {
for (vector<UsageItem>::iterator usage_itr = usage_entries->begin();
usage_itr != usage_entries->end(); ++usage_itr) {
const map<string, ConjugationType>::const_iterator baseform_itr =
baseform_map.find(usage_itr->conjugation);
if (baseform_itr == baseform_map.end()) {
continue;
}
const ConjugationType &type = baseform_itr->second;
if (usage_itr->key.length() <= type.key_suffix.length()) {
LOG(WARNING) << "key:[" << usage_itr->key << "] is not longer then "
<< "baseform.key_suffix of \"" << usage_itr->conjugation
<< "\" : [" << type.key_suffix << "]";
}
if (usage_itr->value.length() <= type.value_suffix.length()) {
LOG(WARNING) << "value:[" << usage_itr->value << "] is not longer then "
<< "baseform.value_suffix of \"" << usage_itr->conjugation
<< "\" : [" << type.value_suffix << "]";
}
usage_itr->key.erase(usage_itr->key.length() - type.key_suffix.length());
usage_itr->value.erase(
usage_itr->value.length() - type.value_suffix.length());
}
}
void Convert() {
// Load cforms_file
map<string, vector<ConjugationType> > inflection_map;
map<string, ConjugationType> baseform_map;
LoadConjugation(FLAGS_cforms_file, &inflection_map, &baseform_map);
// Load usage_data_file
vector<UsageItem> usage_entries;
vector<string> conjugation_list;
LoadUsage(FLAGS_usage_data_file, &usage_entries, &conjugation_list);
ostream *ofs = &std::cout;
if (!FLAGS_output.empty()) {
ofs = new OutputFileStream(FLAGS_output.c_str());
}
*ofs << "// This header file is generated by "
<< "gen_usage_rewriter_dictionary_main." << std::endl;
// Output kConjugationNum
*ofs << "static const int kConjugationNum = " << conjugation_list.size()
<< ";" << std::endl;
// Output kBaseConjugationSuffix
*ofs << "static const ConjugationSuffix kBaseConjugationSuffix[] = {"
<< std::endl;
for (size_t i = 0; i < conjugation_list.size(); ++i) {
string value_suffix, key_suffix;
Util::Escape(baseform_map[conjugation_list[i]].value_suffix, &value_suffix);
Util::Escape(baseform_map[conjugation_list[i]].key_suffix, &key_suffix);
*ofs << " {\"" << value_suffix << "\", \"" << key_suffix << "\"}, "
<< "// " << conjugation_list[i] << std::endl;
}
*ofs << "};" << std::endl;
// Output kConjugationSuffixData
vector<int> conjugation_index(conjugation_list.size() + 1);
*ofs << "static const ConjugationSuffix kConjugationSuffixData[] = {"
<< std::endl;
int out_count = 0;
for (size_t i = 0; i < conjugation_list.size(); ++i) {
vector<ConjugationType> conjugations = inflection_map[conjugation_list[i]];
conjugation_index[i] = out_count;
if (conjugations.size() == 0) {
*ofs << " // " << i << ": (" << out_count << "-" << out_count
<< "): no conjugations" << std::endl;
*ofs << " {\"\",\"\"}," << std::endl;
++out_count;
} else {
typedef pair<string, string> StrPair;
set<StrPair> key_and_value_suffix_set;
for (size_t j = 0; j < conjugations.size(); ++j) {
StrPair key_and_value_suffix(conjugations[j].value_suffix,
conjugations[j].key_suffix);
key_and_value_suffix_set.insert(key_and_value_suffix);
}
*ofs << " // " << i << ": (" << out_count << "-"
<< (out_count + key_and_value_suffix_set.size() - 1)
<< "): " << conjugation_list[i] << std::endl
<< " ";
set<StrPair>::iterator itr;
for (itr = key_and_value_suffix_set.begin();
itr != key_and_value_suffix_set.end(); ++itr) {
string value_suffix, key_suffix;
Util::Escape(itr->first, &value_suffix);
Util::Escape(itr->second, &key_suffix);
*ofs << " {\"" << value_suffix <<
"\", \"" << key_suffix << "\"},";
++out_count;
}
*ofs << std::endl;
}
}
*ofs << "};" << std::endl;
conjugation_index[conjugation_list.size()] = out_count;
// Output kConjugationSuffixDataIndex
*ofs << "static const int kConjugationSuffixDataIndex[] = {";
for (size_t i = 0; i < conjugation_index.size(); ++i) {
if (i != 0) {
*ofs << ", ";
}
*ofs << conjugation_index[i];
}
*ofs << "};" << std::endl;
RemoveBaseformConjugationSuffix(baseform_map, &usage_entries);
std::sort(usage_entries.begin(), usage_entries.end(), UsageItemKeynameCmp);
// Output kUsageDataSize
*ofs << "static const size_t kUsageDataSize = " << usage_entries.size() << ";"
<< std::endl;
// Output kUsageData_value
*ofs << "static const UsageDictItem kUsageData_value[] = {" << std::endl;
int32 usage_id = 0;
for (vector<UsageItem>::iterator i = usage_entries.begin();
i != usage_entries.end(); i++) {
string key, value, meaning;
Util::Escape(i->key, &key);
Util::Escape(i->value, &value);
Util::Escape(i->meaning, &meaning);
*ofs << " {" << usage_id << ", \"" << key << "\", "
<< "\"" << value << "\", "
<< "" << i->conjugation_id << ", "
<< "\"" << meaning << "\"}, // " << i->value << "(" << i->key << ")"
<< std::endl;
++usage_id;
}
*ofs << " { 0, NULL, NULL, 0, NULL }" << std::endl;
*ofs << "};" << std::endl;
if (ofs != &std::cout) {
delete ofs;
}
}
} // namespace
} // namespace mozc
int main(int argc, char **argv) {
mozc::InitMozc(argv[0], &argc, &argv, true);
mozc::Convert();
return 0;
}
| bsd-3-clause |
BuildmLearn/BuildmLearn-Store | WP/doc/DOxygen_HTML/de/d27/class_app_store_1_1_models_1_1_category_instance.js | 182 | var class_app_store_1_1_models_1_1_category_instance =
[
[ "category", "de/d27/class_app_store_1_1_models_1_1_category_instance.html#ac1e8313d7f7d58349cf972f2be0ae365", null ]
]; | bsd-3-clause |
cpmech/gosl | num/qpck/dqk51.f | 9735 | subroutine dqk51(f,a,b,result,abserr,resabs,resasc,fid)
c***begin prologue dqk51
c***date written 800101 (yymmdd)
c***revision date 830518 (yymmdd)
c***category no. h2a1a2
c***keywords 51-point gauss-kronrod rules
c***author piessens,robert,appl. math. & progr. div. - k.u.leuven
c de doncker,elise,appl. math & progr. div. - k.u.leuven
c***purpose to compute i = integral of f over (a,b) with error
c estimate
c j = integral of abs(f) over (a,b)
c***description
c
c integration rules
c standard fortran subroutine
c double precision version
c
c parameters
c on entry
c f - double precision
c function subroutine defining the integrand
c function f(x). the actual name for f needs to be
c declared e x t e r n a l in the calling program.
c
c a - double precision
c lower limit of integration
c
c b - double precision
c upper limit of integration
c
c on return
c result - double precision
c approximation to the integral i
c result is computed by applying the 51-point
c kronrod rule (resk) obtained by optimal addition
c of abscissae to the 25-point gauss rule (resg).
c
c abserr - double precision
c estimate of the modulus of the absolute error,
c which should not exceed abs(i-result)
c
c resabs - double precision
c approximation to the integral j
c
c resasc - double precision
c approximation to the integral of abs(f-i/(b-a))
c over (a,b)
c
c***references (none)
c***routines called d1mach
c***end prologue dqk51
c
double precision a,absc,abserr,b,centr,dabs,dhlgth,dmax1,dmin1,
* d1mach,epmach,f,fc,fsum,fval1,fval2,fv1,fv2,hlgth,resabs,resasc,
* resg,resk,reskh,result,uflow,wg,wgk,xgk
integer j,jtw,jtwm1,fid
external f
c
dimension fv1(25),fv2(25),xgk(26),wgk(26),wg(13)
c
c the abscissae and weights are given for the interval (-1,1).
c because of symmetry only the positive abscissae and their
c corresponding weights are given.
c
c xgk - abscissae of the 51-point kronrod rule
c xgk(2), xgk(4), ... abscissae of the 25-point
c gauss rule
c xgk(1), xgk(3), ... abscissae which are optimally
c added to the 25-point gauss rule
c
c wgk - weights of the 51-point kronrod rule
c
c wg - weights of the 25-point gauss rule
c
c
c gauss quadrature weights and kronron quadrature abscissae and weights
c as evaluated with 80 decimal digit arithmetic by l. w. fullerton,
c bell labs, nov. 1981.
c
data wg ( 1) / 0.0113937985 0102628794 7902964113 235 d0 /
data wg ( 2) / 0.0263549866 1503213726 1901815295 299 d0 /
data wg ( 3) / 0.0409391567 0130631265 5623487711 646 d0 /
data wg ( 4) / 0.0549046959 7583519192 5936891540 473 d0 /
data wg ( 5) / 0.0680383338 1235691720 7187185656 708 d0 /
data wg ( 6) / 0.0801407003 3500101801 3234959669 111 d0 /
data wg ( 7) / 0.0910282619 8296364981 1497220702 892 d0 /
data wg ( 8) / 0.1005359490 6705064420 2206890392 686 d0 /
data wg ( 9) / 0.1085196244 7426365311 6093957050 117 d0 /
data wg ( 10) / 0.1148582591 4571164833 9325545869 556 d0 /
data wg ( 11) / 0.1194557635 3578477222 8178126512 901 d0 /
data wg ( 12) / 0.1222424429 9031004168 8959518945 852 d0 /
data wg ( 13) / 0.1231760537 2671545120 3902873079 050 d0 /
c
data xgk ( 1) / 0.9992621049 9260983419 3457486540 341 d0 /
data xgk ( 2) / 0.9955569697 9049809790 8784946893 902 d0 /
data xgk ( 3) / 0.9880357945 3407724763 7331014577 406 d0 /
data xgk ( 4) / 0.9766639214 5951751149 8315386479 594 d0 /
data xgk ( 5) / 0.9616149864 2584251241 8130033660 167 d0 /
data xgk ( 6) / 0.9429745712 2897433941 4011169658 471 d0 /
data xgk ( 7) / 0.9207471152 8170156174 6346084546 331 d0 /
data xgk ( 8) / 0.8949919978 7827536885 1042006782 805 d0 /
data xgk ( 9) / 0.8658470652 9327559544 8996969588 340 d0 /
data xgk ( 10) / 0.8334426287 6083400142 1021108693 570 d0 /
data xgk ( 11) / 0.7978737979 9850005941 0410904994 307 d0 /
data xgk ( 12) / 0.7592592630 3735763057 7282865204 361 d0 /
data xgk ( 13) / 0.7177664068 1308438818 6654079773 298 d0 /
data xgk ( 14) / 0.6735663684 7346836448 5120633247 622 d0 /
data xgk ( 15) / 0.6268100990 1031741278 8122681624 518 d0 /
data xgk ( 16) / 0.5776629302 4122296772 3689841612 654 d0 /
data xgk ( 17) / 0.5263252843 3471918259 9623778158 010 d0 /
data xgk ( 18) / 0.4730027314 4571496052 2182115009 192 d0 /
data xgk ( 19) / 0.4178853821 9303774885 1814394594 572 d0 /
data xgk ( 20) / 0.3611723058 0938783773 5821730127 641 d0 /
data xgk ( 21) / 0.3030895389 3110783016 7478909980 339 d0 /
data xgk ( 22) / 0.2438668837 2098843204 5190362797 452 d0 /
data xgk ( 23) / 0.1837189394 2104889201 5969888759 528 d0 /
data xgk ( 24) / 0.1228646926 1071039638 7359818808 037 d0 /
data xgk ( 25) / 0.0615444830 0568507888 6546392366 797 d0 /
data xgk ( 26) / 0.0000000000 0000000000 0000000000 000 d0 /
c
data wgk ( 1) / 0.0019873838 9233031592 6507851882 843 d0 /
data wgk ( 2) / 0.0055619321 3535671375 8040236901 066 d0 /
data wgk ( 3) / 0.0094739733 8617415160 7207710523 655 d0 /
data wgk ( 4) / 0.0132362291 9557167481 3656405846 976 d0 /
data wgk ( 5) / 0.0168478177 0912829823 1516667536 336 d0 /
data wgk ( 6) / 0.0204353711 4588283545 6568292235 939 d0 /
data wgk ( 7) / 0.0240099456 0695321622 0092489164 881 d0 /
data wgk ( 8) / 0.0274753175 8785173780 2948455517 811 d0 /
data wgk ( 9) / 0.0307923001 6738748889 1109020215 229 d0 /
data wgk ( 10) / 0.0340021302 7432933783 6748795229 551 d0 /
data wgk ( 11) / 0.0371162714 8341554356 0330625367 620 d0 /
data wgk ( 12) / 0.0400838255 0403238207 4839284467 076 d0 /
data wgk ( 13) / 0.0428728450 2017004947 6895792439 495 d0 /
data wgk ( 14) / 0.0455029130 4992178890 9870584752 660 d0 /
data wgk ( 15) / 0.0479825371 3883671390 6392255756 915 d0 /
data wgk ( 16) / 0.0502776790 8071567196 3325259433 440 d0 /
data wgk ( 17) / 0.0523628858 0640747586 4366712137 873 d0 /
data wgk ( 18) / 0.0542511298 8854549014 4543370459 876 d0 /
data wgk ( 19) / 0.0559508112 2041231730 8240686382 747 d0 /
data wgk ( 20) / 0.0574371163 6156783285 3582693939 506 d0 /
data wgk ( 21) / 0.0586896800 2239420796 1974175856 788 d0 /
data wgk ( 22) / 0.0597203403 2417405997 9099291932 562 d0 /
data wgk ( 23) / 0.0605394553 7604586294 5360267517 565 d0 /
data wgk ( 24) / 0.0611285097 1705304830 5859030416 293 d0 /
data wgk ( 25) / 0.0614711898 7142531666 1544131965 264 d0 /
c note: wgk (26) was calculated from the values of wgk(1..25)
data wgk ( 26) / 0.0615808180 6783293507 8759824240 066 d0 /
c
c
c list of major variables
c -----------------------
c
c centr - mid point of the interval
c hlgth - half-length of the interval
c absc - abscissa
c fval* - function value
c resg - result of the 25-point gauss formula
c resk - result of the 51-point kronrod formula
c reskh - approximation to the mean value of f over (a,b),
c i.e. to i/(b-a)
c
c machine dependent constants
c ---------------------------
c
c epmach is the largest relative spacing.
c uflow is the smallest positive magnitude.
c
c***first executable statement dqk51
epmach = d1mach(4)
uflow = d1mach(1)
c
centr = 0.5d+00*(a+b)
hlgth = 0.5d+00*(b-a)
dhlgth = dabs(hlgth)
c
c compute the 51-point kronrod approximation to
c the integral, and estimate the absolute error.
c
fc = f(centr,fid)
resg = wg(13)*fc
resk = wgk(26)*fc
resabs = dabs(resk)
do 10 j=1,12
jtw = j*2
absc = hlgth*xgk(jtw)
fval1 = f(centr-absc,fid)
fval2 = f(centr+absc,fid)
fv1(jtw) = fval1
fv2(jtw) = fval2
fsum = fval1+fval2
resg = resg+wg(j)*fsum
resk = resk+wgk(jtw)*fsum
resabs = resabs+wgk(jtw)*(dabs(fval1)+dabs(fval2))
10 continue
do 15 j = 1,13
jtwm1 = j*2-1
absc = hlgth*xgk(jtwm1)
fval1 = f(centr-absc,fid)
fval2 = f(centr+absc,fid)
fv1(jtwm1) = fval1
fv2(jtwm1) = fval2
fsum = fval1+fval2
resk = resk+wgk(jtwm1)*fsum
resabs = resabs+wgk(jtwm1)*(dabs(fval1)+dabs(fval2))
15 continue
reskh = resk*0.5d+00
resasc = wgk(26)*dabs(fc-reskh)
do 20 j=1,25
resasc = resasc+wgk(j)*(dabs(fv1(j)-reskh)+dabs(fv2(j)-reskh))
20 continue
result = resk*hlgth
resabs = resabs*dhlgth
resasc = resasc*dhlgth
abserr = dabs((resk-resg)*hlgth)
if(resasc.ne.0.0d+00.and.abserr.ne.0.0d+00)
* abserr = resasc*dmin1(0.1d+01,(0.2d+03*abserr/resasc)**1.5d+00)
if(resabs.gt.uflow/(0.5d+02*epmach)) abserr = dmax1
* ((epmach*0.5d+02)*resabs,abserr)
return
end
| bsd-3-clause |
endlessm/chromium-browser | chrome/browser/extensions/install_signer.h | 4465 | // Copyright 2013 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 CHROME_BROWSER_EXTENSIONS_INSTALL_SIGNER_H_
#define CHROME_BROWSER_EXTENSIONS_INSTALL_SIGNER_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "extensions/common/extension_id.h"
namespace base {
class DictionaryValue;
}
namespace network {
class SimpleURLLoader;
class SharedURLLoaderFactory;
} // namespace network
namespace extensions {
// This represents a list of ids signed with a private key using an algorithm
// that includes some salt bytes.
struct InstallSignature {
// The set of ids that have been signed.
ExtensionIdSet ids;
// Both of these are just arrays of bytes, NOT base64-encoded.
std::string salt;
std::string signature;
// The date that the signature should expire, in YYYY-MM-DD format.
std::string expire_date;
// The time this signature was obtained from the server. Note that this
// is computed locally and *not* signed by the server key.
base::Time timestamp;
// The set of ids that the server indicated were invalid (ie not signed).
// Note that this is computed locally and *not* signed by the signature.
ExtensionIdSet invalid_ids;
InstallSignature();
InstallSignature(const InstallSignature& other);
~InstallSignature();
// Helper methods for serialization to/from a base::DictionaryValue.
void ToValue(base::DictionaryValue* value) const;
static std::unique_ptr<InstallSignature> FromValue(
const base::DictionaryValue& value);
};
// Objects of this class encapsulate an operation to get a signature proving
// that a set of ids are hosted in the webstore.
class InstallSigner {
public:
using SignatureCallback =
base::OnceCallback<void(std::unique_ptr<InstallSignature>)>;
// IMPORTANT NOTE: It is possible that only some, but not all, of the entries
// in |ids| will be successfully signed by the backend. Callers should always
// check the set of ids in the InstallSignature passed to their callback, as
// it may contain only a subset of the ids they passed in.
InstallSigner(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const ExtensionIdSet& ids);
~InstallSigner();
// Returns a set of ids that are forced to be considered not from webstore,
// e.g. by a command line flag used for testing.
static ExtensionIdSet GetForcedNotFromWebstore();
// Begins the process of fetching a signature from the backend. This should
// only be called once! If you want to get another signature, make another
// instance of this class.
void GetSignature(SignatureCallback callback);
// Returns whether the signature in InstallSignature is properly signed with a
// known public key.
static bool VerifySignature(const InstallSignature& signature);
private:
// A helper function that calls |callback_| with an indication that an error
// happened (currently done by passing an empty pointer).
void ReportErrorViaCallback();
// Called when |simple_loader_| has returned a result to parse the response,
// and then call HandleSignatureResult with structured data.
void ParseFetchResponse(std::unique_ptr<std::string> response_body);
// Handles the result from a backend fetch.
void HandleSignatureResult(const std::string& signature,
const std::string& expire_date,
const ExtensionIdSet& invalid_ids);
// The final callback for when we're done.
SignatureCallback callback_;
// The current set of ids we're trying to verify. This may contain fewer ids
// than we started with.
ExtensionIdSet ids_;
// An array of random bytes used as an input to hash with the machine id,
// which will need to be persisted in the eventual InstallSignature we get.
std::string salt_;
// These are used to make the call to a backend server for a signature.
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
// The underlying SimpleURLLoader which does the actual load.
std::unique_ptr<network::SimpleURLLoader> simple_loader_;
// The time the request to the server was started.
base::Time request_start_time_;
DISALLOW_COPY_AND_ASSIGN(InstallSigner);
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_INSTALL_SIGNER_H_
| bsd-3-clause |
leepike/copilot-libraries | README.md | 2149 | # STOP! The official Copilot repos are now at [https://github.com/Copilot-Language/](https://github.com/Copilot-Language).
Overview
========
[copilot-libraries](http://hackage.haskell.org/package/copilot-libraries)
User-supplied libraries for Copilot, including linear-temporal logic,
fault-tolerant voting, regular expressions, etc.
Copilot is a stream (i.e., infinite lists) domain-specific language (DSL) in
Haskell that compiles into embedded C. Copilot is similar in spirit to
languages like Lustre. Copilot contains an interpreter, multiple back-end
compilers, and other verification tools.
Examples
=========
Please see the files under the Examples directory in the
[Copilot](http://hackage.haskell.org/package/copilot) for a number of examples
showing the syntax, use of libraries, and use of the interpreter and back-ends.
The examples is the best way to start.
Installation
============
The Copilot library is cabalized. Assuming you have cabal and the GHC compiler
installed (the [Haskell Platform](http://hackage.haskell.org/platform/) is the
easiest way to obtain these), it should merely be a matter of running
cabal install copilot-libraries
However, we strongly recommend you install Copilot, which installs
copilot-libraries and other packages automatically. Execute
cabal install copilot
Dependencies
=============
copilot-libraries depends on the
[Atom](http://hackage.haskell.org/package/copilot-cbmc) to generate hard
real-time C code.
Resources
=========
[copilot-libraries](http://hackage.haskell.org/package/copilot-libraries) is
available on Hackage.
**Sources** for each package are available on Github as well. Just go to
[Github](github.com) and search for the package of interest. Feel free to fork!
Copyright, License
==================
Copilot is distributed with the BSD3 license. The license file contains the
[BSD3](http://en.wikipedia.org/wiki/BSD_licenses) verbiage.
Thanks
======
We are grateful for NASA Contract NNL08AD13T to [Galois,
Inc](http://corp.galois.com/) and the [National Institute of
Aerospace](http://www.nianet.org/), which partially supported this work.
| bsd-3-clause |
youtube/cobalt | third_party/angle/src/libANGLE/validationES2_autogen.h | 20719 | // GENERATED FILE - DO NOT EDIT.
// Generated by generate_entry_points.py using data from gl.xml and gl_angle_ext.xml.
//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// validationES2_autogen.h:
// Validation functions for the OpenGL ES 2.0 entry points.
#ifndef LIBANGLE_VALIDATION_ES2_AUTOGEN_H_
#define LIBANGLE_VALIDATION_ES2_AUTOGEN_H_
#include "common/PackedEnums.h"
namespace gl
{
class Context;
bool ValidateActiveTexture(Context *context, GLenum texture);
bool ValidateAttachShader(Context *context,
ShaderProgramID programPacked,
ShaderProgramID shaderPacked);
bool ValidateBindAttribLocation(Context *context,
ShaderProgramID programPacked,
GLuint index,
const GLchar *name);
bool ValidateBindBuffer(Context *context, BufferBinding targetPacked, BufferID bufferPacked);
bool ValidateBindFramebuffer(Context *context, GLenum target, FramebufferID framebufferPacked);
bool ValidateBindRenderbuffer(Context *context, GLenum target, RenderbufferID renderbufferPacked);
bool ValidateBindTexture(Context *context, TextureType targetPacked, TextureID texturePacked);
bool ValidateBlendColor(Context *context, GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
bool ValidateBlendEquation(Context *context, GLenum mode);
bool ValidateBlendEquationSeparate(Context *context, GLenum modeRGB, GLenum modeAlpha);
bool ValidateBlendFunc(Context *context, GLenum sfactor, GLenum dfactor);
bool ValidateBlendFuncSeparate(Context *context,
GLenum sfactorRGB,
GLenum dfactorRGB,
GLenum sfactorAlpha,
GLenum dfactorAlpha);
bool ValidateBufferData(Context *context,
BufferBinding targetPacked,
GLsizeiptr size,
const void *data,
BufferUsage usagePacked);
bool ValidateBufferSubData(Context *context,
BufferBinding targetPacked,
GLintptr offset,
GLsizeiptr size,
const void *data);
bool ValidateCheckFramebufferStatus(Context *context, GLenum target);
bool ValidateClear(Context *context, GLbitfield mask);
bool ValidateClearColor(Context *context, GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
bool ValidateClearDepthf(Context *context, GLfloat d);
bool ValidateClearStencil(Context *context, GLint s);
bool ValidateColorMask(Context *context,
GLboolean red,
GLboolean green,
GLboolean blue,
GLboolean alpha);
bool ValidateCompileShader(Context *context, ShaderProgramID shaderPacked);
bool ValidateCompressedTexImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLenum internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLsizei imageSize,
const void *data);
bool ValidateCompressedTexSubImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLsizei imageSize,
const void *data);
bool ValidateCopyTexImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLenum internalformat,
GLint x,
GLint y,
GLsizei width,
GLsizei height,
GLint border);
bool ValidateCopyTexSubImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLint xoffset,
GLint yoffset,
GLint x,
GLint y,
GLsizei width,
GLsizei height);
bool ValidateCreateProgram(Context *context);
bool ValidateCreateShader(Context *context, ShaderType typePacked);
bool ValidateCullFace(Context *context, CullFaceMode modePacked);
bool ValidateDeleteBuffers(Context *context, GLsizei n, const BufferID *buffersPacked);
bool ValidateDeleteFramebuffers(Context *context,
GLsizei n,
const FramebufferID *framebuffersPacked);
bool ValidateDeleteProgram(Context *context, ShaderProgramID programPacked);
bool ValidateDeleteRenderbuffers(Context *context,
GLsizei n,
const RenderbufferID *renderbuffersPacked);
bool ValidateDeleteShader(Context *context, ShaderProgramID shaderPacked);
bool ValidateDeleteTextures(Context *context, GLsizei n, const TextureID *texturesPacked);
bool ValidateDepthFunc(Context *context, GLenum func);
bool ValidateDepthMask(Context *context, GLboolean flag);
bool ValidateDepthRangef(Context *context, GLfloat n, GLfloat f);
bool ValidateDetachShader(Context *context,
ShaderProgramID programPacked,
ShaderProgramID shaderPacked);
bool ValidateDisable(Context *context, GLenum cap);
bool ValidateDisableVertexAttribArray(Context *context, GLuint index);
bool ValidateDrawArrays(Context *context, PrimitiveMode modePacked, GLint first, GLsizei count);
bool ValidateDrawElements(Context *context,
PrimitiveMode modePacked,
GLsizei count,
DrawElementsType typePacked,
const void *indices);
bool ValidateEnable(Context *context, GLenum cap);
bool ValidateEnableVertexAttribArray(Context *context, GLuint index);
bool ValidateFinish(Context *context);
bool ValidateFlush(Context *context);
bool ValidateFramebufferRenderbuffer(Context *context,
GLenum target,
GLenum attachment,
GLenum renderbuffertarget,
RenderbufferID renderbufferPacked);
bool ValidateFramebufferTexture2D(Context *context,
GLenum target,
GLenum attachment,
TextureTarget textargetPacked,
TextureID texturePacked,
GLint level);
bool ValidateFrontFace(Context *context, GLenum mode);
bool ValidateGenBuffers(Context *context, GLsizei n, BufferID *buffersPacked);
bool ValidateGenFramebuffers(Context *context, GLsizei n, FramebufferID *framebuffersPacked);
bool ValidateGenRenderbuffers(Context *context, GLsizei n, RenderbufferID *renderbuffersPacked);
bool ValidateGenTextures(Context *context, GLsizei n, TextureID *texturesPacked);
bool ValidateGenerateMipmap(Context *context, TextureType targetPacked);
bool ValidateGetActiveAttrib(Context *context,
ShaderProgramID programPacked,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLint *size,
GLenum *type,
GLchar *name);
bool ValidateGetActiveUniform(Context *context,
ShaderProgramID programPacked,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLint *size,
GLenum *type,
GLchar *name);
bool ValidateGetAttachedShaders(Context *context,
ShaderProgramID programPacked,
GLsizei maxCount,
GLsizei *count,
ShaderProgramID *shadersPacked);
bool ValidateGetAttribLocation(Context *context, ShaderProgramID programPacked, const GLchar *name);
bool ValidateGetBooleanv(Context *context, GLenum pname, GLboolean *data);
bool ValidateGetBufferParameteriv(Context *context,
BufferBinding targetPacked,
GLenum pname,
GLint *params);
bool ValidateGetError(Context *context);
bool ValidateGetFloatv(Context *context, GLenum pname, GLfloat *data);
bool ValidateGetFramebufferAttachmentParameteriv(Context *context,
GLenum target,
GLenum attachment,
GLenum pname,
GLint *params);
bool ValidateGetIntegerv(Context *context, GLenum pname, GLint *data);
bool ValidateGetProgramInfoLog(Context *context,
ShaderProgramID programPacked,
GLsizei bufSize,
GLsizei *length,
GLchar *infoLog);
bool ValidateGetProgramiv(Context *context,
ShaderProgramID programPacked,
GLenum pname,
GLint *params);
bool ValidateGetRenderbufferParameteriv(Context *context,
GLenum target,
GLenum pname,
GLint *params);
bool ValidateGetShaderInfoLog(Context *context,
ShaderProgramID shaderPacked,
GLsizei bufSize,
GLsizei *length,
GLchar *infoLog);
bool ValidateGetShaderPrecisionFormat(Context *context,
GLenum shadertype,
GLenum precisiontype,
GLint *range,
GLint *precision);
bool ValidateGetShaderSource(Context *context,
ShaderProgramID shaderPacked,
GLsizei bufSize,
GLsizei *length,
GLchar *source);
bool ValidateGetShaderiv(Context *context,
ShaderProgramID shaderPacked,
GLenum pname,
GLint *params);
bool ValidateGetString(Context *context, GLenum name);
bool ValidateGetTexParameterfv(Context *context,
TextureType targetPacked,
GLenum pname,
GLfloat *params);
bool ValidateGetTexParameteriv(Context *context,
TextureType targetPacked,
GLenum pname,
GLint *params);
bool ValidateGetUniformLocation(Context *context,
ShaderProgramID programPacked,
const GLchar *name);
bool ValidateGetUniformfv(Context *context,
ShaderProgramID programPacked,
GLint location,
GLfloat *params);
bool ValidateGetUniformiv(Context *context,
ShaderProgramID programPacked,
GLint location,
GLint *params);
bool ValidateGetVertexAttribPointerv(Context *context, GLuint index, GLenum pname, void **pointer);
bool ValidateGetVertexAttribfv(Context *context, GLuint index, GLenum pname, GLfloat *params);
bool ValidateGetVertexAttribiv(Context *context, GLuint index, GLenum pname, GLint *params);
bool ValidateHint(Context *context, GLenum target, GLenum mode);
bool ValidateIsBuffer(Context *context, BufferID bufferPacked);
bool ValidateIsEnabled(Context *context, GLenum cap);
bool ValidateIsFramebuffer(Context *context, FramebufferID framebufferPacked);
bool ValidateIsProgram(Context *context, ShaderProgramID programPacked);
bool ValidateIsRenderbuffer(Context *context, RenderbufferID renderbufferPacked);
bool ValidateIsShader(Context *context, ShaderProgramID shaderPacked);
bool ValidateIsTexture(Context *context, TextureID texturePacked);
bool ValidateLineWidth(Context *context, GLfloat width);
bool ValidateLinkProgram(Context *context, ShaderProgramID programPacked);
bool ValidatePixelStorei(Context *context, GLenum pname, GLint param);
bool ValidatePolygonOffset(Context *context, GLfloat factor, GLfloat units);
bool ValidateReadPixels(Context *context,
GLint x,
GLint y,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type,
void *pixels);
bool ValidateReleaseShaderCompiler(Context *context);
bool ValidateRenderbufferStorage(Context *context,
GLenum target,
GLenum internalformat,
GLsizei width,
GLsizei height);
bool ValidateSampleCoverage(Context *context, GLfloat value, GLboolean invert);
bool ValidateScissor(Context *context, GLint x, GLint y, GLsizei width, GLsizei height);
bool ValidateShaderBinary(Context *context,
GLsizei count,
const ShaderProgramID *shadersPacked,
GLenum binaryformat,
const void *binary,
GLsizei length);
bool ValidateShaderSource(Context *context,
ShaderProgramID shaderPacked,
GLsizei count,
const GLchar *const *string,
const GLint *length);
bool ValidateStencilFunc(Context *context, GLenum func, GLint ref, GLuint mask);
bool ValidateStencilFuncSeparate(Context *context,
GLenum face,
GLenum func,
GLint ref,
GLuint mask);
bool ValidateStencilMask(Context *context, GLuint mask);
bool ValidateStencilMaskSeparate(Context *context, GLenum face, GLuint mask);
bool ValidateStencilOp(Context *context, GLenum fail, GLenum zfail, GLenum zpass);
bool ValidateStencilOpSeparate(Context *context,
GLenum face,
GLenum sfail,
GLenum dpfail,
GLenum dppass);
bool ValidateTexImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const void *pixels);
bool ValidateTexParameterf(Context *context, TextureType targetPacked, GLenum pname, GLfloat param);
bool ValidateTexParameterfv(Context *context,
TextureType targetPacked,
GLenum pname,
const GLfloat *params);
bool ValidateTexParameteri(Context *context, TextureType targetPacked, GLenum pname, GLint param);
bool ValidateTexParameteriv(Context *context,
TextureType targetPacked,
GLenum pname,
const GLint *params);
bool ValidateTexSubImage2D(Context *context,
TextureTarget targetPacked,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type,
const void *pixels);
bool ValidateUniform1f(Context *context, GLint location, GLfloat v0);
bool ValidateUniform1fv(Context *context, GLint location, GLsizei count, const GLfloat *value);
bool ValidateUniform1i(Context *context, GLint location, GLint v0);
bool ValidateUniform1iv(Context *context, GLint location, GLsizei count, const GLint *value);
bool ValidateUniform2f(Context *context, GLint location, GLfloat v0, GLfloat v1);
bool ValidateUniform2fv(Context *context, GLint location, GLsizei count, const GLfloat *value);
bool ValidateUniform2i(Context *context, GLint location, GLint v0, GLint v1);
bool ValidateUniform2iv(Context *context, GLint location, GLsizei count, const GLint *value);
bool ValidateUniform3f(Context *context, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
bool ValidateUniform3fv(Context *context, GLint location, GLsizei count, const GLfloat *value);
bool ValidateUniform3i(Context *context, GLint location, GLint v0, GLint v1, GLint v2);
bool ValidateUniform3iv(Context *context, GLint location, GLsizei count, const GLint *value);
bool ValidateUniform4f(Context *context,
GLint location,
GLfloat v0,
GLfloat v1,
GLfloat v2,
GLfloat v3);
bool ValidateUniform4fv(Context *context, GLint location, GLsizei count, const GLfloat *value);
bool ValidateUniform4i(Context *context, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
bool ValidateUniform4iv(Context *context, GLint location, GLsizei count, const GLint *value);
bool ValidateUniformMatrix2fv(Context *context,
GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value);
bool ValidateUniformMatrix3fv(Context *context,
GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value);
bool ValidateUniformMatrix4fv(Context *context,
GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value);
bool ValidateUseProgram(Context *context, ShaderProgramID programPacked);
bool ValidateValidateProgram(Context *context, ShaderProgramID programPacked);
bool ValidateVertexAttrib1f(Context *context, GLuint index, GLfloat x);
bool ValidateVertexAttrib1fv(Context *context, GLuint index, const GLfloat *v);
bool ValidateVertexAttrib2f(Context *context, GLuint index, GLfloat x, GLfloat y);
bool ValidateVertexAttrib2fv(Context *context, GLuint index, const GLfloat *v);
bool ValidateVertexAttrib3f(Context *context, GLuint index, GLfloat x, GLfloat y, GLfloat z);
bool ValidateVertexAttrib3fv(Context *context, GLuint index, const GLfloat *v);
bool ValidateVertexAttrib4f(Context *context,
GLuint index,
GLfloat x,
GLfloat y,
GLfloat z,
GLfloat w);
bool ValidateVertexAttrib4fv(Context *context, GLuint index, const GLfloat *v);
bool ValidateVertexAttribPointer(Context *context,
GLuint index,
GLint size,
VertexAttribType typePacked,
GLboolean normalized,
GLsizei stride,
const void *pointer);
bool ValidateViewport(Context *context, GLint x, GLint y, GLsizei width, GLsizei height);
} // namespace gl
#endif // LIBANGLE_VALIDATION_ES2_AUTOGEN_H_
| bsd-3-clause |
youtube/cobalt | starboard/shared/stub/window_get_platform_handle.cc | 717 | // Copyright 2016 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "starboard/window.h"
void* SbWindowGetPlatformHandle(SbWindow window) {
return NULL;
}
| bsd-3-clause |
herumi/cybozulib | test/base/event_test.cpp | 581 | #include <stdio.h>
#include <cybozu/thread.hpp>
#include <cybozu/event.hpp>
#include <cybozu/test.hpp>
class Thread : public cybozu::ThreadBase {
cybozu::Event& ev_;
public:
bool done_;
Thread(cybozu::Event& ev)
: ev_(ev)
, done_(false)
{
}
void threadEntry()
{
puts("thread");
puts("sleep 100msec");
cybozu::Sleep(100);
puts("wakeup");
ev_.wakeup();
cybozu::Sleep(100);
ev_.wakeup();
}
};
CYBOZU_TEST_AUTO(event_test)
{
cybozu::Event ev;
Thread th(ev);
th.beginThread();
ev.wait();
puts("done");
ev.wait();
puts("done");
th.joinThread();
}
| bsd-3-clause |
Cocotteseb/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Layout/ViewLayoutRibbonPadding.cs | 3234 | // *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
// Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
// Version 4.4.1.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// View element adds padding to the provided drawing area.
/// </summary>
internal class ViewLayoutRibbonPadding : ViewComposite
{
#region Instance Fields
private Padding _preferredPadding;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewLayoutRibbonPadding class.
/// </summary>
/// <param name="preferredPadding">Padding to use when calculating space.</param>
public ViewLayoutRibbonPadding(Padding preferredPadding)
{
_preferredPadding = preferredPadding;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewLayoutRibbonPadding:" + Id;
}
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
// Get the preferred size of the contained content
Size preferredSize = base.GetPreferredSize(context);
// Add on the padding we need around edges
return new Size(preferredSize.Width + _preferredPadding.Horizontal,
preferredSize.Height + _preferredPadding.Vertical);
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
// Validate incoming reference
if (context == null) throw new ArgumentNullException("context");
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Find the rectangle for the child elements by applying padding
context.DisplayRectangle = CommonHelper.ApplyPadding(Orientation.Horizontal, ClientRectangle, _preferredPadding);
// Let base perform actual layout process of child elements
base.Layout(context);
// Put back the original display value now we have finished
context.DisplayRectangle = ClientRectangle;
}
#endregion
}
}
| bsd-3-clause |
lionkov/ninep | clnt/pool.go | 1798 | // Copyright 2009 The Ninep 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 clnt
var m2id = [...]uint8{
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 7,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 0,
}
func newPool(maxid uint32) *pool {
p := new(pool)
p.maxid = maxid
p.nchan = make(chan uint32)
return p
}
func (p *pool) getId() uint32 {
var n uint32 = 0
var ret uint32
p.Lock()
for n = 0; n < uint32(len(p.imap)); n++ {
if p.imap[n] != 0xFF {
break
}
}
if int(n) >= len(p.imap) {
m := uint32(len(p.imap) + 32)
if uint32(m*8) > p.maxid {
m = p.maxid/8 + 1
}
b := make([]byte, m)
copy(b, p.imap)
p.imap = b
}
if n >= uint32(len(p.imap)) {
p.need++
p.Unlock()
ret = <-p.nchan
} else {
ret = uint32(m2id[p.imap[n]])
p.imap[n] |= 1 << ret
ret += n * 8
p.Unlock()
}
return ret
}
func (p *pool) putId(id uint32) {
p.Lock()
if p.need > 0 {
p.nchan <- id
p.need--
p.Unlock()
return
}
p.imap[id/8] &= ^(1 << (id % 8))
p.Unlock()
}
| bsd-3-clause |
AlexanderBliznuk/disposable_razors | migrations/m170212_160300_modify_subscription.php | 735 | <?php
use yii\db\Migration;
class m170212_160300_modify_subscription extends Migration
{
public function up() {
$this->addColumn('subscription', 'good_id', \yii\db\Schema::TYPE_INTEGER);
$this->addForeignKey(
'fk-subscription-good_id',
'subscription',
'good_id',
'good',
'id',
'CASCADE'
);
}
public function down() {
$this->dropForeignKey('fk-subscription-good_id', 'subscription');
$this->dropColumn('subscription', 'good_id');
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| bsd-3-clause |
CUBRID/cubrid-testcases | sql/_26_features_920/issue_9405_ro_locale/_02_collation/cases/_10_alphabet.sql | 3274 | --+ holdcas on;
set names utf8;
CREATE TABLE coll_test_ro (id INTEGER, s1 VARCHAR(10) collate utf8_ro_cs, s2 VARCHAR(10) collate utf8_ro_cs, s3 VARCHAR(10) collate utf8_ro_cs);
INSERT INTO coll_test_ro (id, s1, s2, s3) values (0, 'a', 'A', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (1, 'ă', 'Ă', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (2, 'â', 'Â', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (3, 'b', 'B', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (4, 'c', 'C', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (5, 'd', 'D', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (6, 'e', 'E', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (7, 'f', 'F', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (8, 'g', 'G', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (9, 'h', 'H', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (10, 'i', 'I', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (11, 'î', 'Î', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (12, 'j', 'J', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (13, 'k', 'K', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (14, 'l', 'L', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (15, 'm', 'M', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (16, 'n', 'N', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (17, 'o', 'O', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (18, 'p', 'P', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (19, 'q', 'Q', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (20, 'r', 'R', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (21, 's', 'S', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (22, 'ş', 'Ş', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (23, 'ș', 'Ș', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (24, 't', 'T', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (25, 'ţ', 'Ţ', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (26, 'ț', 'Ț', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (27, 'u', 'U', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (28, 'v', 'V', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (29, 'w', 'W', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (30, 'x', 'X', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (31, 'y', 'Y', '');
INSERT INTO coll_test_ro (id, s1, s2, s3) values (32, 'z', 'Z', '');
SELECT id, s1 FROM coll_test_ro ORDER BY s1,id;
SELECT id, s2 FROM coll_test_ro ORDER BY s2,id;
SELECT id, s1, s2 FROM coll_test_ro WHERE s1 <> lower(s2) ORDER BY s1;
SELECT id, s1, s2 FROM coll_test_ro WHERE s2 <> upper(s1) ORDER BY s1;
UPDATE coll_test_ro SET s3=upper(s1);
SELECT id, s1, s2, s3 FROM coll_test_ro WHERE s3 <> s2 ORDER BY s3;
UPDATE coll_test_ro SET s3=lower(s2);
SELECT id, s1, s2, s3 FROM coll_test_ro WHERE s3 <> s1 ORDER BY s3;
CREATE TABLE coll_test_ro2 (id INTEGER, s varchar(10) collate utf8_ro_cs);
INSERT INTO coll_test_ro2 (id, s) SELECT id, s1 FROM coll_test_ro;
INSERT INTO coll_test_ro2 (id, s) SELECT id + 33, s2 FROM coll_test_ro;
SELECT id, s FROM coll_test_ro2 ORDER BY s,id;
DROP TABLE coll_test_ro2;
DROP TABLE coll_test_ro;
set names iso88591;
commit;
--+ holdcas off;
| bsd-3-clause |
exponent/exponent | android/versioned-abis/expoview-abi38_0_0/src/main/java/abi38_0_0/expo/modules/taskManager/TaskManagerUtils.java | 10404 | package abi38_0_0.expo.modules.taskManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.util.Log;
import org.unimodules.interfaces.taskManager.TaskInterface;
import org.unimodules.interfaces.taskManager.TaskManagerUtilsInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import androidx.annotation.NonNull;
import androidx.collection.ArraySet;
public class TaskManagerUtils implements TaskManagerUtilsInterface {
// Key that every job created by the task manager must contain in its extras bundle.
private static final String EXTRAS_REQUIRED_KEY = "expo.modules.taskManager";
private static final String TAG = "TaskManagerUtils";
// Request code number used for pending intents created by this module.
private static final int PENDING_INTENT_REQUEST_CODE = 5055;
private static final int DEFAULT_OVERRIDE_DEADLINE = 60 * 1000; // 1 minute
private static final Set<TaskInterface> sTasksReschedulingJob = new ArraySet<>();
//region TaskManagerUtilsInterface
@Override
public PendingIntent createTaskIntent(Context context, TaskInterface task) {
return createTaskIntent(context, task, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void cancelTaskIntent(Context context, String appId, String taskName) {
PendingIntent pendingIntent = createTaskIntent(context, appId, taskName, PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
pendingIntent.cancel();
}
}
@Override
public void scheduleJob(Context context, @NonNull TaskInterface task, List<PersistableBundle> data) {
if (task == null) {
Log.e(TAG, "Trying to schedule job for null task!");
} else {
updateOrScheduleJob(context, task, data);
}
}
@Override
public void cancelScheduledJob(Context context, int jobId) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.cancel(jobId);
} else {
Log.e(this.getClass().getName(), "Job scheduler not found!");
}
}
@Override
public List<PersistableBundle> extractDataFromJobParams(JobParameters params) {
PersistableBundle extras = params.getExtras();
List<PersistableBundle> data = new ArrayList<>();
int dataSize = extras.getInt("dataSize", 0);
for (int i = 0; i < dataSize; i++) {
data.add(extras.getPersistableBundle(String.valueOf(i)));
}
return data;
}
//endregion TaskManagerUtilsInterface
//region static helpers
static boolean notifyTaskJobCancelled(TaskInterface task) {
boolean isRescheduled = sTasksReschedulingJob.contains(task);
if (isRescheduled) {
sTasksReschedulingJob.remove(task);
}
return isRescheduled;
}
//endregion static helpers
//region private helpers
private void updateOrScheduleJob(Context context, TaskInterface task, List<PersistableBundle> data) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler == null) {
Log.e(this.getClass().getName(), "Job scheduler not found!");
return;
}
List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
Collections.sort(pendingJobs, new Comparator<JobInfo>() {
@Override
public int compare(JobInfo a, JobInfo b) {
return Integer.compare(a.getId(), b.getId());
}
});
// We will be looking for the lowest number that is not being used yet.
int newJobId = 0;
for (JobInfo jobInfo : pendingJobs) {
int jobId = jobInfo.getId();
if (isJobInfoRelatedToTask(jobInfo, task)) {
JobInfo mergedJobInfo = createJobInfoByAddingData(jobInfo, data);
// Add the task to the list of rescheduled tasks.
sTasksReschedulingJob.add(task);
try {
// Cancel jobs with the same ID to let them be rescheduled.
jobScheduler.cancel(jobId);
// Reschedule job for given task.
jobScheduler.schedule(mergedJobInfo);
} catch (IllegalStateException e) {
Log.e(this.getClass().getName(), "Unable to reschedule a job: " + e.getMessage());
}
return;
}
if (newJobId == jobId) {
newJobId++;
}
}
try {
// Given task doesn't have any pending jobs yet, create a new JobInfo and schedule it then.
JobInfo jobInfo = createJobInfo(context, task, newJobId, data);
jobScheduler.schedule(jobInfo);
} catch (IllegalStateException e) {
Log.e(this.getClass().getName(), "Unable to schedule a new job: " + e.getMessage());
}
}
private JobInfo createJobInfoByAddingData(JobInfo jobInfo, List<PersistableBundle> data) {
PersistableBundle mergedExtras = jobInfo.getExtras();
int dataSize = mergedExtras.getInt("dataSize", 0);
if (data != null) {
mergedExtras.putInt("dataSize", dataSize + data.size());
for (int i = 0; i < data.size(); i++) {
mergedExtras.putPersistableBundle(String.valueOf(dataSize + i), data.get(i));
}
}
return createJobInfo(jobInfo.getId(), jobInfo.getService(), mergedExtras);
}
private PendingIntent createTaskIntent(Context context, String appId, String taskName, int flags) {
if (context == null) {
return null;
}
Intent intent = new Intent(TaskBroadcastReceiver.INTENT_ACTION, null, context, TaskBroadcastReceiver.class);
Uri dataUri = new Uri.Builder()
.appendQueryParameter("appId", appId)
.appendQueryParameter("taskName", taskName)
.build();
intent.setData(dataUri);
return PendingIntent.getBroadcast(context, PENDING_INTENT_REQUEST_CODE, intent, flags);
}
private PendingIntent createTaskIntent(Context context, TaskInterface task, int flags) {
String appId = task.getAppId();
String taskName = task.getName();
return createTaskIntent(context, appId, taskName, flags);
}
private JobInfo createJobInfo(int jobId, ComponentName jobService, PersistableBundle extras) {
return new JobInfo.Builder(jobId, jobService)
.setExtras(extras)
.setMinimumLatency(0)
.setOverrideDeadline(DEFAULT_OVERRIDE_DEADLINE)
.build();
}
private JobInfo createJobInfo(Context context, TaskInterface task, int jobId, List<PersistableBundle> data) {
return createJobInfo(jobId, new ComponentName(context, TaskJobService.class), createExtrasForTask(task, data));
}
private PersistableBundle createExtrasForTask(TaskInterface task, List<PersistableBundle> data) {
PersistableBundle extras = new PersistableBundle();
extras.putInt(EXTRAS_REQUIRED_KEY, 1);
extras.putString("appId", task.getAppId());
extras.putString("taskName", task.getName());
if (data != null) {
extras.putInt("dataSize", data.size());
for (int i = 0; i < data.size(); i++) {
extras.putPersistableBundle(String.valueOf(i), data.get(i));
}
} else {
extras.putInt("dataSize", 0);
}
return extras;
}
private boolean isJobInfoRelatedToTask(JobInfo jobInfo, TaskInterface task) {
PersistableBundle extras = jobInfo.getExtras();
String appId = task.getAppId();
String taskName = task.getName();
if (extras.containsKey(EXTRAS_REQUIRED_KEY)) {
return appId.equals(extras.getString("appId", "")) && taskName.equals(extras.getString("taskName", ""));
}
return false;
}
//endregion private helpers
//region converting map to bundle
@SuppressWarnings("unchecked")
static Bundle mapToBundle(Map<String, Object> map) {
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
if (value instanceof Double) {
bundle.putDouble(key, (Double) value);
} else if (value instanceof Integer) {
bundle.putInt(key, (Integer) value);
} else if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Boolean) {
bundle.putBoolean(key, (Boolean) value);
} else if (value instanceof List) {
List<Object> list = (List<Object>) value;
Object first = list.get(0);
if (first == null || first instanceof Double) {
bundle.putDoubleArray(key, listToDoubleArray(list));
} else if (first instanceof Integer) {
bundle.putIntArray(key, listToIntArray(list));
} else if (first instanceof String) {
bundle.putStringArray(key, listToStringArray(list));
} else if (first instanceof Map) {
bundle.putParcelableArrayList(key, listToParcelableArrayList(list));
}
} else if (value instanceof Map) {
bundle.putBundle(key, mapToBundle((Map<String, Object>) value));
}
}
return bundle;
}
@SuppressWarnings("unchecked")
private static double[] listToDoubleArray(List<Object> list) {
double[] doubles = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
doubles[i] = (Double) list.get(i);
}
return doubles;
}
@SuppressWarnings("unchecked")
private static int[] listToIntArray(List<Object> list) {
int[] integers = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
integers[i] = (Integer) list.get(i);
}
return integers;
}
@SuppressWarnings("unchecked")
private static String[] listToStringArray(List<Object> list) {
String[] strings = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
strings[i] = list.get(i).toString();
}
return strings;
}
@SuppressWarnings("unchecked")
private static ArrayList<Parcelable> listToParcelableArrayList(List<Object> list) {
ArrayList<Parcelable> arrayList = new ArrayList<>();
for (Object item : list) {
Map<String, Object> map = (Map<String, Object>) item;
arrayList.add(mapToBundle(map));
}
return arrayList;
}
//endregion converting map to bundle
}
| bsd-3-clause |
mne-tools/mne-tools.github.io | 0.14/generated/mne.viz.plot_evoked.html | 13519 | <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mne.viz.plot_evoked — MNE 0.14.1 documentation</title>
<link rel="stylesheet" href="../_static/basic.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/gallery.css" type="text/css" />
<link rel="stylesheet" href="../_static/bootswatch-3.3.6/flatly/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.14.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</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="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="../_static/bootstrap-3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../_static/bootstrap-sphinx.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-37225609-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<link rel="stylesheet" href="../_static/style.css " type="text/css" />
<script type="text/javascript">
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);
js.id=id;js.src="https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<link rel="canonical" href="https://mne.tools/stable/index.html" />
</head>
<body>
<div id="navbar" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html"><span><img src="../_static/mne_logo_small.png"></span>
</a>
<span class="navbar-text navbar-version pull-left"><b>0.14.1</b></span>
</div>
<div class="collapse navbar-collapse nav-collapse">
<ul class="nav navbar-nav">
<li><a href="../getting_started.html">Get started</a></li>
<li><a href="../tutorials.html">Tutorials</a></li>
<li><a href="../auto_examples/index.html">Examples</a></li>
<li><a href="../python_reference.html">API</a></li>
<li><a href="../manual/index.html">Manual</a></li>
<li><a href="../contributing.html">Contribute</a></li>
<li><a href="../faq.html">FAQ</a></li>
<li class="dropdown globaltoc-container">
<a role="button"
id="dLabelGlobalToc"
data-toggle="dropdown"
data-target="#"
href="../index.html">Site <b class="caret"></b></a>
<ul class="dropdown-menu globaltoc"
role="menu"
aria-labelledby="dLabelGlobalToc"></ul>
</li>
<li class="hidden-sm"></li>
</ul>
<form class="navbar-form navbar-right" action="../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../index.html">
<img class="logo" src="../_static/mne_logo_small.png" alt="Logo"/>
</a></p><ul>
<li><a class="reference internal" href="#">mne.viz.plot_evoked</a></li>
</ul>
<form action="../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="col-md-12 content">
<div class="section" id="mne-viz-plot-evoked">
<h1>mne.viz.plot_evoked<a class="headerlink" href="#mne-viz-plot-evoked" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="mne.viz.plot_evoked">
<code class="descclassname">mne.viz.</code><code class="descname">plot_evoked</code><span class="sig-paren">(</span><em>evoked</em>, <em>picks=None</em>, <em>exclude=’bads’</em>, <em>unit=True</em>, <em>show=True</em>, <em>ylim=None</em>, <em>xlim=’tight’</em>, <em>proj=False</em>, <em>hline=None</em>, <em>units=None</em>, <em>scalings=None</em>, <em>titles=None</em>, <em>axes=None</em>, <em>gfp=False</em>, <em>window_title=None</em>, <em>spatial_colors=False</em>, <em>zorder=’unsorted’</em>, <em>selectable=True</em><span class="sig-paren">)</span><a class="reference external" href="http://github.com/mne-tools/mne-python/blob/maint/0.14/mne/viz/evoked.py#L491-L585"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#mne.viz.plot_evoked" title="Permalink to this definition">¶</a></dt>
<dd><p>Plot evoked data using butteryfly plots.</p>
<p>Left click to a line shows the channel name. Selecting an area by clicking
and holding left mouse button plots a topographic map of the painted area.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If bad channels are not excluded they are shown in red.</p>
</div>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>evoked</strong> : instance of Evoked</p>
<blockquote>
<div><p>The evoked data</p>
</div></blockquote>
<p><strong>picks</strong> : array-like of int | None</p>
<blockquote>
<div><p>The indices of channels to plot. If None show all.</p>
</div></blockquote>
<p><strong>exclude</strong> : list of str | ‘bads’</p>
<blockquote>
<div><p>Channels names to exclude from being shown. If ‘bads’, the
bad channels are excluded.</p>
</div></blockquote>
<p><strong>unit</strong> : bool</p>
<blockquote>
<div><p>Scale plot with channel (SI) unit.</p>
</div></blockquote>
<p><strong>show</strong> : bool</p>
<blockquote>
<div><p>Show figure if True.</p>
</div></blockquote>
<p><strong>ylim</strong> : dict | None</p>
<blockquote>
<div><p>ylim for plots (after scaling has been applied). e.g.
ylim = dict(eeg=[-20, 20])
Valid keys are eeg, mag, grad, misc. If None, the ylim parameter
for each channel equals the pyplot default.</p>
</div></blockquote>
<p><strong>xlim</strong> : ‘tight’ | tuple | None</p>
<blockquote>
<div><p>xlim for plots.</p>
</div></blockquote>
<p><strong>proj</strong> : bool | ‘interactive’</p>
<blockquote>
<div><p>If true SSP projections are applied before display. If ‘interactive’,
a check box for reversible selection of SSP projection vectors will
be shown.</p>
</div></blockquote>
<p><strong>hline</strong> : list of floats | None</p>
<blockquote>
<div><p>The values at which to show an horizontal line.</p>
</div></blockquote>
<p><strong>units</strong> : dict | None</p>
<blockquote>
<div><p>The units of the channel types used for axes lables. If None,
defaults to <cite>dict(eeg=’uV’, grad=’fT/cm’, mag=’fT’)</cite>.</p>
</div></blockquote>
<p><strong>scalings</strong> : dict | None</p>
<blockquote>
<div><p>The scalings of the channel types to be applied for plotting. If None,`
defaults to <cite>dict(eeg=1e6, grad=1e13, mag=1e15)</cite>.</p>
</div></blockquote>
<p><strong>titles</strong> : dict | None</p>
<blockquote>
<div><p>The titles associated with the channels. If None, defaults to
<cite>dict(eeg=’EEG’, grad=’Gradiometers’, mag=’Magnetometers’)</cite>.</p>
</div></blockquote>
<p><strong>axes</strong> : instance of Axis | list | None</p>
<blockquote>
<div><p>The axes to plot to. If list, the list must be a list of Axes of
the same length as the number of channel types. If instance of
Axes, there must be only one channel type plotted.</p>
</div></blockquote>
<p><strong>gfp</strong> : bool | ‘only’</p>
<blockquote>
<div><p>Plot GFP in green if True or “only”. If “only”, then the individual
channel traces will not be shown.</p>
</div></blockquote>
<p><strong>window_title</strong> : str | None</p>
<blockquote>
<div><p>The title to put at the top of the figure.</p>
</div></blockquote>
<p><strong>spatial_colors</strong> : bool</p>
<blockquote>
<div><p>If True, the lines are color coded by mapping physical sensor
coordinates into color values. Spatially similar channels will have
similar colors. Bad channels will be dotted. If False, the good
channels are plotted black and bad channels red. Defaults to False.</p>
</div></blockquote>
<p><strong>zorder</strong> : str | callable</p>
<blockquote>
<div><p>Which channels to put in the front or back. Only matters if
<cite>spatial_colors</cite> is used.
If str, must be <cite>std</cite> or <cite>unsorted</cite> (defaults to <cite>unsorted</cite>). If
<cite>std</cite>, data with the lowest standard deviation (weakest effects) will
be put in front so that they are not obscured by those with stronger
effects. If <cite>unsorted</cite>, channels are z-sorted as in the evoked
instance.
If callable, must take one argument: a numpy array of the same
dimensionality as the evoked raw data; and return a list of
unique integers corresponding to the number of channels.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 0.13.0.</span></p>
</div>
</div></blockquote>
<p><strong>selectable</strong> : bool</p>
<blockquote>
<div><p>Whether to use interactive features. If True (default), it is possible
to paint an area to draw topomaps. When False, the interactive features
are disabled. Disabling interactive features reduces memory consumption
and is useful when using <code class="docutils literal"><span class="pre">axes</span></code> parameter to draw multiaxes figures.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 0.13.0.</span></p>
</div>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>fig</strong> : instance of matplotlib.figure.Figure</p>
<blockquote class="last">
<div><p>Figure containing the butterfly plots.</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<div style='clear:both'></div></div>
</div>
</div>
</div>
<footer class="footer">
<div class="container"><img src="../_static/institutions.png" alt="Institutions"></div>
<div class="container">
<ul class="list-inline">
<li><a href="https://github.com/mne-tools/mne-python">GitHub</a></li>
<li>·</li>
<li><a href="https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis">Mailing list</a></li>
<li>·</li>
<li><a href="https://gitter.im/mne-tools/mne-python">Gitter</a></li>
<li>·</li>
<li><a href="whats_new.html">What's new</a></li>
<li>·</li>
<li><a href="faq.html#cite">Cite MNE</a></li>
<li class="pull-right"><a href="#">Back to top</a></li>
</ul>
<p>© Copyright 2012-2017, MNE Developers. Last updated on 2017-08-15.</p>
</div>
</footer>
<script src="https://mne.tools/versionwarning.js"></script>
</body>
</html> | bsd-3-clause |
splashblot/dronedb | lib/assets/test/spec/cartodb3/components/modals/modals-service-model.spec.js | 3915 | var CoreView = require('backbone/core-view');
var ModalsServiceModel = require('../../../../../javascripts/cartodb3/components/modals/modals-service-model');
var Router = require('../../../../../javascripts/cartodb3/routes/router');
describe('components/modals/modals-service-model', function () {
beforeEach(function () {
this.modals = new ModalsServiceModel();
this.willCreateModalSpy = jasmine.createSpy('willCreateModal');
this.didCreateModalSpy = jasmine.createSpy('didCreateModal');
this.modals.on('willCreateModal', this.willCreateModalSpy);
this.modals.on('didCreateModal', this.didCreateModalSpy);
});
describe('.create', function () {
var contentView, contentView2;
beforeEach(function () {
spyOn(Router, 'navigate');
spyOn(document.body, 'appendChild');
contentView = new CoreView();
spyOn(contentView, 'render').and.callThrough();
this.modalView = this.modals.create(function () {
return contentView;
});
});
it('should return a modal view', function () {
expect(this.modalView).toBeDefined();
});
it('should trigger a willCreateModal event', function () {
expect(this.willCreateModalSpy).toHaveBeenCalled();
});
it('should trigger a didCreateModal event', function () {
expect(this.didCreateModalSpy).toHaveBeenCalled();
});
it('should render the content view', function () {
expect(contentView.render).toHaveBeenCalled();
});
it('should append the modal to the body', function () {
expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView.el);
});
it('should add the special body class', function () {
expect(document.body.className).toContain('is-inDialog');
});
describe('subsequent calls', function () {
beforeEach(function () {
contentView2 = new CoreView();
spyOn(contentView2, 'render').and.callThrough();
this.modalView2 = this.modals.create(function () {
return contentView2;
});
});
it('should reuse modal view', function () {
expect(this.modalView2).toBe(this.modalView);
});
it('should append the new modal to the body', function () {
expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView2.el);
});
it('should keep the special body class', function () {
expect(document.body.className).toContain('is-inDialog');
});
describe('when destroyed', function () {
beforeEach(function () {
jasmine.clock().install();
this.destroyOnceSpy = jasmine.createSpy('destroyedModal');
this.modals.onDestroyOnce(this.destroyOnceSpy);
spyOn(this.modalView2, 'clean').and.callThrough();
this.modalView2.destroy();
});
afterEach(function () {
jasmine.clock().uninstall();
});
it('should not clean the view right away but wait until after animation', function () {
expect(this.modalView2.clean).not.toHaveBeenCalled();
});
it('should have closing animation', function () {
expect(this.modalView2.el.className).toContain('is-closing');
expect(this.modalView2.el.className).not.toContain('is-opening');
});
it('should remove the special body class', function () {
expect(document.body.className).not.toContain('is-inDialog');
});
describe('when close animation is done', function () {
beforeEach(function () {
jasmine.clock().tick(250);
});
it('should have cleaned the view', function () {
expect(this.modalView2.clean).toHaveBeenCalled();
});
it('should have triggered listener', function () {
expect(this.destroyOnceSpy).toHaveBeenCalled();
});
});
});
});
});
});
| bsd-3-clause |
patrick-luethi/Envision | OOVisualization/src/expressions/VArrayInitializerStyle.h | 2553 | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich 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.
**
***********************************************************************************************************************/
#pragma once
#include "../oovisualization_api.h"
#include "VisualizationBase/src/items/VListStyle.h"
#include "VisualizationBase/src/layouts/GridLayoutStyle.h"
namespace OOVisualization {
class OOVISUALIZATION_API VArrayInitializerStyle : public Super<Visualization::ItemStyle>
{
private:
Visualization::GridLayoutStyle layout_;
Visualization::VListStyle values_;
public:
void load(Visualization::StyleLoader& sl);
const Visualization::GridLayoutStyle& layout() const;
const Visualization::VListStyle& values() const;
};
inline const Visualization::GridLayoutStyle& VArrayInitializerStyle::layout() const { return layout_; }
inline const Visualization::VListStyle& VArrayInitializerStyle::values() const { return values_; }
} | bsd-3-clause |
bsipocz/astropy | astropy/utils/iers/iers.py | 31536 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The astropy.utils.iers package provides access to the tables provided by
the International Earth Rotation and Reference Systems Service, in
particular allowing interpolation of published UT1-UTC values for given
times. These are used in `astropy.time` to provide UT1 values. The polar
motions are also used for determining earth orientation for
celestial-to-terrestrial coordinate transformations
(in `astropy.coordinates`).
"""
from warnings import warn
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import numpy as np
from astropy import config as _config
from astropy import units as u
from astropy.table import Table, QTable
from astropy.utils.data import get_pkg_data_filename, clear_download_cache
from astropy import utils
from astropy.utils.exceptions import AstropyWarning
__all__ = ['Conf', 'conf',
'IERS', 'IERS_B', 'IERS_A', 'IERS_Auto',
'FROM_IERS_B', 'FROM_IERS_A', 'FROM_IERS_A_PREDICTION',
'TIME_BEFORE_IERS_RANGE', 'TIME_BEYOND_IERS_RANGE',
'IERS_A_FILE', 'IERS_A_URL', 'IERS_A_URL_MIRROR', 'IERS_A_README',
'IERS_B_FILE', 'IERS_B_URL', 'IERS_B_README',
'IERSRangeError', 'IERSStaleWarning']
# IERS-A default file name, URL, and ReadMe with content description
IERS_A_FILE = 'finals2000A.all'
IERS_A_URL = 'https://maia.usno.navy.mil/ser7/finals2000A.all'
IERS_A_URL_MIRROR = 'https://toshi.nofs.navy.mil/ser7/finals2000A.all'
IERS_A_README = get_pkg_data_filename('data/ReadMe.finals2000A')
# IERS-B default file name, URL, and ReadMe with content description
IERS_B_FILE = get_pkg_data_filename('data/eopc04_IAU2000.62-now')
IERS_B_URL = 'http://hpiers.obspm.fr/iers/eop/eopc04/eopc04_IAU2000.62-now'
IERS_B_README = get_pkg_data_filename('data/ReadMe.eopc04_IAU2000')
# Status/source values returned by IERS.ut1_utc
FROM_IERS_B = 0
FROM_IERS_A = 1
FROM_IERS_A_PREDICTION = 2
TIME_BEFORE_IERS_RANGE = -1
TIME_BEYOND_IERS_RANGE = -2
MJD_ZERO = 2400000.5
INTERPOLATE_ERROR = """\
interpolating from IERS_Auto using predictive values that are more
than {0} days old.
Normally you should not see this error because this class
automatically downloads the latest IERS-A table. Perhaps you are
offline? If you understand what you are doing then this error can be
suppressed by setting the auto_max_age configuration variable to
``None``:
from astropy.utils.iers import conf
conf.auto_max_age = None
"""
def download_file(*args, **kwargs):
"""
Overload astropy.utils.data.download_file within iers module to use a
custom (longer) wait time. This just passes through ``*args`` and
``**kwargs`` after temporarily setting the download_file remote timeout to
the local ``iers.conf.remote_timeout`` value.
"""
with utils.data.conf.set_temp('remote_timeout', conf.remote_timeout):
return utils.data.download_file(*args, **kwargs)
class IERSStaleWarning(AstropyWarning):
pass
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.utils.iers`.
"""
auto_download = _config.ConfigItem(
True,
'Enable auto-downloading of the latest IERS data. If set to False '
'then the local IERS-B file will be used by default. Default is True.')
auto_max_age = _config.ConfigItem(
30.0,
'Maximum age (days) of predictive data before auto-downloading. Default is 30.')
iers_auto_url = _config.ConfigItem(
IERS_A_URL,
'URL for auto-downloading IERS file data.')
iers_auto_url_mirror = _config.ConfigItem(
IERS_A_URL_MIRROR,
'Mirror URL for auto-downloading IERS file data.')
remote_timeout = _config.ConfigItem(
10.0,
'Remote timeout downloading IERS file data (seconds).')
conf = Conf()
class IERSRangeError(IndexError):
"""
Any error for when dates are outside of the valid range for IERS
"""
class IERS(QTable):
"""Generic IERS table class, defining interpolation functions.
Sub-classed from `astropy.table.QTable`. The table should hold columns
'MJD', 'UT1_UTC', 'dX_2000A'/'dY_2000A', and 'PM_x'/'PM_y'.
"""
iers_table = None
@classmethod
def open(cls, file=None, cache=False, **kwargs):
"""Open an IERS table, reading it from a file if not loaded before.
Parameters
----------
file : str or None
full local or network path to the ascii file holding IERS data,
for passing on to the ``read`` class methods (further optional
arguments that are available for some IERS subclasses can be added).
If None, use the default location from the ``read`` class method.
cache : bool
Whether to use cache. Defaults to False, since IERS files
are regularly updated.
Returns
-------
An IERS table class instance
Notes
-----
On the first call in a session, the table will be memoized (in the
``iers_table`` class attribute), and further calls to ``open`` will
return this stored table if ``file=None`` (the default).
If a table needs to be re-read from disk, pass on an explicit file
location or use the (sub-class) close method and re-open.
If the location is a network location it is first downloaded via
download_file.
For the IERS class itself, an IERS_B sub-class instance is opened.
"""
if file is not None or cls.iers_table is None:
if file is not None:
if urlparse(file).netloc:
kwargs.update(file=download_file(file, cache=cache))
else:
kwargs.update(file=file)
cls.iers_table = cls.read(**kwargs)
return cls.iers_table
@classmethod
def close(cls):
"""Remove the IERS table from the class.
This allows the table to be re-read from disk during one's session
(e.g., if one finds it is out of date and has updated the file).
"""
cls.iers_table = None
def mjd_utc(self, jd1, jd2=0.):
"""Turn a time to MJD, returning integer and fractional parts.
Parameters
----------
jd1 : float, array, or Time
first part of two-part JD, or Time object
jd2 : float or array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
Returns
-------
mjd : float or array
integer part of MJD
utc : float or array
fractional part of MJD
"""
try: # see if this is a Time object
jd1, jd2 = jd1.utc.jd1, jd1.utc.jd2
except Exception:
pass
mjd = np.floor(jd1 - MJD_ZERO + jd2)
utc = jd1 - (MJD_ZERO+mjd) + jd2
return mjd, utc
def ut1_utc(self, jd1, jd2=0., return_status=False):
"""Interpolate UT1-UTC corrections in IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
ut1_utc : float or float array
UT1-UTC, interpolated in IERS Table
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['UT1_UTC'],
self.ut1_utc_source if return_status else None)
def dcip_xy(self, jd1, jd2=0., return_status=False):
"""Interpolate CIP corrections in IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD (default 0., ignored if jd1 is Time)
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
D_x : Quantity with angle units
x component of CIP correction for the requested times
D_y : Quantity with angle units
y component of CIP correction for the requested times
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['dX_2000A', 'dY_2000A'],
self.dcip_source if return_status else None)
def pm_xy(self, jd1, jd2=0., return_status=False):
"""Interpolate polar motions from IERS Table for given dates.
Parameters
----------
jd1 : float, float array, or Time object
first part of two-part JD, or Time object
jd2 : float or float array, optional
second part of two-part JD.
Default is 0., ignored if jd1 is `~astropy.time.Time`.
return_status : bool
Whether to return status values. If False (default),
raise ``IERSRangeError`` if any time is out of the range covered
by the IERS table.
Returns
-------
PM_x : Quantity with angle units
x component of polar motion for the requested times
PM_y : Quantity with angle units
y component of polar motion for the requested times
status : int or int array
Status values (if ``return_status``=``True``)::
``iers.FROM_IERS_B``
``iers.FROM_IERS_A``
``iers.FROM_IERS_A_PREDICTION``
``iers.TIME_BEFORE_IERS_RANGE``
``iers.TIME_BEYOND_IERS_RANGE``
"""
return self._interpolate(jd1, jd2, ['PM_x', 'PM_y'],
self.pm_source if return_status else None)
def _check_interpolate_indices(self, indices_orig, indices_clipped, max_input_mjd):
"""
Check that the indices from interpolation match those after clipping
to the valid table range. This method gets overridden in the IERS_Auto
class because it has different requirements.
"""
if np.any(indices_orig != indices_clipped):
raise IERSRangeError('(some) times are outside of range covered '
'by IERS table.')
def _interpolate(self, jd1, jd2, columns, source=None):
mjd, utc = self.mjd_utc(jd1, jd2)
# enforce array
is_scalar = not hasattr(mjd, '__array__') or mjd.ndim == 0
if is_scalar:
mjd = np.array([mjd])
utc = np.array([utc])
self._refresh_table_as_needed(mjd)
# For typical format, will always find a match (since MJD are integer)
# hence, important to define which side we will be; this ensures
# self['MJD'][i-1]<=mjd<self['MJD'][i]
i = np.searchsorted(self['MJD'].value, mjd, side='right')
# Get index to MJD at or just below given mjd, clipping to ensure we
# stay in range of table (status will be set below for those outside)
i1 = np.clip(i, 1, len(self) - 1)
i0 = i1 - 1
mjd_0, mjd_1 = self['MJD'][i0].value, self['MJD'][i1].value
results = []
for column in columns:
val_0, val_1 = self[column][i0], self[column][i1]
d_val = val_1 - val_0
if column == 'UT1_UTC':
# Check & correct for possible leap second (correcting diff.,
# not 1st point, since jump can only happen right at 2nd point)
d_val -= d_val.round()
# Linearly interpolate (which is what TEMPO does for UT1-UTC, but
# may want to follow IERS gazette #13 for more precise
# interpolation and correction for tidal effects;
# http://maia.usno.navy.mil/iers-gaz13)
val = val_0 + (mjd - mjd_0 + utc) / (mjd_1 - mjd_0) * d_val
# Do not extrapolate outside range, instead just propagate last values.
val[i == 0] = self[column][0]
val[i == len(self)] = self[column][-1]
if is_scalar:
val = val[0]
results.append(val)
if source:
# Set status to source, using the routine passed in.
status = source(i1)
# Check for out of range
status[i == 0] = TIME_BEFORE_IERS_RANGE
status[i == len(self)] = TIME_BEYOND_IERS_RANGE
if is_scalar:
status = status[0]
results.append(status)
return results
else:
self._check_interpolate_indices(i1, i, np.max(mjd))
return results[0] if len(results) == 1 else results
def _refresh_table_as_needed(self, mjd):
"""
Potentially update the IERS table in place depending on the requested
time values in ``mdj`` and the time span of the table. The base behavior
is not to update the table. ``IERS_Auto`` overrides this method.
"""
pass
def ut1_utc_source(self, i):
"""Source for UT1-UTC. To be overridden by subclass."""
return np.zeros_like(i)
def dcip_source(self, i):
"""Source for CIP correction. To be overridden by subclass."""
return np.zeros_like(i)
def pm_source(self, i):
"""Source for polar motion. To be overridden by subclass."""
return np.zeros_like(i)
@property
def time_now(self):
"""
Property to provide the current time, but also allow for explicitly setting
the _time_now attribute for testing purposes.
"""
from astropy.time import Time
try:
return self._time_now
except Exception:
return Time.now()
class IERS_A(IERS):
"""IERS Table class targeted to IERS A, provided by USNO.
These include rapid turnaround and predicted times.
See http://maia.usno.navy.mil/
Notes
-----
The IERS A file is not part of astropy. It can be downloaded from
``iers.IERS_A_URL`` or ``iers.IERS_A_URL_MIRROR``. See ``iers.__doc__``
for instructions on use in ``Time``, etc.
"""
iers_table = None
@classmethod
def _combine_a_b_columns(cls, iers_a):
"""
Return a new table with appropriate combination of IERS_A and B columns.
"""
# IERS A has some rows at the end that hold nothing but dates & MJD
# presumably to be filled later. Exclude those a priori -- there
# should at least be a predicted UT1-UTC and PM!
table = iers_a[~iers_a['UT1_UTC_A'].mask &
~iers_a['PolPMFlag_A'].mask]
# This does nothing for IERS_A, but allows IERS_Auto to ensure the
# IERS B values in the table are consistent with the true ones.
table = cls._substitute_iers_b(table)
# Run np.where on the data from the table columns, since in numpy 1.9
# it otherwise returns an only partially initialized column.
table['UT1_UTC'] = np.where(table['UT1_UTC_B'].mask,
table['UT1_UTC_A'].data,
table['UT1_UTC_B'].data)
# Ensure the unit is correct, for later column conversion to Quantity.
table['UT1_UTC'].unit = table['UT1_UTC_A'].unit
table['UT1Flag'] = np.where(table['UT1_UTC_B'].mask,
table['UT1Flag_A'].data,
'B')
# Repeat for polar motions.
table['PM_x'] = np.where(table['PM_X_B'].mask,
table['PM_x_A'].data,
table['PM_X_B'].data)
table['PM_x'].unit = table['PM_x_A'].unit
table['PM_y'] = np.where(table['PM_Y_B'].mask,
table['PM_y_A'].data,
table['PM_Y_B'].data)
table['PM_y'].unit = table['PM_y_A'].unit
table['PolPMFlag'] = np.where(table['PM_X_B'].mask,
table['PolPMFlag_A'].data,
'B')
table['dX_2000A'] = np.where(table['dX_2000A_B'].mask,
table['dX_2000A_A'].data,
table['dX_2000A_B'].data)
table['dX_2000A'].unit = table['dX_2000A_A'].unit
table['dY_2000A'] = np.where(table['dY_2000A_B'].mask,
table['dY_2000A_A'].data,
table['dY_2000A_B'].data)
table['dY_2000A'].unit = table['dY_2000A_A'].unit
table['NutFlag'] = np.where(table['dX_2000A_B'].mask,
table['NutFlag_A'].data,
'B')
# Get the table index for the first row that has predictive values
# PolPMFlag_A IERS (I) or Prediction (P) flag for
# Bull. A polar motion values
# UT1Flag_A IERS (I) or Prediction (P) flag for
# Bull. A UT1-UTC values
is_predictive = (table['UT1Flag_A'] == 'P') | (table['PolPMFlag_A'] == 'P')
table.meta['predictive_index'] = np.min(np.flatnonzero(is_predictive))
table.meta['predictive_mjd'] = table['MJD'][table.meta['predictive_index']]
return table
@classmethod
def _substitute_iers_b(cls, table):
# See documentation in IERS_Auto.
return table
@classmethod
def read(cls, file=None, readme=None):
"""Read IERS-A table from a finals2000a.* file provided by USNO.
Parameters
----------
file : str
full path to ascii file holding IERS-A data.
Defaults to ``iers.IERS_A_FILE``.
readme : str
full path to ascii file holding CDS-style readme.
Defaults to package version, ``iers.IERS_A_README``.
Returns
-------
``IERS_A`` class instance
"""
if file is None:
file = IERS_A_FILE
if readme is None:
readme = IERS_A_README
# Read in as a regular Table, including possible masked columns.
# Columns will be filled and converted to Quantity in cls.__init__.
iers_a = Table.read(file, format='cds', readme=readme)
iers_a = Table(iers_a, masked=True, copy=False)
# Combine the A and B data for UT1-UTC and PM columns
table = cls._combine_a_b_columns(iers_a)
table.meta['data_path'] = file
table.meta['readme_path'] = readme
# Fill any masked values, and convert to a QTable.
return cls(table.filled())
def ut1_utc_source(self, i):
"""Set UT1-UTC source flag for entries in IERS table"""
ut1flag = self['UT1Flag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[ut1flag == 'I'] = FROM_IERS_A
source[ut1flag == 'P'] = FROM_IERS_A_PREDICTION
return source
def dcip_source(self, i):
"""Set CIP correction source flag for entries in IERS table"""
nutflag = self['NutFlag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[nutflag == 'I'] = FROM_IERS_A
source[nutflag == 'P'] = FROM_IERS_A_PREDICTION
return source
def pm_source(self, i):
"""Set polar motion source flag for entries in IERS table"""
pmflag = self['PolPMFlag'][i]
source = np.ones_like(i) * FROM_IERS_B
source[pmflag == 'I'] = FROM_IERS_A
source[pmflag == 'P'] = FROM_IERS_A_PREDICTION
return source
class IERS_B(IERS):
"""IERS Table class targeted to IERS B, provided by IERS itself.
These are final values; see http://www.iers.org/
Notes
-----
If the package IERS B file (```iers.IERS_B_FILE``) is out of date, a new
version can be downloaded from ``iers.IERS_B_URL``.
"""
iers_table = None
@classmethod
def read(cls, file=None, readme=None, data_start=14):
"""Read IERS-B table from a eopc04_iau2000.* file provided by IERS.
Parameters
----------
file : str
full path to ascii file holding IERS-B data.
Defaults to package version, ``iers.IERS_B_FILE``.
readme : str
full path to ascii file holding CDS-style readme.
Defaults to package version, ``iers.IERS_B_README``.
data_start : int
starting row. Default is 14, appropriate for standard IERS files.
Returns
-------
``IERS_B`` class instance
"""
if file is None:
file = IERS_B_FILE
if readme is None:
readme = IERS_B_README
# Read in as a regular Table, including possible masked columns.
# Columns will be filled and converted to Quantity in cls.__init__.
iers_b = Table.read(file, format='cds', readme=readme,
data_start=data_start)
return cls(iers_b.filled())
def ut1_utc_source(self, i):
"""Set UT1-UTC source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
def dcip_source(self, i):
"""Set CIP correction source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
def pm_source(self, i):
"""Set PM source flag for entries in IERS table"""
return np.ones_like(i) * FROM_IERS_B
class IERS_Auto(IERS_A):
"""
Provide most-recent IERS data and automatically handle downloading
of updated values as necessary.
"""
iers_table = None
@classmethod
def open(cls):
"""If the configuration setting ``astropy.utils.iers.conf.auto_download``
is set to True (default), then open a recent version of the IERS-A
table with predictions for UT1-UTC and polar motion out to
approximately one year from now. If the available version of this file
is older than ``astropy.utils.iers.conf.auto_max_age`` days old
(or non-existent) then it will be downloaded over the network and cached.
If the configuration setting ``astropy.utils.iers.conf.auto_download``
is set to False then ``astropy.utils.iers.IERS()`` is returned. This
is normally the IERS-B table that is supplied with astropy.
On the first call in a session, the table will be memoized (in the
``iers_table`` class attribute), and further calls to ``open`` will
return this stored table.
Returns
-------
`~astropy.table.QTable` instance with IERS (Earth rotation) data columns
"""
if not conf.auto_download:
cls.iers_table = IERS.open()
return cls.iers_table
all_urls = (conf.iers_auto_url, conf.iers_auto_url_mirror)
if cls.iers_table is not None:
# If the URL has changed, we need to redownload the file, so we
# should ignore the internally cached version.
if cls.iers_table.meta.get('data_url') in all_urls:
return cls.iers_table
dl_success = False
err_list = []
for url in all_urls:
try:
filename = download_file(url, cache=True)
except Exception as err:
err_list.append(str(err))
else:
dl_success = True
break
if not dl_success:
# Issue a warning here, perhaps user is offline. An exception
# will be raised downstream when actually trying to interpolate
# predictive values.
warn(AstropyWarning('failed to download {}, using local IERS-B: {}'
.format(' and '.join(all_urls),
';'.join(err_list)))) # noqa
cls.iers_table = IERS.open()
return cls.iers_table
cls.iers_table = cls.read(file=filename)
cls.iers_table.meta['data_url'] = str(url)
return cls.iers_table
def _check_interpolate_indices(self, indices_orig, indices_clipped, max_input_mjd):
"""Check that the indices from interpolation match those after clipping to the
valid table range. The IERS_Auto class is exempted as long as it has
sufficiently recent available data so the clipped interpolation is
always within the confidence bounds of current Earth rotation
knowledge.
"""
predictive_mjd = self.meta['predictive_mjd']
# See explanation in _refresh_table_as_needed for these conditions
auto_max_age = (conf.auto_max_age if conf.auto_max_age is not None
else np.finfo(float).max)
if (max_input_mjd > predictive_mjd and
self.time_now.mjd - predictive_mjd > auto_max_age):
raise ValueError(INTERPOLATE_ERROR.format(auto_max_age))
def _refresh_table_as_needed(self, mjd):
"""Potentially update the IERS table in place depending on the requested
time values in ``mjd`` and the time span of the table.
For IERS_Auto the behavior is that the table is refreshed from the IERS
server if both the following apply:
- Any of the requested IERS values are predictive. The IERS-A table
contains predictive data out for a year after the available
definitive values.
- The first predictive values are at least ``conf.auto_max_age days`` old.
In other words the IERS-A table was created by IERS long enough
ago that it can be considered stale for predictions.
"""
max_input_mjd = np.max(mjd)
now_mjd = self.time_now.mjd
# IERS-A table contains predictive data out for a year after
# the available definitive values.
fpi = self.meta['predictive_index']
predictive_mjd = self.meta['predictive_mjd']
# Update table in place if necessary
auto_max_age = (conf.auto_max_age if conf.auto_max_age is not None
else np.finfo(float).max)
# If auto_max_age is smaller than IERS update time then repeated downloads may
# occur without getting updated values (giving a IERSStaleWarning).
if auto_max_age < 10:
raise ValueError('IERS auto_max_age configuration value must be larger than 10 days')
if (max_input_mjd > predictive_mjd and
now_mjd - predictive_mjd > auto_max_age):
all_urls = (conf.iers_auto_url, conf.iers_auto_url_mirror)
dl_success = False
err_list = []
# Get the latest version
for url in all_urls:
try:
clear_download_cache(url)
filename = download_file(url, cache=True)
except Exception as err:
err_list.append(str(err))
else:
dl_success = True
break
if not dl_success:
# Issue a warning here, perhaps user is offline. An exception
# will be raised downstream when actually trying to interpolate
# predictive values.
warn(AstropyWarning('failed to download {}: {}.\nA coordinate or time-related '
'calculation might be compromised or fail because the dates are '
'not covered by the available IERS file. See the '
'"IERS data access" section of the astropy documentation '
'for additional information on working offline.'
.format(' and '.join(all_urls), ';'.join(err_list))))
return
new_table = self.__class__.read(file=filename)
new_table.meta['data_url'] = str(url)
# New table has new values?
if new_table['MJD'][-1] > self['MJD'][-1]:
# Replace *replace* current values from the first predictive index through
# the end of the current table. This replacement is much faster than just
# deleting all rows and then using add_row for the whole duration.
new_fpi = np.searchsorted(new_table['MJD'].value, predictive_mjd, side='right')
n_replace = len(self) - fpi
self[fpi:] = new_table[new_fpi:new_fpi + n_replace]
# Sanity check for continuity
if new_table['MJD'][new_fpi + n_replace] - self['MJD'][-1] != 1.0 * u.d:
raise ValueError('unexpected gap in MJD when refreshing IERS table')
# Now add new rows in place
for row in new_table[new_fpi + n_replace:]:
self.add_row(row)
self.meta.update(new_table.meta)
else:
warn(IERSStaleWarning(
'IERS_Auto predictive values are older than {} days but downloading '
'the latest table did not find newer values'.format(conf.auto_max_age)))
@classmethod
def _substitute_iers_b(cls, table):
"""Substitute IERS B values with those from a real IERS B table.
IERS-A has IERS-B values included, but for reasons unknown these
do not match the latest IERS-B values (see comments in #4436).
Here, we use the bundled astropy IERS-B table to overwrite the values
in the downloaded IERS-A table.
"""
iers_b = IERS_B.open()
# Substitute IERS-B values for existing B values in IERS-A table
mjd_b = table['MJD'][~table['UT1_UTC_B'].mask]
i0 = np.searchsorted(iers_b['MJD'].value, mjd_b[0], side='left')
i1 = np.searchsorted(iers_b['MJD'].value, mjd_b[-1], side='right')
iers_b = iers_b[i0:i1]
n_iers_b = len(iers_b)
# If there is overlap then replace IERS-A values from available IERS-B
if n_iers_b > 0:
# Sanity check that we are overwriting the correct values
if not np.allclose(table['MJD'][:n_iers_b], iers_b['MJD'].value):
raise ValueError('unexpected mismatch when copying '
'IERS-B values into IERS-A table.')
# Finally do the overwrite
table['UT1_UTC_B'][:n_iers_b] = iers_b['UT1_UTC'].value
table['PM_X_B'][:n_iers_b] = iers_b['PM_x'].value
table['PM_Y_B'][:n_iers_b] = iers_b['PM_y'].value
return table
# by default for IERS class, read IERS-B table
IERS.read = IERS_B.read
| bsd-3-clause |
snowplow/snowplow-javascript-tracker | plugins/browser-plugin-youtube-tracking/rollup.config.js | 2950 | /*
* Copyright (c) 2022 Snowplow Analytics Ltd
* 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.
*/
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import ts from 'rollup-plugin-ts';
import { banner } from '../../banner';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { terser } from 'rollup-plugin-terser';
import cleanup from 'rollup-plugin-cleanup';
import pkg from './package.json';
import { builtinModules } from 'module';
const umdPlugins = [nodeResolve({ browser: true }), commonjs(), ts()];
const umdName = 'snowplowYouTubeTracking';
export default [
// CommonJS (for Node) and ES module (for bundlers) build.
{
input: './src/index.ts',
plugins: [...umdPlugins, banner(true)],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main, format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
plugins: [...umdPlugins, compiler(), terser(), cleanup({ comments: 'none' }), banner(true)],
treeshake: { moduleSideEffects: ['sha1'] },
output: [{ file: pkg.main.replace('.js', '.min.js'), format: 'umd', sourcemap: true, name: umdName }],
},
{
input: './src/index.ts',
external: [...builtinModules, ...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)],
plugins: [ts(), banner(true)],
output: [{ file: pkg.module, format: 'es', sourcemap: true }],
},
];
| bsd-3-clause |
Eye4web/E4WSms | src/E4W/Sms/Service/SmsService.php | 1405 | <?php
namespace E4W\Sms\Service;
use E4W\Sms\Adapter\Sms\SmsAdapterInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;
class SmsService implements EventManagerAwareInterface
{
use EventManagerAwareTrait;
/** @var SmsAdapterInterface */
protected $adapter;
/**
* Send message
*
* @param $to
* @param $text
* @param string $from
* @return mixed
*/
public function send($to, $text, $from = null)
{
$this->getEventManager()->trigger('send', $this, [
'to' => $to,
'text' => $text,
'from' => $from,
]);
return $this->adapter->send($to, $text, $from);
}
public function receive(array $data)
{
if (!method_exists($this->adapter, 'receive')) {
throw new \Exception('The adapter does not support two-ways sms');
}
$this->getEventManager()->trigger('receive', $this, [
'data' => $data,
]);
return $this->adapter->receive($data);
}
/**
* Set adapter
*
* @param SmsAdapterInterface $adapter
*/
public function setAdapter(SmsAdapterInterface $adapter)
{
$this->adapter = $adapter;
}
/**
* @return SmsAdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
}
| bsd-3-clause |
mattbasta/amo-validator | tests/compat/test_gecko22.py | 1747 | from helper import CompatTestCase
from validator.compat import FX22_DEFINITION
class TestFX22Compat(CompatTestCase):
"""Test that compatibility tests for Gecko 22 are properly executed."""
VERSION = FX22_DEFINITION
def test_nsigh2(self):
self.run_regex_for_compat("nsIGlobalHistory2", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsilms(self):
self.run_regex_for_compat("nsILivemarkService", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_mpat(self):
self.run_regex_for_compat("markPageAsTyped", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_favicon(self):
self.run_regex_for_compat("setFaviconUrlForPage", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsitv(self):
self.run_regex_for_compat("getRowProperties", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_nsipb(self):
self.run_regex_for_compat("nsIPrivateBrowsingService", is_js=True)
self.assert_silent()
self.assert_compat_error(type_="warning")
def test_fullZoom(self):
self.run_regex_for_compat("fullZoom", is_js=True)
self.assert_silent()
self.assert_compat_error()
def test_userdata(self):
self.run_regex_for_compat("getUserData", is_js=True)
self.assert_silent()
self.assert_compat_warning()
def test_tooltip(self):
self.run_regex_for_compat("FillInHTMLTooltip", is_js=True)
self.assert_silent()
self.assert_compat_warning()
| bsd-3-clause |
robert-mill/cover | backend/models/Nationality.php | 754 | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "nationality".
*
* @property integer $nationality_id
* @property string $nationality
*/
class Nationality extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'nationality';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nationality'], 'required'],
[['nationality'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'nationality_id' => 'Nationality ID',
'nationality' => 'Nationality',
];
}
}
| bsd-3-clause |
princeofdarkness76/trap | transports/socket/mail-lists.html | 10375 | <!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia at 2014-11-25
| Rendered using Apache Maven Fluido Skin 1.3.0
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20141125" />
<meta http-equiv="Content-Language" content="en" />
<title>Socket Transport Parent - Project Mailing Lists</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.3.0.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.3.0.min.js"></script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<div id="bannerLeft">
<h2>Socket Transport Parent</h2>
</div>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2014-11-25</li>
<li class="divider">|</li> <li id="projectVersion">Version: 1.3</li>
<li class="divider">|</li> <li class="">
<a href="../../index.html" title="Trap">
Trap</a>
</li>
<li class="divider ">/</li>
<li class="">
<a href="../" title="TrAP Transports">
TrAP Transports</a>
</li>
<li class="divider ">/</li>
<li class="">
<a href="./" title="Socket Transport Parent">
Socket Transport Parent</a>
</li>
<li class="divider ">/</li>
<li class="">Project Mailing Lists</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Trap 1.3</li>
<li>
<a href="../../index.html" title="Introduction">
<i class="none"></i>
Introduction</a>
</li>
<li>
<a href="../../trap-api/quickstart.html" title="Java Quickstart">
<i class="none"></i>
Java Quickstart</a>
</li>
<li>
<a href="../../trap-js/index.html" title="JavaScript Quickstart">
<i class="none"></i>
JavaScript Quickstart</a>
</li>
<li>
<a href="../../channels.html" title="Channels">
<i class="none"></i>
Channels</a>
</li>
<li>
<a href="../../configuration.html" title="Configuration">
<i class="none"></i>
Configuration</a>
</li>
<li class="nav-header">Language Specific Documentation</li>
<li>
<a href="../../trap-api/index.html" title="Java">
<i class="none"></i>
Java</a>
</li>
<li>
<a href="../../trap-js/index.html" title="JavaScript">
<i class="none"></i>
JavaScript</a>
</li>
<li class="nav-header">Modules</li>
<li>
<a href="socket-client-ernio/index.html" title="Socket Client using ER NIO">
<i class="none"></i>
Socket Client using ER NIO</a>
</li>
<li>
<a href="socket-server-ernio/index.html" title="Socket Server using ER NIO">
<i class="none"></i>
Socket Server using ER NIO</a>
</li>
<li>
<a href="socket-constants/index.html" title="Socket Constants">
<i class="none"></i>
Socket Constants</a>
</li>
<li>
<a href="socket-tests/index.html" title="Socket Tests">
<i class="none"></i>
Socket Tests</a>
</li>
<li class="nav-header">Project Documentation</li>
<li>
<a href="project-info.html" title="Project Information">
<i class="icon-chevron-down"></i>
Project Information</a>
<ul class="nav nav-list">
<li>
<a href="index.html" title="About">
<i class="none"></i>
About</a>
</li>
<li>
<a href="plugin-management.html" title="Plugin Management">
<i class="none"></i>
Plugin Management</a>
</li>
<li>
<a href="distribution-management.html" title="Distribution Management">
<i class="none"></i>
Distribution Management</a>
</li>
<li>
<a href="dependency-info.html" title="Dependency Information">
<i class="none"></i>
Dependency Information</a>
</li>
<li>
<a href="dependency-convergence.html" title="Dependency Convergence">
<i class="none"></i>
Dependency Convergence</a>
</li>
<li>
<a href="source-repository.html" title="Source Repository">
<i class="none"></i>
Source Repository</a>
</li>
<li class="active">
<a href="#"><i class="none"></i>Mailing Lists</a>
</li>
<li>
<a href="issue-tracking.html" title="Issue Tracking">
<i class="none"></i>
Issue Tracking</a>
</li>
<li>
<a href="integration.html" title="Continuous Integration">
<i class="none"></i>
Continuous Integration</a>
</li>
<li>
<a href="plugins.html" title="Project Plugins">
<i class="none"></i>
Project Plugins</a>
</li>
<li>
<a href="license.html" title="Project License">
<i class="none"></i>
Project License</a>
</li>
<li>
<a href="modules.html" title="Project Modules">
<i class="none"></i>
Project Modules</a>
</li>
<li>
<a href="dependency-management.html" title="Dependency Management">
<i class="none"></i>
Dependency Management</a>
</li>
<li>
<a href="team-list.html" title="Project Team">
<i class="none"></i>
Project Team</a>
</li>
<li>
<a href="project-summary.html" title="Project Summary">
<i class="none"></i>
Project Summary</a>
</li>
<li>
<a href="dependencies.html" title="Dependencies">
<i class="none"></i>
Dependencies</a>
</li>
</ul>
</li>
</ul>
<form id="search-form" action="http://www.google.com/search" method="get" >
<input value="ericssonresearch.github.io/trap/transports/socket/" name="sitesearch" type="hidden"/>
<input class="search-query" name="q" id="query" type="text" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=search-form"></script>
<hr class="divider" />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2>Project Mailing Lists<a name="Project_Mailing_Lists"></a></h2><a name="Project_Mailing_Lists"></a>
<p>There are no mailing lists currently associated with this project.</p></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row span12">Copyright © 2014
<a href="https://www.ericsson.com">Ericsson AB</a>.
All Rights Reserved.
</div>
</div>
</footer>
</body>
</html> | bsd-3-clause |
madbook/reddit-plugin-gold | reddit_gold/controllers.py | 3510 | from pylons import tmpl_context as c
from pylons import app_globals as g
from pylons.i18n import _
from r2.config import feature
from r2.controllers import add_controller
from r2.controllers.reddit_base import RedditController
from r2.lib.errors import errors
from r2.lib.require import require, RequirementException
from r2.lib.validator import (
json_validate,
validate,
validatedForm,
VBoolean,
VExistingUname,
VGold,
VJSON,
VModhash,
VUser,
)
from reddit_gold.models import SnoovatarsByAccount
from reddit_gold.pages import (
GoldInfoPage,
Snoovatar,
SnoovatarProfilePage,
)
from reddit_gold.validators import VSnooColor
@add_controller
class GoldController(RedditController):
def GET_about(self):
return GoldInfoPage(
_("gold"),
show_sidebar=False,
page_classes=["gold-page-ga-tracking"]
).render()
def GET_partners(self):
self.redirect("/gold/about", code=301)
@validate(
vuser=VExistingUname("username"),
)
def GET_snoovatar(self, vuser):
if not vuser or vuser._deleted or not vuser.gold:
self.abort404()
snoovatar = SnoovatarsByAccount.load(vuser, "snoo")
user_is_owner = c.user_is_loggedin and c.user == vuser
if not user_is_owner:
if not snoovatar or not snoovatar["public"]:
self.abort404()
return SnoovatarProfilePage(
user=vuser,
content=Snoovatar(
editable=user_is_owner,
snoovatar=snoovatar,
username=vuser.name,
),
).render()
@add_controller
class GoldApiController(RedditController):
@validatedForm(
VUser(),
VGold(),
VModhash(),
public=VBoolean("public"),
snoo_color=VSnooColor("snoo_color"),
unvalidated_components=VJSON("components"),
)
def POST_snoovatar(self, form, jquery, public, snoo_color, unvalidated_components):
if form.has_errors("components",
errors.NO_TEXT,
errors.TOO_LONG,
errors.BAD_STRING,
):
return
if form.has_errors("snoo_color", errors.BAD_CSS_COLOR):
return
try:
tailors = g.plugins["gold"].tailors_data
validated = {}
for tailor in tailors:
tailor_name = tailor["name"]
component = unvalidated_components.get(tailor_name)
# if the tailor requires a selection, ensure there is one
if not tailor["allow_clear"]:
require(component)
# ensure this dressing exists
dressing = component.get("dressingName")
if dressing:
for d in tailor["dressings"]:
if dressing == d["name"]:
break
else:
raise RequirementException
validated[tailor_name] = component
except RequirementException:
c.errors.add(errors.INVALID_SNOOVATAR, field="components")
form.has_errors("components", errors.INVALID_SNOOVATAR)
return
SnoovatarsByAccount.save(
user=c.user,
name="snoo",
public=public,
snoo_color=snoo_color,
components=validated,
)
| bsd-3-clause |
enderlabs/django-error-capture-middleware | src/error_capture_middleware/handlers/plain.py | 306 | from django.http import HttpResponse
from error_capture_middleware import ErrorCaptureHandler
class PlainExceptionsMiddleware(ErrorCaptureHandler):
def handle(self, request, exception, tb):
return HttpResponse("\n".join(tb),
content_type="text/plain", status=500) | bsd-3-clause |
exponent/exponent | ios/versioned-react-native/ABI39_0_0/Expo/UMReactNativeAdapter/ABI39_0_0UMReactNativeAdapter/UMNativeModulesProxy/ABI39_0_0UMNativeModulesProxy.h | 635 | // Copyright 2018-present 650 Industries. All rights reserved.
#import <ABI39_0_0React/ABI39_0_0RCTBridgeModule.h>
#import <ABI39_0_0UMCore/ABI39_0_0UMInternalModule.h>
#import <ABI39_0_0UMCore/ABI39_0_0UMModuleRegistry.h>
// ABI39_0_0RCTBridgeModule capable of receiving method calls from JS and forwarding them
// to proper exported universal modules. Also, it exports important constants to JS, like
// properties of exported methods and modules' constants.
@interface ABI39_0_0UMNativeModulesProxy : NSObject <ABI39_0_0RCTBridgeModule>
- (instancetype)initWithModuleRegistry:(ABI39_0_0UMModuleRegistry *)moduleRegistry;
@end
| bsd-3-clause |
darwin/upgradr | ieaddon/Upgradr/DPIHelper.cpp | 1874 | // Copyright (c) 2006, Sven Groot, see license.txt for details
#include "stdafx.h"
using namespace Gdiplus;
const float g_baseDpi = 96.0f;
float CDPIHelper::m_fScaleX = CDPIHelper::GetLogPixelsX() / g_baseDpi;
float CDPIHelper::m_fScaleY = CDPIHelper::GetLogPixelsY() / g_baseDpi;
float
CDPIHelper::ScaleX(float value)
{
return value * m_fScaleX;
}
float
CDPIHelper::ScaleY(float value)
{
return value * m_fScaleY;
}
float
CDPIHelper::GetLogPixelsX()
{
CDC dc(GetDC(NULL));
int value = dc.GetDeviceCaps(LOGPIXELSX);
return static_cast<float>(value);
}
float
CDPIHelper::GetLogPixelsY()
{
CDC dc(GetDC(NULL));
int value = dc.GetDeviceCaps(LOGPIXELSY);
return static_cast<float>(value);
}
bool
CDPIHelper::NeedScale()
{
return (!(m_fScaleX==1 && m_fScaleY==1));
}
bool
CDPIHelper::ScaleBitmap(CBitmap& bitmap)
{
if (!NeedScale()) return true;
CDC sourceDC(CreateCompatibleDC(NULL));
if (sourceDC.IsNull()) return false;
sourceDC.SelectBitmap(bitmap);
BITMAPINFO info;
ZeroMemory(&info, sizeof(info));
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
if (GetDIBits(sourceDC, bitmap, 0, 0, NULL, &info, 0))
{
int scaledWidth = static_cast<int>(ScaleX(static_cast<float>(info.bmiHeader.biWidth)));
int scaledHeight = static_cast<int>(ScaleY(static_cast<float>(info.bmiHeader.biHeight)));
CBitmap result;
result.CreateCompatibleBitmap(sourceDC, scaledWidth, scaledHeight);
if (result.IsNull()) return false;
CDC destDC(CreateCompatibleDC(NULL));
if (destDC.IsNull()) return false;
destDC.SelectBitmap(result);
destDC.SetStretchBltMode(HALFTONE);
if (destDC.StretchBlt(0, 0, scaledWidth, scaledHeight, sourceDC, 0, 0, info.bmiHeader.biWidth, info.bmiHeader.biHeight, SRCCOPY))
{
// rescale done
bitmap = result.Detach();
}
}
return true;
} | bsd-3-clause |
chernogolov/sau1 | css/plugins/component.css | 24336 | @font-face {
font-weight: normal;
font-style: normal;
font-family: 'feathericons';
src:url('../fonts/feathericons/feathericons.eot?-8is7zf');
src:url('../fonts/feathericons/feathericons.eot?#iefix-8is7zf') format('embedded-opentype'),
url('../fonts/feathericons/feathericons.woff?-8is7zf') format('woff'),
url('../fonts/feathericons/feathericons.ttf?-8is7zf') format('truetype'),
url('../fonts/feathericons/feathericons.svg?-8is7zf#feathericons') format('svg');
}
.grid {
overflow: hidden;
margin: 0;
padding: 3em 0 0 0;
width: 100%;
max-width: 1920px;
list-style: none;
text-align: center;
}
/* Common style */
.grid figure {
position: relative;
z-index: 1;
display: inline-block;
overflow: hidden;
margin: -0.135em;
width: 33.333%;
height: 400px;
background: #3085a3;
text-align: center;
cursor: pointer;
}
.grid figure img {
position: relative;
display: block;
min-height: 100%;
opacity: 0.8;
}
.grid figure figcaption {
padding: 2em;
color: #fff;
text-transform: uppercase;
font-size: 1.25em;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.grid figure figcaption::before,
.grid figure figcaption::after {
pointer-events: none;
}
.grid figure figcaption,
.grid figure a {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* Anchor will cover the whole item by default */
/* For some effects it will show as a button */
.grid figure a {
z-index: 1000;
text-indent: 200%;
white-space: nowrap;
font-size: 0;
opacity: 0;
}
.grid figure h2 {
word-spacing: -0.15em;
font-weight: 300;
}
.grid figure h2 span {
font-weight: 800;
}
.grid figure h2,
.grid figure p {
margin: 0;
}
.grid figure p {
letter-spacing: 1px;
font-size: 68.5%;
}
/* Individual effects */
/*---------------*/
/***** Lily *****/
/*---------------*/
figure.effect-lily img {
width: -webkit-calc(100% + 50px);
width: calc(100% + 50px);
opacity: 0.7;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-40px,0, 0);
transform: translate3d(-40px,0,0);
}
figure.effect-lily figcaption {
top: auto;
bottom: 0;
height: 50%;
text-align: left;
}
figure.effect-lily h2,
figure.effect-lily p {
-webkit-transform: translate3d(0,40px,0);
transform: translate3d(0,40px,0);
}
figure.effect-lily h2 {
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
}
figure.effect-lily p {
color: rgba(255,255,255,0.6);
opacity: 0;
-webkit-transition: opacity 0.2s, -webkit-transform 0.35s;
transition: opacity 0.2s, transform 0.35s;
}
figure.effect-lily:hover img,
figure.effect-lily:hover p {
opacity: 1;
}
figure.effect-lily:hover img,
figure.effect-lily:hover h2,
figure.effect-lily:hover p {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-lily:hover p {
-webkit-transition-delay: 0.05s;
transition-delay: 0.05s;
-webkit-transition-duration: 0.35s;
transition-duration: 0.35s;
}
/*---------------*/
/***** Sadie *****/
/*---------------*/
figure.effect-sadie figcaption::before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: -webkit-linear-gradient(top, rgba(72,76,97,0) 0%, rgba(72,76,97,0.8) 75%);
background: linear-gradient(to bottom, rgba(72,76,97,0) 0%, rgba(72,76,97,0.8) 75%);
content: '';
opacity: 0;
-webkit-transform: translate3d(0,50%,0);
transform: translate3d(0,50%,0);
}
figure.effect-sadie h2 {
position: absolute;
top: 50%;
left: 0;
width: 100%;
color: #484c61;
-webkit-transition: -webkit-transform 0.35s, color 0.35s;
transition: transform 0.35s, color 0.35s;
-webkit-transform: translate3d(0,-50%,0);
transform: translate3d(0,-50%,0);
}
figure.effect-sadie figcaption::before,
figure.effect-sadie p {
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
}
figure.effect-sadie p {
position: absolute;
bottom: 0;
left: 0;
padding: 2em;
width: 100%;
opacity: 0;
-webkit-transform: translate3d(0,10px,0);
transform: translate3d(0,10px,0);
}
figure.effect-sadie:hover h2 {
color: #fff;
-webkit-transform: translate3d(0,-50%,0) translate3d(0,-40px,0);
transform: translate3d(0,-50%,0) translate3d(0,-40px,0);
}
figure.effect-sadie:hover figcaption::before ,
figure.effect-sadie:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Roxy *****/
/*---------------*/
figure.effect-roxy {
background: -webkit-linear-gradient(45deg, #ff89e9 0%, #05abe0 100%);
background: linear-gradient(45deg, #ff89e9 0%,#05abe0 100%);
}
figure.effect-roxy img {
width: -webkit-calc(100% + 60px);
width: calc(100% + 60px);
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-50px,0,0);
transform: translate3d(-50px,0,0);
}
figure.effect-roxy figcaption::before {
position: absolute;
top: 30px;
right: 30px;
bottom: 30px;
left: 30px;
border: 1px solid #fff;
content: '';
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-20px,0,0);
transform: translate3d(-20px,0,0);
}
figure.effect-roxy figcaption {
padding: 3em;
text-align: left;
}
figure.effect-roxy h2 {
padding: 30% 0 10px 0;
}
figure.effect-roxy p {
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-10px,0,0);
transform: translate3d(-10px,0,0);
}
figure.effect-roxy:hover img {
opacity: 0.7;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-roxy:hover figcaption::before,
figure.effect-roxy:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Bubba *****/
/*---------------*/
figure.effect-bubba {
background: #9e5406;
}
figure.effect-bubba img {
opacity: 0.7;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.effect-bubba:hover img {
opacity: 0.4;
}
figure.effect-bubba figcaption::before,
figure.effect-bubba figcaption::after {
position: absolute;
top: 30px;
right: 30px;
bottom: 30px;
left: 30px;
content: '';
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
}
figure.effect-bubba figcaption::before {
border-top: 1px solid #fff;
border-bottom: 1px solid #fff;
-webkit-transform: scale(0,1);
transform: scale(0,1);
}
figure.effect-bubba figcaption::after {
border-right: 1px solid #fff;
border-left: 1px solid #fff;
-webkit-transform: scale(1,0);
transform: scale(1,0);
}
figure.effect-bubba h2 {
padding-top: 30%;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,-20px,0);
transform: translate3d(0,-20px,0);
}
figure.effect-bubba p {
padding: 20px 2.5em;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(0,20px,0);
transform: translate3d(0,20px,0);
}
figure.effect-bubba:hover figcaption::before,
figure.effect-bubba:hover figcaption::after {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
figure.effect-bubba:hover h2,
figure.effect-bubba:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Romeo *****/
/*---------------*/
figure.effect-romeo {
-webkit-perspective: 1000px;
perspective: 1000px;
}
figure.effect-romeo img {
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(0,0,300px);
transform: translate3d(0,0,300px);
}
figure.effect-romeo:hover img {
opacity: 0.6;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-romeo figcaption::before,
figure.effect-romeo figcaption::after {
position: absolute;
top: 50%;
left: 50%;
width: 80%;
height: 1px;
background: #fff;
content: '';
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-50%,-50%,0);
transform: translate3d(-50%,-50%,0);
}
figure.effect-romeo:hover figcaption::before {
opacity: 0.5;
-webkit-transform: translate3d(-50%,-50%,0) rotate(45deg);
transform: translate3d(-50%,-50%,0) rotate(45deg);
}
figure.effect-romeo:hover figcaption::after {
opacity: 0.5;
-webkit-transform: translate3d(-50%,-50%,0) rotate(-45deg);
transform: translate3d(-50%,-50%,0) rotate(-45deg);
}
figure.effect-romeo h2,
figure.effect-romeo p {
position: absolute;
top: 50%;
left: 0;
width: 100%;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
}
figure.effect-romeo h2 {
-webkit-transform: translate3d(0,-50%,0) translate3d(0,-150%,0);
transform: translate3d(0,-50%,0) translate3d(0,-150%,0);
}
figure.effect-romeo p {
padding: 0.25em 2em;
-webkit-transform: translate3d(0,-50%,0) translate3d(0,150%,0);
transform: translate3d(0,-50%,0) translate3d(0,150%,0);
}
figure.effect-romeo:hover h2 {
-webkit-transform: translate3d(0,-50%,0) translate3d(0,-100%,0);
transform: translate3d(0,-50%,0) translate3d(0,-100%,0);
}
figure.effect-romeo:hover p {
-webkit-transform: translate3d(0,-50%,0) translate3d(0,100%,0);
transform: translate3d(0,-50%,0) translate3d(0,100%,0);
}
/*---------------*/
/***** Layla *****/
/*---------------*/
figure.effect-layla {
background: #18a367;
}
figure.effect-layla img {
min-width: 100%;
height: -webkit-calc(100% + 40px);
height: calc(100% + 40px);
}
figure.effect-layla figcaption {
padding: 3em;
}
figure.effect-layla figcaption::before,
figure.effect-layla figcaption::after {
position: absolute;
content: '';
opacity: 0;
}
figure.effect-layla figcaption::before {
top: 50px;
right: 30px;
bottom: 50px;
left: 30px;
border-top: 1px solid #fff;
border-bottom: 1px solid #fff;
-webkit-transform: scale(0,1);
transform: scale(0,1);
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
}
figure.effect-layla figcaption::after {
top: 30px;
right: 50px;
bottom: 30px;
left: 50px;
border-right: 1px solid #fff;
border-left: 1px solid #fff;
-webkit-transform: scale(1,0);
transform: scale(1,0);
-webkit-transform-origin: 100% 0;
transform-origin: 100% 0;
}
figure.effect-layla h2 {
padding-top: 26%;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
}
figure.effect-layla p {
padding: 0.5em 2em;
text-transform: none;
opacity: 0;
-webkit-transform: translate3d(0,-10px,0);
transform: translate3d(0,-10px,0);
}
figure.effect-layla img,
figure.effect-layla h2 {
-webkit-transform: translate3d(0,-30px,0);
transform: translate3d(0,-30px,0);
}
figure.effect-layla img,
figure.effect-layla figcaption::before,
figure.effect-layla figcaption::after,
figure.effect-layla p {
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
}
figure.effect-layla:hover img {
opacity: 0.7;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-layla:hover figcaption::before,
figure.effect-layla:hover figcaption::after {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
figure.effect-layla:hover h2,
figure.effect-layla:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-layla:hover figcaption::after,
figure.effect-layla:hover h2,
figure.effect-layla:hover p,
figure.effect-layla:hover img {
-webkit-transition-delay: 0.15s;
transition-delay: 0.15s;
}
/*---------------*/
/***** Honey *****/
/*---------------*/
figure.effect-honey {
background: #4a3753;
}
figure.effect-honey img {
opacity: 0.9;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.effect-honey:hover img {
opacity: 0.5;
}
figure.effect-honey figcaption::before {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 10px;
background: #fff;
content: '';
-webkit-transform: translate3d(0,10px,0);
transform: translate3d(0,10px,0);
}
figure.effect-honey h2 {
position: absolute;
bottom: 0;
left: 0;
padding: 1em 1.5em;
width: 100%;
text-align: left;
-webkit-transform: translate3d(0,-30px,0);
transform: translate3d(0,-30px,0);
}
figure.effect-honey h2 i {
font-style: normal;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(0,-30px,0);
transform: translate3d(0,-30px,0);
}
figure.effect-honey figcaption::before,
figure.effect-honey h2 {
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
}
figure.effect-honey:hover figcaption::before,
figure.effect-honey:hover h2,
figure.effect-honey:hover h2 i {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Oscar *****/
/*---------------*/
figure.effect-oscar {
background: -webkit-linear-gradient(45deg, #22682a 0%, #9b4a1b 40%, #3a342a 100%);
background: linear-gradient(45deg, #22682a 0%,#9b4a1b 40%,#3a342a 100%);
}
figure.effect-oscar img {
opacity: 0.9;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.effect-oscar figcaption {
padding: 3em;
background-color: rgba(58,52,42,0.7);
-webkit-transition: background-color 0.35s;
transition: background-color 0.35s;
}
figure.effect-oscar figcaption::before {
position: absolute;
top: 30px;
right: 30px;
bottom: 30px;
left: 30px;
border: 1px solid #fff;
content: '';
}
figure.effect-oscar h2 {
margin: 20% 0 10px 0;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,100%,0);
transform: translate3d(0,100%,0);
}
figure.effect-oscar figcaption::before,
figure.effect-oscar p {
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: scale(0);
transform: scale(0);
}
figure.effect-oscar:hover h2 {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-oscar:hover figcaption::before,
figure.effect-oscar:hover p {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
figure.effect-oscar:hover figcaption {
background-color: rgba(58,52,42,0);
}
figure.effect-oscar:hover img {
opacity: 0.4;
}
/*---------------*/
/***** Marley *****/
/*---------------*/
figure.effect-marley figcaption {
text-align: right;
}
figure.effect-marley h2,
figure.effect-marley p {
position: absolute;
right: 30px;
left: 30px;
padding: 10px 0;
}
figure.effect-marley p {
bottom: 30px;
line-height: 1.5;
-webkit-transform: translate3d(0,100%,0);
transform: translate3d(0,100%,0);
}
figure.effect-marley h2 {
top: 30px;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,20px,0);
transform: translate3d(0,20px,0);
}
figure.effect-marley:hover h2 {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-marley h2::after {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 4px;
background: #fff;
content: '';
-webkit-transform: translate3d(0,40px,0);
transform: translate3d(0,40px,0);
}
figure.effect-marley h2::after,
figure.effect-marley p {
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
}
figure.effect-marley:hover h2::after,
figure.effect-marley:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Ruby *****/
/*---------------*/
figure.effect-ruby {
background-color: #17819c;
}
figure.effect-ruby img {
opacity: 0.7;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: scale(1.15);
transform: scale(1.15);
}
figure.effect-ruby:hover img {
opacity: 0.5;
-webkit-transform: scale(1);
transform: scale(1);
}
figure.effect-ruby h2 {
margin-top: 20%;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,20px,0);
transform: translate3d(0,20px,0);
}
figure.effect-ruby p {
margin: 1em 0 0;
padding: 3em;
border: 1px solid #fff;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(0,20px,0) scale(1.1);
transform: translate3d(0,20px,0) scale(1.1);
}
figure.effect-ruby:hover h2 {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-ruby:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0) scale(1);
transform: translate3d(0,0,0) scale(1);
}
/*---------------*/
/***** Milo *****/
/*---------------*/
figure.effect-milo {
background: #2e5d5a;
}
figure.effect-milo img {
width: -webkit-calc(100% + 60px);
width: calc(100% + 60px);
opacity: 1;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-30px,0,0) scale(1.12);
transform: translate3d(-30px,0,0) scale(1.12);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
figure.effect-milo:hover img {
opacity: 0.5;
-webkit-transform: translate3d(0,0,0) scale(1);
transform: translate3d(0,0,0) scale(1);
}
figure.effect-milo h2 {
position: absolute;
right: 0;
bottom: 0;
padding: 1em 1.2em;
}
figure.effect-milo p {
padding: 0 10px 0 0;
width: 50%;
border-right: 1px solid #fff;
text-align: right;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-40px,0,0);
transform: translate3d(-40px,0,0);
}
figure.effect-milo:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Dexter *****/
/*---------------*/
figure.effect-dexter {
background: -webkit-linear-gradient(top, rgba(37,141,200,1) 0%, rgba(104,60,19,1) 100%);
background: linear-gradient(to bottom, rgba(37,141,200,1) 0%,rgba(104,60,19,1) 100%);
}
figure.effect-dexter img {
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.effect-dexter:hover img {
opacity: 0.4;
}
figure.effect-dexter figcaption::after {
position: absolute;
right: 30px;
bottom: 30px;
left: 30px;
height: -webkit-calc(50% - 30px);
height: calc(50% - 30px);
border: 7px solid #fff;
content: '';
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,-100%,0);
transform: translate3d(0,-100%,0);
}
figure.effect-dexter:hover figcaption::after {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-dexter figcaption {
padding: 3em;
text-align: left;
}
figure.effect-dexter p {
position: absolute;
right: 60px;
bottom: 60px;
left: 60px;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(0,-100px,0);
transform: translate3d(0,-100px,0);
}
figure.effect-dexter:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Sarah *****/
/*---------------*/
figure.effect-sarah {
background: #42b078;
}
figure.effect-sarah img {
width: -webkit-calc(100% + 20px);
width: calc(100% + 20px);
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(-10px,0,0);
transform: translate3d(-10px,0,0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
figure.effect-sarah:hover img {
opacity: 0.4;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-sarah figcaption {
text-align: left;
}
figure.effect-sarah h2 {
position: relative;
overflow: hidden;
padding: 0.5em 0;
}
figure.effect-sarah h2::after {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: #fff;
content: '';
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(-100%,0,0);
transform: translate3d(-100%,0,0);
}
figure.effect-sarah:hover h2::after {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-sarah p {
padding: 1em 0;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: translate3d(100%,0,0);
transform: translate3d(100%,0,0);
}
figure.effect-sarah:hover p {
opacity: 1;
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
/*---------------*/
/***** Zoe *****/
/*---------------*/
figure.effect-zoe figcaption {
top: auto;
bottom: 0;
padding: 1em;
height: 3.75em;
background: #fff;
color: #3c4a50;
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,100%,0);
transform: translate3d(0,100%,0);
}
figure.effect-zoe h2 {
float: left;
}
figure.effect-zoe figcaption > span {
float: right;
}
figure.effect-zoe p {
position: absolute;
bottom: 8em;
padding: 2em;
color: #fff;
text-transform: none;
font-size: 90%;
opacity: 0;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.effect-zoe h2,
figure.effect-zoe figcaption > span {
-webkit-transition: -webkit-transform 0.35s;
transition: transform 0.35s;
-webkit-transform: translate3d(0,200%,0);
transform: translate3d(0,200%,0);
}
figure.effect-zoe figcaption > span::before {
display: inline-block;
padding: 8px 10px;
font-family: 'feathericons';
speak: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-eye::before {
content: '\e000';
}
.icon-paper-clip::before {
content: '\e001';
}
.icon-heart::before {
content: '\e024';
}
figure.effect-zoe h2 {
display: inline-block;
}
figure.effect-zoe:hover p {
opacity: 1;
}
figure.effect-zoe:hover figcaption,
figure.effect-zoe:hover h2,
figure.effect-zoe:hover figcaption > span {
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
figure.effect-zoe:hover h2 {
-webkit-transition-delay: 0.05s;
transition-delay: 0.05s;
}
figure.effect-zoe:hover figcaption > span:nth-child(4) {
-webkit-transition-delay: 0.1s;
transition-delay: 0.1s;
}
figure.effect-zoe:hover figcaption > span:nth-child(3) {
-webkit-transition-delay: 0.15s;
transition-delay: 0.15s;
}
figure.effect-zoe:hover figcaption > span:nth-child(2) {
-webkit-transition-delay: 0.2s;
transition-delay: 0.2s;
}
/*---------------*/
/***** Chico *****/
/*---------------*/
figure.effect-chico img {
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
-webkit-transform: scale(1.12);
transform: scale(1.12);
}
figure.effect-chico:hover img {
opacity: 0.5;
-webkit-transform: scale(1);
transform: scale(1);
}
figure.effect-chico figcaption {
padding: 3em;
}
figure.effect-chico figcaption::before {
position: absolute;
top: 30px;
right: 30px;
bottom: 30px;
left: 30px;
border: 1px solid #fff;
content: '';
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
figure.effect-chico figcaption::before,
figure.effect-chico p {
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s, transform 0.35s;
}
figure.effect-chico h2 {
padding: 20% 0 20px 0;
}
figure.effect-chico p {
margin: 0 auto;
max-width: 200px;
-webkit-transform: scale(1.5);
transform: scale(1.5);
}
figure.effect-chico:hover figcaption::before,
figure.effect-chico:hover p {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
@media screen and (max-width: 69.5em) {
.grid figure {
width: 50%;
}
.grid figure figcaption {
font-size: 90%;
}
}
@media screen and (max-width: 41.5em) {
.grid figure {
width: 100%;
}
} | bsd-3-clause |
lmaxim/zend_gdata | library/Zend/Gdata/MediaMimeStream.php | 5671 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MediaMimeStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Gdata_MimeFile
*/
#require_once 'Zend/Gdata/MimeFile.php';
/**
* @see Zend_Gdata_MimeBodyString
*/
#require_once 'Zend/Gdata/MimeBodyString.php';
/**
* A streaming Media MIME class that allows for buffered read operations.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_MediaMimeStream
{
/**
* A valid MIME boundary.
*
* @var string
*/
protected $_boundaryString = null;
/**
* A handle to the file that is part of the message.
*
* @var resource
*/
protected $_fileHandle = null;
/**
* The current part being read from.
* @var integer
*/
protected $_currentPart = 0;
/**
* The size of the MIME message.
* @var integer
*/
protected $_totalSize = 0;
/**
* An array of all the parts to be sent. Array members are either a
* MimeFile or a MimeBodyString object.
* @var array
*/
protected $_parts = null;
/**
* Create a new MimeMediaStream object.
*
* @param string $xmlString The string corresponding to the XML section
* of the message, typically an atom entry or feed.
* @param string $filePath The path to the file that constitutes the binary
* part of the message.
* @param string $fileContentType The valid internet media type of the file.
* @throws Zend_Gdata_App_IOException If the file cannot be read or does
* not exist. Also if mbstring.func_overload has been set > 1.
*/
public function __construct($xmlString = null, $filePath = null,
$fileContentType = null)
{
if (!file_exists($filePath) || !is_readable($filePath)) {
#require_once 'Zend/Gdata/App/IOException.php';
throw new Zend_Gdata_App_IOException('File to be uploaded at ' .
$filePath . ' does not exist or is not readable.');
}
$this->_fileHandle = fopen($filePath, 'rb', TRUE);
$this->_boundaryString = '=_' . md5(microtime(1) . rand(1,20));
$entry = $this->wrapEntry($xmlString, $fileContentType);
$closingBoundary = new Zend_Gdata_MimeBodyString("\r\n--{$this->_boundaryString}--\r\n");
$file = new Zend_Gdata_MimeFile($this->_fileHandle);
$this->_parts = array($entry, $file, $closingBoundary);
$fileSize = filesize($filePath);
$this->_totalSize = $entry->getSize() + $fileSize
+ $closingBoundary->getSize();
}
/**
* Sandwiches the entry body into a MIME message
*
* @return void
*/
private function wrapEntry($entry, $fileMimeType)
{
$wrappedEntry = "--{$this->_boundaryString}\r\n";
$wrappedEntry .= "Content-Type: application/atom+xml\r\n\r\n";
$wrappedEntry .= $entry;
$wrappedEntry .= "\r\n--{$this->_boundaryString}\r\n";
$wrappedEntry .= "Content-Type: $fileMimeType\r\n\r\n";
return new Zend_Gdata_MimeBodyString($wrappedEntry);
}
/**
* Read a specific chunk of the the MIME multipart message.
*
* @param integer $bufferSize The size of the chunk that is to be read,
* must be lower than MAX_BUFFER_SIZE.
* @return string A corresponding piece of the message. This could be
* binary or regular text.
*/
public function read($bytesRequested)
{
if($this->_currentPart >= count($this->_parts)) {
return FALSE;
}
$activePart = $this->_parts[$this->_currentPart];
$buffer = $activePart->read($bytesRequested);
while(strlen($buffer) < $bytesRequested) {
$this->_currentPart += 1;
$nextBuffer = $this->read($bytesRequested - strlen($buffer));
if($nextBuffer === FALSE) {
break;
}
$buffer .= $nextBuffer;
}
return $buffer;
}
/**
* Return the total size of the mime message.
*
* @return integer Total size of the message to be sent.
*/
public function getTotalSize()
{
return $this->_totalSize;
}
/**
* Close the internal file that we are streaming to the socket.
*
* @return void
*/
public function closeFileHandle()
{
if ($this->_fileHandle !== null) {
fclose($this->_fileHandle);
}
}
/**
* Return a Content-type header that includes the current boundary string.
*
* @return string A valid HTTP Content-Type header.
*/
public function getContentType()
{
return 'multipart/related;boundary="' .
$this->_boundaryString . '"' . "\r\n";
}
}
| bsd-3-clause |
nicko96/Chrome-Infra | infra_libs/event_mon/test/router_test.py | 1648 | # 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.
import os
import random
import unittest
from infra_libs.event_mon import router
from infra_libs.event_mon.log_request_lite_pb2 import LogRequestLite
DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
class RouterTests(unittest.TestCase):
def test_smoke(self):
# Use dry_run to avoid code that deals with http (including auth).
r = router._Router({}, endpoint=None)
self.assertTrue(r.close())
def test_smoke_with_credentials(self):
cache = {'service_account_creds':
os.path.join(DATA_DIR, 'valid_creds.json'),
'service_accounts_creds_root': 'whatever.the/other/is/absolute'}
r = router._Router(cache, endpoint='https://any.where')
self.assertTrue(r.close())
def test_push_smoke(self):
r = router._Router({}, endpoint=None)
req = LogRequestLite.LogEventLite()
req.event_time_ms = router.time_ms()
req.event_code = 1
req.event_flow_id = 2
r.push_event(req)
self.assertTrue(r.close())
def test_push_error_handling(self):
r = router._Router({}, endpoint=None)
r.push_event(None)
self.assertTrue(r.close())
class BackoffTest(unittest.TestCase):
def test_backoff_time_first_value(self):
t = router.backoff_time(attempt=0, retry_backoff=2.)
random.seed(0)
self.assertTrue(1.5 <= t <= 2.5)
def test_backoff_time_max_value(self):
t = router.backoff_time(attempt=10, retry_backoff=2., max_delay=5)
self.assertTrue(abs(t - 5.) < 0.0001)
| bsd-3-clause |
GeoMatDigital/django-geomat | geomat/users/migrations/0001_initial.py | 3014 | # -*- coding: utf-8 -*-
from django.db import models, migrations
import django.utils.timezone
import django.contrib.auth.models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),
('is_superuser', models.BooleanField(help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status', default=False)),
('username', models.CharField(max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], verbose_name='username', error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True)),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
('email', models.EmailField(max_length=254, verbose_name='email address', blank=True)),
('is_staff', models.BooleanField(help_text='Designates whether the user can log into this admin site.', verbose_name='staff status', default=False)),
('is_active', models.BooleanField(help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active', default=True)),
('date_joined', models.DateTimeField(verbose_name='date joined', default=django.utils.timezone.now)),
('groups', models.ManyToManyField(related_name='user_set', blank=True, verbose_name='groups', to='auth.Group', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user')),
('user_permissions', models.ManyToManyField(related_name='user_set', blank=True, verbose_name='user permissions', to='auth.Permission', help_text='Specific permissions for this user.', related_query_name='user')),
('name', models.CharField(max_length=255, verbose_name='Name of User', blank=True)),
],
options={
'verbose_name': 'user',
'abstract': False,
'verbose_name_plural': 'users',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
| bsd-3-clause |
arcostasi/slimantic-skeleton | app/src/Exceptions/HttpExceptionInterface.php | 391 | <?php
namespace App\Exceptions;
/**
* Interface for HTTP error exceptions.
*/
interface HttpExceptionInterface
{
/**
* Returns the status code.
*
* @return int An HTTP response status code
*/
public function getStatusCode();
/**
* Returns response headers.
*
* @return array Response headers
*/
public function getHeaders();
} | bsd-3-clause |
santazhang/sstable | sstable/flags.h | 394 | #pragma once
#include "utils.h"
namespace sst {
class Flags {
public:
static const i32 magic = 0x31545353; // 'SST1'
static const i32 DELETED = 0x1;
static const i32 EMPTY_VALUE = 0x2;
static inline bool deleted(i32 flag) {
return flag & DELETED;
}
static inline bool empty_value(i32 flag) {
return flag & EMPTY_VALUE;
}
};
} // namespace sst
| bsd-3-clause |
LuminateWireless/grpc-java | core/src/main/java/io/grpc/ManagedChannelProvider.java | 5316 | /*
* Copyright 2015, Google 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:
*
* * 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 Google 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.
*/
package io.grpc;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ServiceLoader;
/**
* Provider of managed channels for transport agnostic consumption.
*
* <p>Implementations <em>should not</em> throw. If they do, it may interrupt class loading. If
* exceptions may reasonably occur for implementation-specific reasons, implementations should
* generally handle the exception gracefully and return {@code false} from {@link #isAvailable()}.
*/
@Internal
public abstract class ManagedChannelProvider {
private static final ManagedChannelProvider provider
= load(getCorrectClassLoader());
@VisibleForTesting
static ManagedChannelProvider load(ClassLoader classLoader) {
ServiceLoader<ManagedChannelProvider> providers
= ServiceLoader.load(ManagedChannelProvider.class, classLoader);
List<ManagedChannelProvider> list = new ArrayList<ManagedChannelProvider>();
for (ManagedChannelProvider current : providers) {
if (!current.isAvailable()) {
continue;
}
list.add(current);
}
if (list.isEmpty()) {
return null;
} else {
return Collections.max(list, new Comparator<ManagedChannelProvider>() {
@Override
public int compare(ManagedChannelProvider f1, ManagedChannelProvider f2) {
return f1.priority() - f2.priority();
}
});
}
}
/**
* Returns the ClassLoader-wide default channel.
*
* @throws ProviderNotFoundException if no provider is available
*/
public static ManagedChannelProvider provider() {
if (provider == null) {
throw new ProviderNotFoundException("No functional channel service provider found. "
+ "Try adding a dependency on the grpc-okhttp or grpc-netty artifact");
}
return provider;
}
private static ClassLoader getCorrectClassLoader() {
if (isAndroid()) {
// When android:sharedUserId or android:process is used, Android will setup a dummy
// ClassLoader for the thread context (http://stackoverflow.com/questions/13407006),
// instead of letting users to manually set context class loader, we choose the
// correct class loader here.
return ManagedChannelProvider.class.getClassLoader();
}
return Thread.currentThread().getContextClassLoader();
}
protected static boolean isAndroid() {
try {
Class.forName("android.app.Application", /*initialize=*/ false, null);
return true;
} catch (Exception e) {
// If Application isn't loaded, it might as well not be Android.
return false;
}
}
/**
* Whether this provider is available for use, taking the current environment into consideration.
* If {@code false}, no other methods are safe to be called.
*/
protected abstract boolean isAvailable();
/**
* A priority, from 0 to 10 that this provider should be used, taking the current environment into
* consideration. 5 should be considered the default, and then tweaked based on environment
* detection. A priority of 0 does not imply that the provider wouldn't work; just that it should
* be last in line.
*/
protected abstract int priority();
/**
* Creates a new builder with the given host and port.
*/
protected abstract ManagedChannelBuilder<?> builderForAddress(String name, int port);
/**
* Creates a new builder with the given target URI.
*/
protected abstract ManagedChannelBuilder<?> builderForTarget(String target);
public static final class ProviderNotFoundException extends RuntimeException {
public ProviderNotFoundException(String msg) {
super(msg);
}
}
}
| bsd-3-clause |
pdxacm/acmapi | CONTRIBUTING.md | 1336 | Contributing
============
## Communication
Don't be shy, ask for help. If you have a question, comment, concern, or
great idea just open up an issue to start the conversation. You can
also email me.
## Commits
* __Rebase__: Whenever you have made commits on your local copy while at
the same time commits have been made upstream you should `rebase` instead
of pull/merge. Rebasing will put the upstream commits before your new
local commits.
```sh
git pull --rebase upstream
```
* __References__: When you are addressing a issue you should reference
that issue in your commits or pull requests. For example, if you just
addressed issue #11 the first line of your commit message should be
prefixed with `(gh-11)`.
## Testing
All code summited needs to pass the current test suite.
### Testing Dependencies
Installation of acmapi does not install the testing dependencies.
You will need to install `Nose` and `Mock`. The dependencies can be
installed with pip.
```sh
pip install Nose Mock
```
### Running Tests
Tests can be ran locally as well as by TravisCI.
```sh
nosetests
```
## License
This project is under the BSD Clause 3 license. Any and all
future contributions will be licensed the same. If you put statements that
declare your code licensed under anything else they will not be pulled.
| bsd-3-clause |
spider049/yii2-meeting | backend/modules/personal/Module.php | 387 | <?php
namespace backend\modules\personal;
/**
* personal module definition class
*/
class Module extends \yii\base\Module
{
/**
* @inheritdoc
*/
public $controllerNamespace = 'backend\modules\personal\controllers';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}
| bsd-3-clause |
amanjpro/9riskane | src/com/rezgame/backend/logic/GameHistoryManager.java | 162 | package com.rezgame.backend.logic;
/*
* Copyright (c) <2013>, Amanj Sherwany and Nosheen Zaza
* All rights reserved.
* */
public class GameHistoryManager {
}
| bsd-3-clause |
sviperll/static-mustache | static-mustache/src/main/java/com/github/sviperll/staticmustache/TemplateCompiler.java | 12095 | /*
* Copyright (c) 2014, Victor Nazarov <[email protected]>
* 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.
*/
package com.github.sviperll.staticmustache;
import com.github.sviperll.staticmustache.context.ContextException;
import com.github.sviperll.staticmustache.context.TemplateCompilerContext;
import com.github.sviperll.staticmustache.token.MustacheTokenizer;
import java.io.IOException;
import javax.annotation.Nonnull;
/**
*
* @author Victor Nazarov <[email protected]>
*/
class TemplateCompiler implements TokenProcessor<PositionedToken<MustacheToken>> {
public static Factory compilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createCompiler(reader, writer, context);
}
};
}
public static Factory headerCompilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createHeaderCompiler(reader, writer, context);
}
};
}
public static Factory footerCompilerFactory() {
return new Factory() {
@Override
public TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer,
TemplateCompilerContext context) {
return TemplateCompiler.createFooterCompiler(reader, writer, context);
}
};
}
public static TemplateCompiler createCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new SimpleTemplateCompiler(reader, writer, context);
}
public static TemplateCompiler createHeaderCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new HeaderTemplateCompiler(reader, writer, context);
}
public static TemplateCompiler createFooterCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
return new FooterTemplateCompiler(reader, writer, context);
}
private final NamedReader reader;
private final boolean expectsYield;
final SwitchablePrintWriter writer;
private TemplateCompilerContext context;
boolean foundYield = false;
private TemplateCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context, boolean expectsYield) {
this.reader = reader;
this.writer = writer;
this.context = context;
this.expectsYield = expectsYield;
}
void run() throws ProcessingException, IOException {
TokenProcessor<Character> processor = MustacheTokenizer.createInstance(reader.name(), this);
int readResult;
while ((readResult = reader.read()) >= 0) {
processor.processToken((char)readResult);
}
processor.processToken(TokenProcessor.EOF);
writer.println();
}
@Override
public void processToken(@Nonnull PositionedToken<MustacheToken> positionedToken) throws ProcessingException {
positionedToken.innerToken().accept(new CompilingTokenProcessor(positionedToken.position()));
}
private class CompilingTokenProcessor implements MustacheToken.Visitor<Void, ProcessingException> {
private final Position position;
public CompilingTokenProcessor(Position position) {
this.position = position;
}
@Override
public Void beginSection(String name) throws ProcessingException {
try {
context = context.getChild(name);
print(context.beginSectionRenderingCode());
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
return null;
}
@Override
public Void beginInvertedSection(String name) throws ProcessingException {
try {
context = context.getInvertedChild(name);
print(context.beginSectionRenderingCode());
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
return null;
}
@Override
public Void endSection(String name) throws ProcessingException {
if (!context.isEnclosed())
throw new ProcessingException(position, "Closing " + name + " block when no block is currently open");
else if (!context.currentEnclosedContextName().equals(name))
throw new ProcessingException(position, "Closing " + name + " block instead of " + context.currentEnclosedContextName());
else {
print(context.endSectionRenderingCode());
context = context.parentContext();
return null;
}
}
@Override
public Void variable(String name) throws ProcessingException {
try {
if (!expectsYield || !name.equals("yield")) {
TemplateCompilerContext variable = context.getChild(name);
writer.print(variable.renderingCode());
} else {
if (foundYield)
throw new ProcessingException(position, "Yield can be used only once");
else if (context.isEnclosed())
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block before yield");
else {
throw new ProcessingException(position, "Yield should be unescaped variable");
}
}
return null;
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
}
@Override
public Void unescapedVariable(String name) throws ProcessingException {
try {
if (!expectsYield || !name.equals("yield")) {
TemplateCompilerContext variable = context.getChild(name);
writer.print(variable.unescapedRenderingCode());
} else {
if (foundYield)
throw new ProcessingException(position, "Yield can be used only once");
if (context.isEnclosed())
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block before yield");
else {
foundYield = true;
if (writer.suppressesOutput())
writer.enableOutput();
else
writer.disableOutput();
}
}
return null;
} catch (ContextException ex) {
throw new ProcessingException(position, ex);
}
}
@Override
public Void specialCharacter(char c) throws ProcessingException {
if (c == '\n') {
printCodeToWrite("\\n");
println();
} else if (c == '"') {
printCodeToWrite("\\\"");
} else
printCodeToWrite("" + c);
return null;
}
@Override
public Void text(String s) throws ProcessingException {
printCodeToWrite(s);
return null;
}
@Override
public Void endOfFile() throws ProcessingException {
if (!context.isEnclosed())
return null;
else {
throw new ProcessingException(position, "Unclosed " + context.currentEnclosedContextName() + " block at end of file");
}
}
private void printCodeToWrite(String s) {
print(context.unescapedWriterExpression() + ".append(\"" + s + "\"); ");
}
private void print(String s) {
writer.print(s);
}
private void println() {
writer.println();
}
}
static class SimpleTemplateCompiler extends TemplateCompiler {
private SimpleTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, false);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
writer.enableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
static class HeaderTemplateCompiler extends TemplateCompiler {
private HeaderTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, true);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
foundYield = false;
writer.enableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
static class FooterTemplateCompiler extends TemplateCompiler {
private FooterTemplateCompiler(NamedReader inputReader, SwitchablePrintWriter writer, TemplateCompilerContext context) {
super(inputReader, writer, context, true);
}
@Override
void run() throws ProcessingException, IOException {
boolean suppressesOutput = writer.suppressesOutput();
foundYield = false;
writer.disableOutput();
super.run();
if (suppressesOutput)
writer.disableOutput();
else
writer.enableOutput();
}
}
interface Factory {
TemplateCompiler createTemplateCompiler(NamedReader reader, SwitchablePrintWriter writer, TemplateCompilerContext context);
}
}
| bsd-3-clause |
ofgulban/retinex_for_mri | script_examples/readme.md | 75 | This folder contains examples of this library used within a python script.
| bsd-3-clause |
liuqx315/Sundials | sundials/src/cvodes/cvodes_impl.h | 47780 | /*
* -----------------------------------------------------------------
* $Revision: 4075 $
* $Date: 2014-04-24 10:46:58 -0700 (Thu, 24 Apr 2014) $
* -----------------------------------------------------------------
* Programmer(s): Radu Serban @ LLNL
* -----------------------------------------------------------------
* LLNS Copyright Start
* Copyright (c) 2014, Lawrence Livermore National Security
* This work was performed under the auspices of the U.S. Department
* of Energy by Lawrence Livermore National Laboratory in part under
* Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* LLNS Copyright End
* -----------------------------------------------------------------
* Implementation header file for the main CVODES integrator.
* -----------------------------------------------------------------
*/
#ifndef _CVODES_IMPL_H
#define _CVODES_IMPL_H
#ifdef __cplusplus /* wrapper to enable C++ usage */
extern "C" {
#endif
#include <stdarg.h>
#include <cvodes/cvodes.h>
#include <sundials/sundials_nvector.h>
#include <sundials/sundials_types.h>
/*
* =================================================================
* I N T E R N A L C V O D E S C O N S T A N T S
* =================================================================
*/
/* Basic CVODES constants */
#define ADAMS_Q_MAX 12 /* max value of q for lmm == ADAMS */
#define BDF_Q_MAX 5 /* max value of q for lmm == BDF */
#define Q_MAX ADAMS_Q_MAX /* max value of q for either lmm */
#define L_MAX (Q_MAX+1) /* max value of L for either lmm */
#define NUM_TESTS 5 /* number of error test quantities */
#define HMIN_DEFAULT RCONST(0.0) /* hmin default value */
#define HMAX_INV_DEFAULT RCONST(0.0) /* hmax_inv default value */
#define MXHNIL_DEFAULT 10 /* mxhnil default value */
#define MXSTEP_DEFAULT 500 /* mxstep default value */
/*
* =================================================================
* F O R W A R D P O I N T E R R E F E R E N C E S
* =================================================================
*/
typedef struct CVadjMemRec *CVadjMem;
typedef struct CkpntMemRec *CkpntMem;
typedef struct DtpntMemRec *DtpntMem;
typedef struct CVodeBMemRec *CVodeBMem;
/*
* =================================================================
* M A I N I N T E G R A T O R M E M O R Y B L O C K
* =================================================================
*/
/*
* -----------------------------------------------------------------
* Types: struct CVodeMemRec, CVodeMem
* -----------------------------------------------------------------
* The type CVodeMem is type pointer to struct CVodeMemRec.
* This structure contains fields to keep track of problem state.
* -----------------------------------------------------------------
*/
typedef struct CVodeMemRec {
realtype cv_uround; /* machine unit roundoff */
/*--------------------------
Problem Specification Data
--------------------------*/
CVRhsFn cv_f; /* y' = f(t,y(t)) */
void *cv_user_data; /* user pointer passed to f */
int cv_lmm; /* lmm = ADAMS or BDF */
int cv_iter; /* iter = FUNCTIONAL or NEWTON */
int cv_itol; /* itol = CV_SS, CV_SV, or CV_WF, or CV_NN */
realtype cv_reltol; /* relative tolerance */
realtype cv_Sabstol; /* scalar absolute tolerance */
N_Vector cv_Vabstol; /* vector absolute tolerance */
booleantype cv_user_efun; /* TRUE if user sets efun */
CVEwtFn cv_efun; /* function to set ewt */
void *cv_e_data; /* user pointer passed to efun */
/*-----------------------
Quadrature Related Data
-----------------------*/
booleantype cv_quadr; /* TRUE if integrating quadratures */
CVQuadRhsFn cv_fQ; /* q' = fQ(t, y(t)) */
booleantype cv_errconQ; /* TRUE if quadrs. are included in error test */
int cv_itolQ; /* itolQ = CV_SS or CV_SV */
realtype cv_reltolQ; /* relative tolerance for quadratures */
realtype cv_SabstolQ; /* scalar absolute tolerance for quadratures */
N_Vector cv_VabstolQ; /* vector absolute tolerance for quadratures */
/*------------------------
Sensitivity Related Data
------------------------*/
booleantype cv_sensi; /* TRUE if computing sensitivities */
int cv_Ns; /* Number of sensitivities */
int cv_ism; /* ism = SIMULTANEOUS or STAGGERED */
CVSensRhsFn cv_fS; /* fS = (df/dy)*yS + (df/dp) */
CVSensRhs1Fn cv_fS1; /* fS1 = (df/dy)*yS_i + (df/dp) */
void *cv_fS_data; /* data pointer passed to fS */
booleantype cv_fSDQ; /* TRUE if using internal DQ functions */
int cv_ifS; /* ifS = ALLSENS or ONESENS */
realtype *cv_p; /* parameters in f(t,y,p) */
realtype *cv_pbar; /* scale factors for parameters */
int *cv_plist; /* list of sensitivities */
int cv_DQtype; /* central/forward finite differences */
realtype cv_DQrhomax; /* cut-off value for separate/simultaneous FD */
booleantype cv_errconS; /* TRUE if yS are considered in err. control */
int cv_itolS;
realtype cv_reltolS; /* relative tolerance for sensitivities */
realtype *cv_SabstolS; /* scalar absolute tolerances for sensi. */
N_Vector *cv_VabstolS; /* vector absolute tolerances for sensi. */
/*-----------------------------------
Quadrature Sensitivity Related Data
-----------------------------------*/
booleantype cv_quadr_sensi; /* TRUE if computing sensitivties of quadrs. */
CVQuadSensRhsFn cv_fQS; /* fQS = (dfQ/dy)*yS + (dfQ/dp) */
void *cv_fQS_data; /* data pointer passed to fQS */
booleantype cv_fQSDQ; /* TRUE if using internal DQ functions */
booleantype cv_errconQS; /* TRUE if yQS are considered in err. con. */
int cv_itolQS;
realtype cv_reltolQS; /* relative tolerance for yQS */
realtype *cv_SabstolQS; /* scalar absolute tolerances for yQS */
N_Vector *cv_VabstolQS; /* vector absolute tolerances for yQS */
/*-----------------------
Nordsieck History Array
-----------------------*/
N_Vector cv_zn[L_MAX]; /* Nordsieck array, of size N x (q+1).
zn[j] is a vector of length N (j=0,...,q)
zn[j] = [1/factorial(j)] * h^j *
(jth derivative of the interpolating poly.) */
/*-------------------
Vectors of length N
-------------------*/
N_Vector cv_ewt; /* error weight vector */
N_Vector cv_y; /* y is used as temporary storage by the solver.
The memory is provided by the user to CVode
where the vector is named yout. */
N_Vector cv_acor; /* In the context of the solution of the
nonlinear equation, acor = y_n(m) - y_n(0).
On return, this vector is scaled to give
the estimated local error in y. */
N_Vector cv_tempv; /* temporary storage vector */
N_Vector cv_ftemp; /* temporary storage vector */
/*--------------------------
Quadrature Related Vectors
--------------------------*/
N_Vector cv_znQ[L_MAX]; /* Nordsieck arrays for quadratures */
N_Vector cv_ewtQ; /* error weight vector for quadratures */
N_Vector cv_yQ; /* Unlike y, yQ is not allocated by the user */
N_Vector cv_acorQ; /* acorQ = yQ_n(m) - yQ_n(0) */
N_Vector cv_tempvQ; /* temporary storage vector (~ tempv) */
/*---------------------------
Sensitivity Related Vectors
---------------------------*/
N_Vector *cv_znS[L_MAX]; /* Nordsieck arrays for sensitivities */
N_Vector *cv_ewtS; /* error weight vectors for sensitivities */
N_Vector *cv_yS; /* yS=yS0 (allocated by the user) */
N_Vector *cv_acorS; /* acorS = yS_n(m) - yS_n(0) */
N_Vector *cv_tempvS; /* temporary storage vector (~ tempv) */
N_Vector *cv_ftempS; /* temporary storage vector (~ ftemp) */
booleantype cv_stgr1alloc; /* Did we allocate ncfS1, ncfnS1, and nniS1? */
/*--------------------------------------
Quadrature Sensitivity Related Vectors
--------------------------------------*/
N_Vector *cv_znQS[L_MAX]; /* Nordsieck arrays for quadr. sensitivities */
N_Vector *cv_ewtQS; /* error weight vectors for sensitivities */
N_Vector *cv_yQS; /* Unlike yS, yQS is not allocated by the user */
N_Vector *cv_acorQS; /* acorQS = yQS_n(m) - yQS_n(0) */
N_Vector *cv_tempvQS; /* temporary storage vector (~ tempv) */
N_Vector cv_ftempQ; /* temporary storage vector (~ ftemp) */
/*-----------------
Tstop information
-----------------*/
booleantype cv_tstopset;
realtype cv_tstop;
/*---------
Step Data
---------*/
int cv_q; /* current order */
int cv_qprime; /* order to be used on the next step
* qprime = q-1, q, or q+1 */
int cv_next_q; /* order to be used on the next step */
int cv_qwait; /* number of internal steps to wait before
* considering a change in q */
int cv_L; /* L = q + 1 */
realtype cv_hin;
realtype cv_h; /* current step size */
realtype cv_hprime; /* step size to be used on the next step */
realtype cv_next_h; /* step size to be used on the next step */
realtype cv_eta; /* eta = hprime / h */
realtype cv_hscale; /* value of h used in zn */
realtype cv_tn; /* current internal value of t */
realtype cv_tretlast; /* last value of t returned */
realtype cv_tau[L_MAX+1]; /* array of previous q+1 successful step
* sizes indexed from 1 to q+1 */
realtype cv_tq[NUM_TESTS+1]; /* array of test quantities indexed from
* 1 to NUM_TESTS(=5) */
realtype cv_l[L_MAX]; /* coefficients of l(x) (degree q poly) */
realtype cv_rl1; /* the scalar 1/l[1] */
realtype cv_gamma; /* gamma = h * rl1 */
realtype cv_gammap; /* gamma at the last setup call */
realtype cv_gamrat; /* gamma / gammap */
realtype cv_crate; /* est. corrector conv. rate in Nls */
realtype cv_crateS; /* est. corrector conv. rate in NlsStgr */
realtype cv_acnrm; /* | acor | */
realtype cv_acnrmQ; /* | acorQ | */
realtype cv_acnrmS; /* | acorS | */
realtype cv_acnrmQS; /* | acorQS | */
realtype cv_nlscoef; /* coeficient in nonlinear convergence test */
int cv_mnewt; /* Newton iteration counter */
int *cv_ncfS1; /* Array of Ns local counters for conv.
* failures (used in CVStep for STAGGERED1) */
/*------
Limits
------*/
int cv_qmax; /* q <= qmax */
long int cv_mxstep; /* maximum number of internal steps for one
user call */
int cv_maxcor; /* maximum number of corrector iterations for
the solution of the nonlinear equation */
int cv_maxcorS;
int cv_mxhnil; /* max. number of warning messages issued to the
user that t + h == t for the next internal step */
int cv_maxnef; /* maximum number of error test failures */
int cv_maxncf; /* maximum number of nonlinear conv. failures */
realtype cv_hmin; /* |h| >= hmin */
realtype cv_hmax_inv; /* |h| <= 1/hmax_inv */
realtype cv_etamax; /* eta <= etamax */
/*----------
Counters
----------*/
long int cv_nst; /* number of internal steps taken */
long int cv_nfe; /* number of f calls */
long int cv_nfQe; /* number of fQ calls */
long int cv_nfSe; /* number of fS calls */
long int cv_nfeS; /* number of f calls from sensi DQ */
long int cv_nfQSe; /* number of fQS calls */
long int cv_nfQeS; /* number of fQ calls from sensi DQ */
long int cv_ncfn; /* number of corrector convergence failures */
long int cv_ncfnS; /* number of total sensi. corr. conv. failures */
long int *cv_ncfnS1; /* number of sensi. corrector conv. failures */
long int cv_nni; /* number of nonlinear iterations performed */
long int cv_nniS; /* number of total sensi. nonlinear iterations */
long int *cv_nniS1; /* number of sensi. nonlinear iterations */
long int cv_netf; /* number of error test failures */
long int cv_netfQ; /* number of quadr. error test failures */
long int cv_netfS; /* number of sensi. error test failures */
long int cv_netfQS; /* number of quadr. sensi. error test failures */
long int cv_nsetups; /* number of setup calls */
long int cv_nsetupsS; /* number of setup calls due to sensitivities */
int cv_nhnil; /* number of messages issued to the user that
t + h == t for the next iternal step */
/*-----------------------------
Space requirements for CVODES
-----------------------------*/
long int cv_lrw1; /* no. of realtype words in 1 N_Vector y */
long int cv_liw1; /* no. of integer words in 1 N_Vector y */
long int cv_lrw1Q; /* no. of realtype words in 1 N_Vector yQ */
long int cv_liw1Q; /* no. of integer words in 1 N_Vector yQ */
long int cv_lrw; /* no. of realtype words in CVODES work vectors */
long int cv_liw; /* no. of integer words in CVODES work vectors */
/*----------------
Step size ratios
----------------*/
realtype cv_etaqm1; /* ratio of new to old h for order q-1 */
realtype cv_etaq; /* ratio of new to old h for order q */
realtype cv_etaqp1; /* ratio of new to old h for order q+1 */
/*------------------
Linear Solver Data
------------------*/
/* Linear Solver functions to be called */
int (*cv_linit)(struct CVodeMemRec *cv_mem);
int (*cv_lsetup)(struct CVodeMemRec *cv_mem, int convfail,
N_Vector ypred, N_Vector fpred, booleantype *jcurPtr,
N_Vector vtemp1, N_Vector vtemp2, N_Vector vtemp3);
int (*cv_lsolve)(struct CVodeMemRec *cv_mem, N_Vector b, N_Vector weight,
N_Vector ycur, N_Vector fcur);
void (*cv_lfree)(struct CVodeMemRec *cv_mem);
/* Linear Solver specific memory */
void *cv_lmem;
/* Flag to request a call to the setup routine */
booleantype cv_forceSetup;
/*------------
Saved Values
------------*/
int cv_qu; /* last successful q value used */
long int cv_nstlp; /* step number of last setup call */
realtype cv_h0u; /* actual initial stepsize */
realtype cv_hu; /* last successful h value used */
realtype cv_saved_tq5; /* saved value of tq[5] */
booleantype cv_jcur; /* is Jacobian info for linear solver current? */
realtype cv_tolsf; /* tolerance scale factor */
int cv_qmax_alloc; /* qmax used when allocating mem */
int cv_qmax_allocQ; /* qmax used when allocating quad. mem */
int cv_qmax_allocS; /* qmax used when allocating sensi. mem */
int cv_qmax_allocQS; /* qmax used when allocating quad. sensi. mem */
int cv_indx_acor; /* index of zn vector in which acor is saved */
booleantype cv_setupNonNull; /* Does setup do something? */
/*--------------------------------------------------------------------
Flags turned ON by CVodeInit, CVodeSensMalloc, and CVodeQuadMalloc
and read by CVodeReInit, CVodeSensReInit, and CVodeQuadReInit
--------------------------------------------------------------------*/
booleantype cv_VabstolMallocDone;
booleantype cv_MallocDone;
booleantype cv_VabstolQMallocDone;
booleantype cv_QuadMallocDone;
booleantype cv_VabstolSMallocDone;
booleantype cv_SabstolSMallocDone;
booleantype cv_SensMallocDone;
booleantype cv_VabstolQSMallocDone;
booleantype cv_SabstolQSMallocDone;
booleantype cv_QuadSensMallocDone;
/*-------------------------------------------
Error handler function and error ouput file
-------------------------------------------*/
CVErrHandlerFn cv_ehfun; /* Error messages are handled by ehfun */
void *cv_eh_data; /* dats pointer passed to ehfun */
FILE *cv_errfp; /* CVODES error messages are sent to errfp */
/*-------------------------
Stability Limit Detection
-------------------------*/
booleantype cv_sldeton; /* Is Stability Limit Detection on? */
realtype cv_ssdat[6][4]; /* scaled data array for STALD */
int cv_nscon; /* counter for STALD method */
long int cv_nor; /* counter for number of order reductions */
/*----------------
Rootfinding Data
----------------*/
CVRootFn cv_gfun; /* Function g for roots sought */
int cv_nrtfn; /* number of components of g */
int *cv_iroots; /* array for root information */
int *cv_rootdir; /* array specifying direction of zero-crossing */
realtype cv_tlo; /* nearest endpoint of interval in root search */
realtype cv_thi; /* farthest endpoint of interval in root search */
realtype cv_trout; /* t value returned by rootfinding routine */
realtype *cv_glo; /* saved array of g values at t = tlo */
realtype *cv_ghi; /* saved array of g values at t = thi */
realtype *cv_grout; /* array of g values at t = trout */
realtype cv_toutc; /* copy of tout (if NORMAL mode) */
realtype cv_ttol; /* tolerance on root location trout */
int cv_taskc; /* copy of parameter itask */
int cv_irfnd; /* flag showing whether last step had a root */
long int cv_nge; /* counter for g evaluations */
booleantype *cv_gactive; /* array with active/inactive event functions */
int cv_mxgnull; /* number of warning messages about possible g==0 */
/*------------------------
Adjoint sensitivity data
------------------------*/
booleantype cv_adj; /* TRUE if performing ASA */
struct CVadjMemRec *cv_adj_mem; /* Pointer to adjoint memory structure */
booleantype cv_adjMallocDone;
} *CVodeMem;
/*
* =================================================================
* A D J O I N T M O D U L E M E M O R Y B L O C K
* =================================================================
*/
/*
* -----------------------------------------------------------------
* Types : struct CkpntMemRec, CkpntMem
* -----------------------------------------------------------------
* The type CkpntMem is type pointer to struct CkpntMemRec.
* This structure contains fields to store all information at a
* check point that is needed to 'hot' start cvodes.
* -----------------------------------------------------------------
*/
struct CkpntMemRec {
/* Integration limits */
realtype ck_t0;
realtype ck_t1;
/* Nordsieck History Array */
N_Vector ck_zn[L_MAX];
/* Do we need to carry quadratures? */
booleantype ck_quadr;
/* Nordsieck History Array for quadratures */
N_Vector ck_znQ[L_MAX];
/* Do we need to carry sensitivities? */
booleantype ck_sensi;
/* number of sensitivities */
int ck_Ns;
/* Nordsieck History Array for sensitivities */
N_Vector *ck_znS[L_MAX];
/* Do we need to carry quadrature sensitivities? */
booleantype ck_quadr_sensi;
/* Nordsieck History Array for quadrature sensitivities */
N_Vector *ck_znQS[L_MAX];
/* Was ck_zn[qmax] allocated?
ck_zqm = 0 - no
ck_zqm = qmax - yes */
int ck_zqm;
/* Step data */
long int ck_nst;
realtype ck_tretlast;
int ck_q;
int ck_qprime;
int ck_qwait;
int ck_L;
realtype ck_gammap;
realtype ck_h;
realtype ck_hprime;
realtype ck_hscale;
realtype ck_eta;
realtype ck_etamax;
realtype ck_tau[L_MAX+1];
realtype ck_tq[NUM_TESTS+1];
realtype ck_l[L_MAX];
/* Saved values */
realtype ck_saved_tq5;
/* Pointer to next structure in list */
struct CkpntMemRec *ck_next;
};
/*
* -----------------------------------------------------------------
* Types for functions provided by an interpolation module
* -----------------------------------------------------------------
* cvaIMMallocFn: Type for a function that initializes the content
* field of the structures in the dt array
* cvaIMFreeFn: Type for a function that deallocates the content
* field of the structures in the dt array
* cvaIMGetYFn: Type for a function that returns the
* interpolated forward solution.
* cvaIMStorePnt: Type for a function that stores a new
* point in the structure d
* -----------------------------------------------------------------
*/
typedef booleantype (*cvaIMMallocFn)(CVodeMem cv_mem);
typedef void (*cvaIMFreeFn)(CVodeMem cv_mem);
typedef int (*cvaIMGetYFn)(CVodeMem cv_mem, realtype t, N_Vector y, N_Vector *yS);
typedef int (*cvaIMStorePntFn)(CVodeMem cv_mem, DtpntMem d);
/*
* -----------------------------------------------------------------
* Type : struct DtpntMemRec
* -----------------------------------------------------------------
* This structure contains fields to store all information at a
* data point that is needed to interpolate solution of forward
* simulations. Its content field depends on IMtype.
* -----------------------------------------------------------------
*/
struct DtpntMemRec {
realtype t; /* time */
void *content; /* IMtype-dependent content */
};
/* Data for cubic Hermite interpolation */
typedef struct HermiteDataMemRec {
N_Vector y;
N_Vector yd;
N_Vector *yS;
N_Vector *ySd;
} *HermiteDataMem;
/* Data for polynomial interpolation */
typedef struct PolynomialDataMemRec {
N_Vector y;
N_Vector *yS;
int order;
} *PolynomialDataMem;
/*
* -----------------------------------------------------------------
* Type : struct CVodeBMemRec
* -----------------------------------------------------------------
* The type CVodeBMem is a pointer to a structure which stores all
* information for ONE backward problem.
* The CVadjMem structure contains a linked list of CVodeBMem pointers
* -----------------------------------------------------------------
*/
struct CVodeBMemRec {
/* Index of this backward problem */
int cv_index;
/* Time at which the backward problem is initialized */
realtype cv_t0;
/* CVODES memory for this backward problem */
CVodeMem cv_mem;
/* Flags to indicate that this backward problem's RHS or quad RHS
* require forward sensitivities */
booleantype cv_f_withSensi;
booleantype cv_fQ_withSensi;
/* Right hand side function for backward run */
CVRhsFnB cv_f;
CVRhsFnBS cv_fs;
/* Right hand side quadrature function for backward run */
CVQuadRhsFnB cv_fQ;
CVQuadRhsFnBS cv_fQs;
/* User user_data */
void *cv_user_data;
/* Memory block for a linear solver's interface to CVODEA */
void *cv_lmem;
/* Function to free any memory allocated by the linear solver */
void (*cv_lfree)(CVodeBMem cvB_mem);
/* Memory block for a preconditioner's module interface to CVODEA */
void *cv_pmem;
/* Function to free any memory allocated by the preconditioner module */
void (*cv_pfree)(CVodeBMem cvB_mem);
/* Time at which to extract solution / quadratures */
realtype cv_tout;
/* Workspace Nvector */
N_Vector cv_y;
/* Pointer to next structure in list */
struct CVodeBMemRec *cv_next;
};
/*
* -----------------------------------------------------------------
* Type : struct CVadjMemRec
* -----------------------------------------------------------------
* The type CVadjMem is type pointer to struct CVadjMemRec.
* This structure contins fields to store all information
* necessary for adjoint sensitivity analysis.
* -----------------------------------------------------------------
*/
struct CVadjMemRec {
/* --------------------
* Forward problem data
* -------------------- */
/* Integration interval */
realtype ca_tinitial, ca_tfinal;
/* Flag for first call to CVodeF */
booleantype ca_firstCVodeFcall;
/* Flag if CVodeF was called with TSTOP */
booleantype ca_tstopCVodeFcall;
realtype ca_tstopCVodeF;
/* ----------------------
* Backward problems data
* ---------------------- */
/* Storage for backward problems */
struct CVodeBMemRec *cvB_mem;
/* Number of backward problems */
int ca_nbckpbs;
/* Address of current backward problem */
struct CVodeBMemRec *ca_bckpbCrt;
/* Flag for first call to CVodeB */
booleantype ca_firstCVodeBcall;
/* ----------------
* Check point data
* ---------------- */
/* Storage for check point information */
struct CkpntMemRec *ck_mem;
/* Number of check points */
int ca_nckpnts;
/* address of the check point structure for which data is available */
struct CkpntMemRec *ca_ckpntData;
/* ------------------
* Interpolation data
* ------------------ */
/* Number of steps between 2 check points */
long int ca_nsteps;
/* Storage for data from forward runs */
struct DtpntMemRec **dt_mem;
/* Actual number of data points in dt_mem (typically np=nsteps+1) */
long int ca_np;
/* Interpolation type */
int ca_IMtype;
/* Functions set by the interpolation module */
cvaIMMallocFn ca_IMmalloc;
cvaIMFreeFn ca_IMfree;
cvaIMStorePntFn ca_IMstore; /* store a new interpolation point */
cvaIMGetYFn ca_IMget; /* interpolate forward solution */
/* Flags controlling the interpolation module */
booleantype ca_IMmallocDone; /* IM initialized? */
booleantype ca_IMnewData; /* new data available in dt_mem?*/
booleantype ca_IMstoreSensi; /* store sensitivities? */
booleantype ca_IMinterpSensi; /* interpolate sensitivities? */
/* Workspace for the interpolation module */
N_Vector ca_Y[L_MAX]; /* pointers to zn[i] */
N_Vector *ca_YS[L_MAX]; /* pointers to znS[i] */
realtype ca_T[L_MAX];
/* -------------------------------
* Workspace for wrapper functions
* ------------------------------- */
N_Vector ca_ytmp;
N_Vector *ca_yStmp;
};
/*
* =================================================================
* I N T E R F A C E T O L I N E A R S O L V E R S
* =================================================================
*/
/*
* -----------------------------------------------------------------
* Communication between CVODE and a CVODE Linear Solver
* -----------------------------------------------------------------
* convfail (input to cv_lsetup)
*
* CV_NO_FAILURES : Either this is the first cv_setup call for this
* step, or the local error test failed on the
* previous attempt at this step (but the Newton
* iteration converged).
*
* CV_FAIL_BAD_J : This value is passed to cv_lsetup if
*
* (a) The previous Newton corrector iteration
* did not converge and the linear solver's
* setup routine indicated that its Jacobian-
* related data is not current
* or
* (b) During the previous Newton corrector
* iteration, the linear solver's solve routine
* failed in a recoverable manner and the
* linear solver's setup routine indicated that
* its Jacobian-related data is not current.
*
* CV_FAIL_OTHER : During the current internal step try, the
* previous Newton iteration failed to converge
* even though the linear solver was using current
* Jacobian-related data.
* -----------------------------------------------------------------
*/
/* Constants for convfail (input to cv_lsetup) */
#define CV_NO_FAILURES 0
#define CV_FAIL_BAD_J 1
#define CV_FAIL_OTHER 2
/*
* -----------------------------------------------------------------
* int (*cv_linit)(CVodeMem cv_mem);
* -----------------------------------------------------------------
* The purpose of cv_linit is to complete initializations for a
* specific linear solver, such as counters and statistics.
* An LInitFn should return 0 if it has successfully initialized the
* CVODE linear solver and a negative value otherwise.
* If an error does occur, an appropriate message should be sent to
* the error handler function.
* -----------------------------------------------------------------
*/
/*
* -----------------------------------------------------------------
* int (*cv_lsetup)(CVodeMem cv_mem, int convfail, N_Vector ypred,
* N_Vector fpred, booleantype *jcurPtr,
* N_Vector vtemp1, N_Vector vtemp2,
* N_Vector vtemp3);
* -----------------------------------------------------------------
* The job of cv_lsetup is to prepare the linear solver for
* subsequent calls to cv_lsolve. It may recompute Jacobian-
* related data is it deems necessary. Its parameters are as
* follows:
*
* cv_mem - problem memory pointer of type CVodeMem. See the
* typedef earlier in this file.
*
* convfail - a flag to indicate any problem that occurred during
* the solution of the nonlinear equation on the
* current time step for which the linear solver is
* being used. This flag can be used to help decide
* whether the Jacobian data kept by a CVODE linear
* solver needs to be updated or not.
* Its possible values have been documented above.
*
* ypred - the predicted y vector for the current CVODE internal
* step.
*
* fpred - f(tn, ypred).
*
* jcurPtr - a pointer to a boolean to be filled in by cv_lsetup.
* The function should set *jcurPtr=TRUE if its Jacobian
* data is current after the call and should set
* *jcurPtr=FALSE if its Jacobian data is not current.
* Note: If cv_lsetup calls for re-evaluation of
* Jacobian data (based on convfail and CVODE state
* data), it should return *jcurPtr=TRUE always;
* otherwise an infinite loop can result.
*
* vtemp1 - temporary N_Vector provided for use by cv_lsetup.
*
* vtemp3 - temporary N_Vector provided for use by cv_lsetup.
*
* vtemp3 - temporary N_Vector provided for use by cv_lsetup.
*
* The cv_lsetup routine should return 0 if successful, a positive
* value for a recoverable error, and a negative value for an
* unrecoverable error.
* -----------------------------------------------------------------
*/
/*
* -----------------------------------------------------------------
* int (*cv_lsolve)(CVodeMem cv_mem, N_Vector b, N_Vector weight,
* N_Vector ycur, N_Vector fcur);
* -----------------------------------------------------------------
* cv_lsolve must solve the linear equation P x = b, where
* P is some approximation to (I - gamma J), J = (df/dy)(tn,ycur)
* and the RHS vector b is input. The N-vector ycur contains
* the solver's current approximation to y(tn) and the vector
* fcur contains the N_Vector f(tn,ycur). The solution is to be
* returned in the vector b. cv_lsolve returns a positive value
* for a recoverable error and a negative value for an
* unrecoverable error. Success is indicated by a 0 return value.
* -----------------------------------------------------------------
*/
/*
* -----------------------------------------------------------------
* void (*cv_lfree)(CVodeMem cv_mem);
* -----------------------------------------------------------------
* cv_lfree should free up any memory allocated by the linear
* solver. This routine is called once a problem has been
* completed and the linear solver is no longer needed.
* -----------------------------------------------------------------
*/
/*
* =================================================================
* C V O D E S I N T E R N A L F U N C T I O N S
* =================================================================
*/
/* Prototype of internal ewtSet function */
int cvEwtSet(N_Vector ycur, N_Vector weight, void *data);
/* High level error handler */
void cvProcessError(CVodeMem cv_mem,
int error_code, const char *module, const char *fname,
const char *msgfmt, ...);
/* Prototype of internal errHandler function */
void cvErrHandler(int error_code, const char *module, const char *function,
char *msg, void *data);
/* Prototypes for internal sensitivity rhs wrappers */
int cvSensRhsWrapper(CVodeMem cv_mem, realtype time,
N_Vector ycur, N_Vector fcur,
N_Vector *yScur, N_Vector *fScur,
N_Vector temp1, N_Vector temp2);
int cvSensRhs1Wrapper(CVodeMem cv_mem, realtype time,
N_Vector ycur, N_Vector fcur,
int is, N_Vector yScur, N_Vector fScur,
N_Vector temp1, N_Vector temp2);
/* Prototypes for internal sensitivity rhs DQ functions */
int cvSensRhsInternalDQ(int Ns, realtype t,
N_Vector y, N_Vector ydot,
N_Vector *yS, N_Vector *ySdot,
void *fS_data,
N_Vector tempv, N_Vector ftemp);
int cvSensRhs1InternalDQ(int Ns, realtype t,
N_Vector y, N_Vector ydot,
int is, N_Vector yS, N_Vector ySdot,
void *fS_data,
N_Vector tempv, N_Vector ftemp);
/*
* =================================================================
* C V O D E S E R R O R M E S S A G E S
* =================================================================
*/
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define MSG_TIME "t = %Lg"
#define MSG_TIME_H "t = %Lg and h = %Lg"
#define MSG_TIME_INT "t = %Lg is not between tcur - hu = %Lg and tcur = %Lg."
#define MSG_TIME_TOUT "tout = %Lg"
#define MSG_TIME_TSTOP "tstop = %Lg"
#elif defined(SUNDIALS_DOUBLE_PRECISION)
#define MSG_TIME "t = %lg"
#define MSG_TIME_H "t = %lg and h = %lg"
#define MSG_TIME_INT "t = %lg is not between tcur - hu = %lg and tcur = %lg."
#define MSG_TIME_TOUT "tout = %lg"
#define MSG_TIME_TSTOP "tstop = %lg"
#else
#define MSG_TIME "t = %g"
#define MSG_TIME_H "t = %g and h = %g"
#define MSG_TIME_INT "t = %g is not between tcur - hu = %g and tcur = %g."
#define MSG_TIME_TOUT "tout = %g"
#define MSG_TIME_TSTOP "tstop = %g"
#endif
/* Initialization and I/O error messages */
#define MSGCV_NO_MEM "cvode_mem = NULL illegal."
#define MSGCV_CVMEM_FAIL "Allocation of cvode_mem failed."
#define MSGCV_MEM_FAIL "A memory request failed."
#define MSGCV_BAD_LMM "Illegal value for lmm. The legal values are CV_ADAMS and CV_BDF."
#define MSGCV_BAD_ITER "Illegal value for iter. The legal values are CV_FUNCTIONAL and CV_NEWTON."
#define MSGCV_NO_MALLOC "Attempt to call before CVodeInit."
#define MSGCV_NEG_MAXORD "maxord <= 0 illegal."
#define MSGCV_BAD_MAXORD "Illegal attempt to increase maximum method order."
#define MSGCV_SET_SLDET "Attempt to use stability limit detection with the CV_ADAMS method illegal."
#define MSGCV_NEG_HMIN "hmin < 0 illegal."
#define MSGCV_NEG_HMAX "hmax < 0 illegal."
#define MSGCV_BAD_HMIN_HMAX "Inconsistent step size limits: hmin > hmax."
#define MSGCV_BAD_RELTOL "reltol < 0 illegal."
#define MSGCV_BAD_ABSTOL "abstol has negative component(s) (illegal)."
#define MSGCV_NULL_ABSTOL "abstol = NULL illegal."
#define MSGCV_NULL_Y0 "y0 = NULL illegal."
#define MSGCV_NULL_F "f = NULL illegal."
#define MSGCV_NULL_G "g = NULL illegal."
#define MSGCV_BAD_NVECTOR "A required vector operation is not implemented."
#define MSGCV_BAD_K "Illegal value for k."
#define MSGCV_NULL_DKY "dky = NULL illegal."
#define MSGCV_BAD_T "Illegal value for t." MSG_TIME_INT
#define MSGCV_NO_ROOT "Rootfinding was not initialized."
#define MSGCV_NO_QUAD "Quadrature integration not activated."
#define MSGCV_BAD_ITOLQ "Illegal value for itolQ. The legal values are CV_SS and CV_SV."
#define MSGCV_NULL_ABSTOLQ "abstolQ = NULL illegal."
#define MSGCV_BAD_RELTOLQ "reltolQ < 0 illegal."
#define MSGCV_BAD_ABSTOLQ "abstolQ has negative component(s) (illegal)."
#define MSGCV_SENSINIT_2 "Sensitivity analysis already initialized."
#define MSGCV_NO_SENSI "Forward sensitivity analysis not activated."
#define MSGCV_BAD_ITOLS "Illegal value for itolS. The legal values are CV_SS, CV_SV, and CV_EE."
#define MSGCV_NULL_ABSTOLS "abstolS = NULL illegal."
#define MSGCV_BAD_RELTOLS "reltolS < 0 illegal."
#define MSGCV_BAD_ABSTOLS "abstolS has negative component(s) (illegal)."
#define MSGCV_BAD_PBAR "pbar has zero component(s) (illegal)."
#define MSGCV_BAD_PLIST "plist has negative component(s) (illegal)."
#define MSGCV_BAD_NS "NS <= 0 illegal."
#define MSGCV_NULL_YS0 "yS0 = NULL illegal."
#define MSGCV_BAD_ISM "Illegal value for ism. Legal values are: CV_SIMULTANEOUS, CV_STAGGERED and CV_STAGGERED1."
#define MSGCV_BAD_IFS "Illegal value for ifS. Legal values are: CV_ALLSENS and CV_ONESENS."
#define MSGCV_BAD_ISM_IFS "Illegal ism = CV_STAGGERED1 for CVodeSensInit."
#define MSGCV_BAD_IS "Illegal value for is."
#define MSGCV_NULL_DKYA "dkyA = NULL illegal."
#define MSGCV_BAD_DQTYPE "Illegal value for DQtype. Legal values are: CV_CENTERED and CV_FORWARD."
#define MSGCV_BAD_DQRHO "DQrhomax < 0 illegal."
#define MSGCV_BAD_ITOLQS "Illegal value for itolQS. The legal values are CV_SS, CV_SV, and CV_EE."
#define MSGCV_NULL_ABSTOLQS "abstolQS = NULL illegal."
#define MSGCV_BAD_RELTOLQS "reltolQS < 0 illegal."
#define MSGCV_BAD_ABSTOLQS "abstolQS has negative component(s) (illegal)."
#define MSGCV_NO_QUADSENSI "Forward sensitivity analysis for quadrature variables not activated."
#define MSGCV_NULL_YQS0 "yQS0 = NULL illegal."
/* CVode Error Messages */
#define MSGCV_NO_TOL "No integration tolerances have been specified."
#define MSGCV_LSOLVE_NULL "The linear solver's solve routine is NULL."
#define MSGCV_YOUT_NULL "yout = NULL illegal."
#define MSGCV_TRET_NULL "tret = NULL illegal."
#define MSGCV_BAD_EWT "Initial ewt has component(s) equal to zero (illegal)."
#define MSGCV_EWT_NOW_BAD "At " MSG_TIME ", a component of ewt has become <= 0."
#define MSGCV_BAD_ITASK "Illegal value for itask."
#define MSGCV_BAD_H0 "h0 and tout - t0 inconsistent."
#define MSGCV_BAD_TOUT "Trouble interpolating at " MSG_TIME_TOUT ". tout too far back in direction of integration"
#define MSGCV_EWT_FAIL "The user-provide EwtSet function failed."
#define MSGCV_EWT_NOW_FAIL "At " MSG_TIME ", the user-provide EwtSet function failed."
#define MSGCV_LINIT_FAIL "The linear solver's init routine failed."
#define MSGCV_HNIL_DONE "The above warning has been issued mxhnil times and will not be issued again for this problem."
#define MSGCV_TOO_CLOSE "tout too close to t0 to start integration."
#define MSGCV_MAX_STEPS "At " MSG_TIME ", mxstep steps taken before reaching tout."
#define MSGCV_TOO_MUCH_ACC "At " MSG_TIME ", too much accuracy requested."
#define MSGCV_HNIL "Internal " MSG_TIME_H " are such that t + h = t on the next step. The solver will continue anyway."
#define MSGCV_ERR_FAILS "At " MSG_TIME_H ", the error test failed repeatedly or with |h| = hmin."
#define MSGCV_CONV_FAILS "At " MSG_TIME_H ", the corrector convergence test failed repeatedly or with |h| = hmin."
#define MSGCV_SETUP_FAILED "At " MSG_TIME ", the setup routine failed in an unrecoverable manner."
#define MSGCV_SOLVE_FAILED "At " MSG_TIME ", the solve routine failed in an unrecoverable manner."
#define MSGCV_RHSFUNC_FAILED "At " MSG_TIME ", the right-hand side routine failed in an unrecoverable manner."
#define MSGCV_RHSFUNC_UNREC "At " MSG_TIME ", the right-hand side failed in a recoverable manner, but no recovery is possible."
#define MSGCV_RHSFUNC_REPTD "At " MSG_TIME " repeated recoverable right-hand side function errors."
#define MSGCV_RHSFUNC_FIRST "The right-hand side routine failed at the first call."
#define MSGCV_RTFUNC_FAILED "At " MSG_TIME ", the rootfinding routine failed in an unrecoverable manner."
#define MSGCV_CLOSE_ROOTS "Root found at and very near " MSG_TIME "."
#define MSGCV_BAD_TSTOP "The value " MSG_TIME_TSTOP " is behind current " MSG_TIME " in the direction of integration."
#define MSGCV_INACTIVE_ROOTS "At the end of the first step, there are still some root functions identically 0. This warning will not be issued again."
#define MSGCV_NO_TOLQ "No integration tolerances for quadrature variables have been specified."
#define MSGCV_BAD_EWTQ "Initial ewtQ has component(s) equal to zero (illegal)."
#define MSGCV_EWTQ_NOW_BAD "At " MSG_TIME ", a component of ewtQ has become <= 0."
#define MSGCV_QRHSFUNC_FAILED "At " MSG_TIME ", the quadrature right-hand side routine failed in an unrecoverable manner."
#define MSGCV_QRHSFUNC_UNREC "At " MSG_TIME ", the quadrature right-hand side failed in a recoverable manner, but no recovery is possible."
#define MSGCV_QRHSFUNC_REPTD "At " MSG_TIME " repeated recoverable quadrature right-hand side function errors."
#define MSGCV_QRHSFUNC_FIRST "The quadrature right-hand side routine failed at the first call."
#define MSGCV_NO_TOLS "No integration tolerances for sensitivity variables have been specified."
#define MSGCV_NULL_P "p = NULL when using internal DQ for sensitivity RHS illegal."
#define MSGCV_BAD_EWTS "Initial ewtS has component(s) equal to zero (illegal)."
#define MSGCV_EWTS_NOW_BAD "At " MSG_TIME ", a component of ewtS has become <= 0."
#define MSGCV_SRHSFUNC_FAILED "At " MSG_TIME ", the sensitivity right-hand side routine failed in an unrecoverable manner."
#define MSGCV_SRHSFUNC_UNREC "At " MSG_TIME ", the sensitivity right-hand side failed in a recoverable manner, but no recovery is possible."
#define MSGCV_SRHSFUNC_REPTD "At " MSG_TIME " repeated recoverable sensitivity right-hand side function errors."
#define MSGCV_SRHSFUNC_FIRST "The sensitivity right-hand side routine failed at the first call."
#define MSGCV_NULL_FQ "CVODES is expected to use DQ to evaluate the RHS of quad. sensi., but quadratures were not initialized."
#define MSGCV_NO_TOLQS "No integration tolerances for quadrature sensitivity variables have been specified."
#define MSGCV_BAD_EWTQS "Initial ewtQS has component(s) equal to zero (illegal)."
#define MSGCV_EWTQS_NOW_BAD "At " MSG_TIME ", a component of ewtQS has become <= 0."
#define MSGCV_QSRHSFUNC_FAILED "At " MSG_TIME ", the quadrature sensitivity right-hand side routine failed in an unrecoverable manner."
#define MSGCV_QSRHSFUNC_UNREC "At " MSG_TIME ", the quadrature sensitivity right-hand side failed in a recoverable manner, but no recovery is possible."
#define MSGCV_QSRHSFUNC_REPTD "At " MSG_TIME " repeated recoverable quadrature sensitivity right-hand side function errors."
#define MSGCV_QSRHSFUNC_FIRST "The quadrature sensitivity right-hand side routine failed at the first call."
/*
* =================================================================
* C V O D E A E R R O R M E S S A G E S
* =================================================================
*/
#define MSGCV_NO_ADJ "Illegal attempt to call before calling CVodeAdjMalloc."
#define MSGCV_BAD_STEPS "Steps nonpositive illegal."
#define MSGCV_BAD_INTERP "Illegal value for interp."
#define MSGCV_BAD_WHICH "Illegal value for which."
#define MSGCV_NO_BCK "No backward problems have been defined yet."
#define MSGCV_NO_FWD "Illegal attempt to call before calling CVodeF."
#define MSGCV_BAD_TB0 "The initial time tB0 for problem %d is outside the interval over which the forward problem was solved."
#define MSGCV_BAD_SENSI "At least one backward problem requires sensitivities, but they were not stored for interpolation."
#define MSGCV_BAD_ITASKB "Illegal value for itaskB. Legal values are CV_NORMAL and CV_ONE_STEP."
#define MSGCV_BAD_TBOUT "The final time tBout is outside the interval over which the forward problem was solved."
#define MSGCV_BACK_ERROR "Error occured while integrating backward problem # %d"
#define MSGCV_BAD_TINTERP "Bad t = %g for interpolation."
#define MSGCV_WRONG_INTERP "This function cannot be called for the specified interp type."
#ifdef __cplusplus
}
#endif
#endif
| bsd-3-clause |
NifTK/MITK | Modules/QtWidgets/src/QmitkStdMultiWidget.cpp | 64616 | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#define SMW_INFO MITK_INFO("widget.stdmulti")
#include "QmitkStdMultiWidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <qsplitter.h>
#include <QList>
#include <QMouseEvent>
#include <QTimer>
#include <mitkProperties.h>
#include <mitkPlaneGeometryDataMapper2D.h>
#include <mitkPointSet.h>
#include <mitkLine.h>
#include <mitkInteractionConst.h>
#include <mitkDataStorage.h>
#include <mitkOverlayManager.h>
#include <mitkNodePredicateBase.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkStatusBar.h>
#include <mitkImage.h>
#include <mitkVtkLayerController.h>
#include <mitkCameraController.h>
#include <vtkTextProperty.h>
#include <vtkCornerAnnotation.h>
#include <vtkMitkRectangleProp.h>
#include "mitkPixelTypeMultiplex.h"
#include "mitkImagePixelReadAccessor.h"
#include <iomanip>
QmitkStdMultiWidget::QmitkStdMultiWidget(QWidget* parent, Qt::WindowFlags f, mitk::RenderingManager* renderingManager, mitk::BaseRenderer::RenderingMode::Type renderingMode, const QString& name)
: QWidget(parent, f),
mitkWidget1(NULL),
mitkWidget2(NULL),
mitkWidget3(NULL),
mitkWidget4(NULL),
levelWindowWidget(NULL),
QmitkStdMultiWidgetLayout(NULL),
m_Layout(LAYOUT_DEFAULT),
m_PlaneMode(PLANE_MODE_SLICING),
m_RenderingManager(renderingManager),
m_GradientBackgroundFlag(true),
m_TimeNavigationController(NULL),
m_MainSplit(NULL),
m_LayoutSplit(NULL),
m_SubSplit1(NULL),
m_SubSplit2(NULL),
mitkWidget1Container(NULL),
mitkWidget2Container(NULL),
mitkWidget3Container(NULL),
mitkWidget4Container(NULL),
m_PendingCrosshairPositionEvent(false),
m_CrosshairNavigationEnabled(false)
{
/******************************************************
* Use the global RenderingManager if none was specified
* ****************************************************/
if (m_RenderingManager == NULL)
{
m_RenderingManager = mitk::RenderingManager::GetInstance();
}
m_TimeNavigationController = m_RenderingManager->GetTimeNavigationController();
/*******************************/
//Create Widget manually
/*******************************/
//create Layouts
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
QmitkStdMultiWidgetLayout->setContentsMargins(0,0,0,0);
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//creae Widget Container
mitkWidget1Container = new QWidget(m_SubSplit1);
mitkWidget2Container = new QWidget(m_SubSplit1);
mitkWidget3Container = new QWidget(m_SubSplit2);
mitkWidget4Container = new QWidget(m_SubSplit2);
mitkWidget1Container->setContentsMargins(0,0,0,0);
mitkWidget2Container->setContentsMargins(0,0,0,0);
mitkWidget3Container->setContentsMargins(0,0,0,0);
mitkWidget4Container->setContentsMargins(0,0,0,0);
//create Widget Layout
QHBoxLayout *mitkWidgetLayout1 = new QHBoxLayout(mitkWidget1Container);
QHBoxLayout *mitkWidgetLayout2 = new QHBoxLayout(mitkWidget2Container);
QHBoxLayout *mitkWidgetLayout3 = new QHBoxLayout(mitkWidget3Container);
QHBoxLayout *mitkWidgetLayout4 = new QHBoxLayout(mitkWidget4Container);
m_CornerAnnotations[0] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[1] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[2] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotations[3] = vtkSmartPointer<vtkCornerAnnotation>::New();
m_RectangleProps[0] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[1] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[2] = vtkSmartPointer<vtkMitkRectangleProp>::New();
m_RectangleProps[3] = vtkSmartPointer<vtkMitkRectangleProp>::New();
mitkWidgetLayout1->setMargin(0);
mitkWidgetLayout2->setMargin(0);
mitkWidgetLayout3->setMargin(0);
mitkWidgetLayout4->setMargin(0);
//set Layout to Widget Container
mitkWidget1Container->setLayout(mitkWidgetLayout1);
mitkWidget2Container->setLayout(mitkWidgetLayout2);
mitkWidget3Container->setLayout(mitkWidgetLayout3);
mitkWidget4Container->setLayout(mitkWidgetLayout4);
//set SizePolicy
mitkWidget1Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget2Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget3Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
mitkWidget4Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
//insert Widget Container into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//Create RenderWindows 1
mitkWidget1 = new QmitkRenderWindow(mitkWidget1Container, name + ".widget1", NULL, m_RenderingManager,renderingMode);
mitkWidget1->SetLayoutIndex( AXIAL );
mitkWidgetLayout1->addWidget(mitkWidget1);
//Create RenderWindows 2
mitkWidget2 = new QmitkRenderWindow(mitkWidget2Container, name + ".widget2", NULL, m_RenderingManager,renderingMode);
mitkWidget2->setEnabled( true );
mitkWidget2->SetLayoutIndex( SAGITTAL );
mitkWidgetLayout2->addWidget(mitkWidget2);
//Create RenderWindows 3
mitkWidget3 = new QmitkRenderWindow(mitkWidget3Container, name + ".widget3", NULL, m_RenderingManager,renderingMode);
mitkWidget3->SetLayoutIndex( CORONAL );
mitkWidgetLayout3->addWidget(mitkWidget3);
//Create RenderWindows 4
mitkWidget4 = new QmitkRenderWindow(mitkWidget4Container, name + ".widget4", NULL, m_RenderingManager,renderingMode);
mitkWidget4->SetLayoutIndex( THREE_D );
mitkWidgetLayout4->addWidget(mitkWidget4);
//create SignalSlot Connection
connect( mitkWidget1, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget1, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget1, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget1, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget2, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget2, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget2, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget2, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget3, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget3, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget3, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget3, SLOT(OnWidgetPlaneModeChanged(int)) );
connect( mitkWidget4, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) );
connect( mitkWidget4, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) );
connect( mitkWidget4, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) );
connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget4, SLOT(OnWidgetPlaneModeChanged(int)) );
//Create Level Window Widget
levelWindowWidget = new QmitkLevelWindowWidget( m_MainSplit ); //this
levelWindowWidget->setObjectName(QString::fromUtf8("levelWindowWidget"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(levelWindowWidget->sizePolicy().hasHeightForWidth());
levelWindowWidget->setSizePolicy(sizePolicy);
levelWindowWidget->setMaximumWidth(50);
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//resize Image.
this->resize( QSize(364, 477).expandedTo(minimumSizeHint()) );
//Initialize the widgets.
this->InitializeWidget();
//Activate Widget Menu
this->ActivateMenuWidget( true );
}
void QmitkStdMultiWidget::InitializeWidget()
{
//Make all black and overwrite renderwindow 4
this->FillGradientBackgroundWithBlack();
//This is #191919 in hex
float tmp1[3] = { 0.098f, 0.098f, 0.098f};
//This is #7F7F7F in hex
float tmp2[3] = { 0.498f, 0.498f, 0.498f};
m_GradientBackgroundColors[3] = std::make_pair(mitk::Color(tmp1), mitk::Color(tmp2));
//Yellow is default color for widget4
m_DecorationColorWidget4[0] = 1.0f;
m_DecorationColorWidget4[1] = 1.0f;
m_DecorationColorWidget4[2] = 0.0f;
// transfer colors in WorldGeometry-Nodes of the associated Renderer
mitk::IntProperty::Pointer layer;
// of widget 1
m_PlaneNode1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode1->SetColor(GetDecorationColor(0));
layer = mitk::IntProperty::New(1000);
m_PlaneNode1->SetProperty("layer",layer);
// ... of widget 2
m_PlaneNode2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode2->SetColor(GetDecorationColor(1));
layer = mitk::IntProperty::New(1000);
m_PlaneNode2->SetProperty("layer",layer);
// ... of widget 3
m_PlaneNode3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode3->SetColor(GetDecorationColor(2));
layer = mitk::IntProperty::New(1000);
m_PlaneNode3->SetProperty("layer",layer);
//The parent node
m_ParentNodeForGeometryPlanes = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode();
layer = mitk::IntProperty::New(1000);
m_ParentNodeForGeometryPlanes->SetProperty("layer",layer);
mitk::OverlayManager::Pointer OverlayManager = mitk::OverlayManager::New();
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetOverlayManager(OverlayManager);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetMapperID(mitk::BaseRenderer::Standard3D);
// Set plane mode (slicing/rotation behavior) to slicing (default)
m_PlaneMode = PLANE_MODE_SLICING;
// Set default view directions for SNCs
mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Axial );
mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Sagittal );
mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Frontal );
mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection(
mitk::SliceNavigationController::Original );
SetDecorationProperties("Axial", GetDecorationColor(0), 0);
SetDecorationProperties("Sagittal", GetDecorationColor(1), 1);
SetDecorationProperties("Coronal", GetDecorationColor(2), 2);
SetDecorationProperties("3D", GetDecorationColor(3), 3);
//connect to the "time navigation controller": send time via sliceNavigationControllers
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget1->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget2->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget3->GetSliceNavigationController() , false);
m_TimeNavigationController->ConnectGeometryTimeEvent(
mitkWidget4->GetSliceNavigationController() , false);
mitkWidget1->GetSliceNavigationController()
->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()));
//reverse connection between sliceNavigationControllers and m_TimeNavigationController
mitkWidget1->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
mitkWidget2->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
mitkWidget3->GetSliceNavigationController()
->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
//mitkWidget4->GetSliceNavigationController()
// ->ConnectGeometryTimeEvent(m_TimeNavigationController, false);
m_MouseModeSwitcher = mitk::MouseModeSwitcher::New();
// setup the department logo rendering
m_LogoRendering = mitk::LogoOverlay::New();
mitk::BaseRenderer::Pointer renderer4 = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow());
m_LogoRendering->SetOpacity(0.5);
mitk::Point2D offset;
offset.Fill(0.03);
m_LogoRendering->SetOffsetVector(offset);
m_LogoRendering->SetRelativeSize(0.15);
m_LogoRendering->SetCornerPosition(1);
m_LogoRendering->SetLogoImagePath("DefaultLogo");
renderer4->GetOverlayManager()->AddOverlay(m_LogoRendering.GetPointer(),renderer4);
}
void QmitkStdMultiWidget::FillGradientBackgroundWithBlack()
{
//We have 4 widgets and ...
for(unsigned int i = 0; i < 4; ++i)
{
float black[3] = {0.0f, 0.0f, 0.0f};
m_GradientBackgroundColors[i] = std::make_pair(mitk::Color(black), mitk::Color(black));
}
}
std::pair<mitk::Color, mitk::Color> QmitkStdMultiWidget::GetGradientColors(unsigned int widgetNumber)
{
if(widgetNumber > 3)
{
MITK_ERROR << "Decoration color for unknown widget!";
float black[3] = { 0.0f, 0.0f, 0.0f};
return std::make_pair(mitk::Color(black), mitk::Color(black));
}
return m_GradientBackgroundColors[widgetNumber];
}
mitk::Color QmitkStdMultiWidget::GetDecorationColor(unsigned int widgetNumber)
{
//The implementation looks a bit messy here, but it avoids
//synchronization of the color of the geometry nodes and an
//internal member here.
//Default colors were chosen for decent visibitliy.
//Feel free to change your preferences in the workbench.
float tmp[3] = {0.0f,0.0f,0.0f};
switch (widgetNumber) {
case 0:
{
if(m_PlaneNode1.IsNotNull())
{
if(m_PlaneNode1->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode1->GetProperty("color"))->GetColor();
}
}
float red[3] = { 0.753f, 0.0f, 0.0f};//This is #C00000 in hex
return mitk::Color(red);
}
case 1:
{
if(m_PlaneNode2.IsNotNull())
{
if(m_PlaneNode2->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode2->GetProperty("color"))->GetColor();
}
}
float green[3] = { 0.0f, 0.69f, 0.0f};//This is #00B000 in hex
return mitk::Color(green);
}
case 2:
{
if(m_PlaneNode3.IsNotNull())
{
if(m_PlaneNode3->GetColor(tmp))
{
return dynamic_cast<mitk::ColorProperty*>(
m_PlaneNode3->GetProperty("color"))->GetColor();
}
}
float blue[3] = { 0.0, 0.502f, 1.0f};//This is #0080FF in hex
return mitk::Color(blue);
}
case 3:
{
return m_DecorationColorWidget4;
}
default:
MITK_ERROR << "Decoration color for unknown widget!";
float black[3] = { 0.0f, 0.0f, 0.0f};
return mitk::Color(black);
}
}
std::string QmitkStdMultiWidget::GetCornerAnnotationText(unsigned int widgetNumber)
{
if(widgetNumber > 3)
{
MITK_ERROR << "Decoration color for unknown widget!";
return std::string("");
}
return std::string(m_CornerAnnotations[widgetNumber]->GetText(0));
}
QmitkStdMultiWidget::~QmitkStdMultiWidget()
{
DisablePositionTracking();
//DisableNavigationControllerEventListening();
m_TimeNavigationController->Disconnect(mitkWidget1->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget2->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget3->GetSliceNavigationController());
m_TimeNavigationController->Disconnect(mitkWidget4->GetSliceNavigationController());
}
void QmitkStdMultiWidget::RemovePlanesFromDataStorage()
{
if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull())
{
if(m_DataStorage.IsNotNull())
{
m_DataStorage->Remove(m_PlaneNode1);
m_DataStorage->Remove(m_PlaneNode2);
m_DataStorage->Remove(m_PlaneNode3);
m_DataStorage->Remove(m_ParentNodeForGeometryPlanes);
}
}
}
void QmitkStdMultiWidget::AddPlanesToDataStorage()
{
if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull())
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->Add(m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode1, m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode2, m_ParentNodeForGeometryPlanes);
m_DataStorage->Add(m_PlaneNode3, m_ParentNodeForGeometryPlanes);
}
}
}
void QmitkStdMultiWidget::changeLayoutTo2DImagesUp()
{
SMW_INFO << "changing layout to 2D images up... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget Container into splitter top
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit1->addWidget( mitkWidget3Container );
//set SplitterSize for splitter top
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
//insert Widget Container into splitter bottom
m_SubSplit2->addWidget( mitkWidget4Container );
//set SplitterSize for splitter m_LayoutSplit
splitterSize.clear();
splitterSize.push_back(400);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
//Change Layout Name
m_Layout = LAYOUT_2D_IMAGES_UP;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2DImagesLeft()
{
SMW_INFO << "changing layout to 2D images left... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit1->addWidget( mitkWidget3Container );
//set splitterSize of SubSplit1
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_SubSplit2->addWidget( mitkWidget4Container );
//set splitterSize of Layout Split
splitterSize.clear();
splitterSize.push_back(400);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
//update Layout Name
m_Layout = LAYOUT_2D_IMAGES_LEFT;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::SetDecorationProperties( std::string text,
mitk::Color color, int widgetNumber)
{
if( widgetNumber > 3)
{
MITK_ERROR << "Unknown render window for annotation.";
return;
}
vtkRenderer* renderer = this->GetRenderWindow(widgetNumber)->GetRenderer()->GetVtkRenderer();
if(!renderer) return;
vtkSmartPointer<vtkCornerAnnotation> annotation = m_CornerAnnotations[widgetNumber];
annotation->SetText(0, text.c_str());
annotation->SetMaximumFontSize(12);
annotation->GetTextProperty()->SetColor( color[0],color[1],color[2] );
if(!renderer->HasViewProp(annotation))
{
renderer->AddViewProp(annotation);
}
vtkSmartPointer<vtkMitkRectangleProp> frame = m_RectangleProps[widgetNumber];
frame->SetColor(color[0],color[1],color[2]);
if(!renderer->HasViewProp(frame))
{
renderer->AddViewProp(frame);
}
}
void QmitkStdMultiWidget::SetCornerAnnotationVisibility(bool visibility)
{
for(int i = 0 ; i<4 ; ++i)
{
m_CornerAnnotations[i]->SetVisibility(visibility);
}
}
bool QmitkStdMultiWidget::IsCornerAnnotationVisible(void) const
{
return m_CornerAnnotations[0]->GetVisibility() > 0;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(unsigned int number)
{
switch (number) {
case 0:
return this->GetRenderWindow1();
case 1:
return this->GetRenderWindow2();
case 2:
return this->GetRenderWindow3();
case 3:
return this->GetRenderWindow4();
default:
MITK_ERROR << "Requested unknown render window";
break;
}
return NULL;
}
void QmitkStdMultiWidget::changeLayoutToDefault()
{
SMW_INFO << "changing layout to default... " << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget container into the splitters
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_SubSplit2->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show Widget if hidden
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_DEFAULT;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget2->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget3->LayoutDesignListChanged( LAYOUT_DEFAULT );
mitkWidget4->LayoutDesignListChanged( LAYOUT_DEFAULT );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToBig3D()
{
SMW_INFO << "changing layout to big 3D ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget4Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_BIG_3D;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget2->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget3->LayoutDesignListChanged( LAYOUT_BIG_3D );
mitkWidget4->LayoutDesignListChanged( LAYOUT_BIG_3D );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget1()
{
SMW_INFO << "changing layout to big Widget1 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget1Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
mitkWidget2->hide();
mitkWidget3->hide();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET1;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET1 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET1 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget2()
{
SMW_INFO << "changing layout to big Widget2 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget2Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET2;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET2 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET2 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToWidget3()
{
SMW_INFO << "changing layout to big Widget3 ..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//add widget Splitter to main Splitter
m_MainSplit->addWidget( mitkWidget3Container );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
mitkWidget4->hide();
m_Layout = LAYOUT_WIDGET3;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET3 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET3 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToRowWidget3And4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//add Widgets to splitter
m_LayoutSplit->addWidget( mitkWidget3Container );
m_LayoutSplit->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_ROW_WIDGET_3_AND_4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToColumnWidget3And4()
{
SMW_INFO << "changing layout to Widget3 and 4 in one Column..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//add Widgets to splitter
m_LayoutSplit->addWidget( mitkWidget3Container );
m_LayoutSplit->addWidget( mitkWidget4Container );
//set SplitterSize
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
mitkWidget1->hide();
mitkWidget2->hide();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_COLUMN_WIDGET_3_AND_4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToRowWidgetSmall3andBig4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
this->changeLayoutToRowWidget3And4();
m_Layout = LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4;
}
void QmitkStdMultiWidget::changeLayoutToSmallUpperWidget2Big3and4()
{
SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget into the splitters
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget3Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit2->setSizes( splitterSize );
splitterSize.clear();
splitterSize.push_back(500);
splitterSize.push_back(1000);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show Widget if hidden
mitkWidget1->hide();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
if ( mitkWidget3->isHidden() ) mitkWidget3->show();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget2->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget3->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
mitkWidget4->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2x2Dand3DWidget()
{
SMW_INFO << "changing layout to 2 x 2D and 3D Widget" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//add Widgets to splitter
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget2Container );
m_SubSplit2->addWidget( mitkWidget4Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2X_2D_AND_3D_WIDGET;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutToLeft2Dand3DRight2D()
{
SMW_INFO << "changing layout to 2D and 3D left, 2D right Widget" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//add Widgets to splitter
m_SubSplit1->addWidget( mitkWidget1Container );
m_SubSplit1->addWidget( mitkWidget4Container );
m_SubSplit2->addWidget( mitkWidget2Container );
//set Splitter Size
QList<int> splitterSize;
splitterSize.push_back(1000);
splitterSize.push_back(1000);
m_SubSplit1->setSizes( splitterSize );
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt and add to Layout
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
if ( mitkWidget2->isHidden() ) mitkWidget2->show();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET );
//update Alle Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::changeLayoutTo2DUpAnd3DDown()
{
SMW_INFO << "changing layout to 2D up and 3D down" << std::endl;
//Hide all Menu Widgets
this->HideAllWidgetToolbars();
delete QmitkStdMultiWidgetLayout ;
//create Main Layout
QmitkStdMultiWidgetLayout = new QHBoxLayout( this );
//Set Layout to widget
this->setLayout(QmitkStdMultiWidgetLayout);
//create main splitter
m_MainSplit = new QSplitter( this );
QmitkStdMultiWidgetLayout->addWidget( m_MainSplit );
//create m_LayoutSplit and add to the mainSplit
m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit );
m_MainSplit->addWidget( m_LayoutSplit );
//add LevelWindow Widget to mainSplitter
m_MainSplit->addWidget( levelWindowWidget );
//create m_SubSplit1 and m_SubSplit2
m_SubSplit1 = new QSplitter( m_LayoutSplit );
m_SubSplit2 = new QSplitter( m_LayoutSplit );
//insert Widget Container into splitter top
m_SubSplit1->addWidget( mitkWidget1Container );
//set SplitterSize for splitter top
QList<int> splitterSize;
//insert Widget Container into splitter bottom
m_SubSplit2->addWidget( mitkWidget4Container );
//set SplitterSize for splitter m_LayoutSplit
splitterSize.clear();
splitterSize.push_back(700);
splitterSize.push_back(700);
m_LayoutSplit->setSizes( splitterSize );
//show mainSplitt
m_MainSplit->show();
//show/hide Widgets
if ( mitkWidget1->isHidden() ) mitkWidget1->show();
mitkWidget2->hide();
mitkWidget3->hide();
if ( mitkWidget4->isHidden() ) mitkWidget4->show();
m_Layout = LAYOUT_2D_UP_AND_3D_DOWN;
//update Layout Design List
mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN );
//update all Widgets
this->UpdateAllWidgets();
}
void QmitkStdMultiWidget::SetDataStorage( mitk::DataStorage* ds )
{
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetDataStorage(ds);
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetDataStorage(ds);
m_DataStorage = ds;
}
void QmitkStdMultiWidget::Fit()
{
vtkSmartPointer<vtkRenderer> vtkrenderer;
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetVtkRenderer();
if ( vtkrenderer!= NULL )
vtkrenderer->ResetCamera();
mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetCameraController()->Fit();
mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetCameraController()->Fit();
int w = vtkObject::GetGlobalWarningDisplay();
vtkObject::GlobalWarningDisplayOff();
vtkObject::SetGlobalWarningDisplay(w);
}
void QmitkStdMultiWidget::InitPositionTracking()
{
// TODO POSITIONTRACKER
}
void QmitkStdMultiWidget::AddDisplayPlaneSubTree()
{
// add the displayed planes of the multiwidget to a node to which the subtree
// @a planesSubTree points ...
mitk::PlaneGeometryDataMapper2D::Pointer mapper;
// ... of widget 1
mitk::BaseRenderer* renderer1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow());
m_PlaneNode1 = renderer1->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode1->SetProperty("name", mitk::StringProperty::New(std::string(renderer1->GetName()) + ".plane"));
m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
// ... of widget 2
mitk::BaseRenderer* renderer2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow());
m_PlaneNode2 = renderer2->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode2->SetProperty("name", mitk::StringProperty::New(std::string(renderer2->GetName()) + ".plane"));
m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
// ... of widget 3
mitk::BaseRenderer* renderer3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow());
m_PlaneNode3 = renderer3->GetCurrentWorldPlaneGeometryNode();
m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true));
m_PlaneNode3->SetProperty("name", mitk::StringProperty::New(std::string(renderer3->GetName()) + ".plane"));
m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true));
mapper = mitk::PlaneGeometryDataMapper2D::New();
m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper);
m_ParentNodeForGeometryPlanes = mitk::DataNode::New();
m_ParentNodeForGeometryPlanes->SetProperty("name", mitk::StringProperty::New("Widgets"));
m_ParentNodeForGeometryPlanes->SetProperty("helper object", mitk::BoolProperty::New(true));
}
mitk::SliceNavigationController* QmitkStdMultiWidget::GetTimeNavigationController()
{
return m_TimeNavigationController;
}
void QmitkStdMultiWidget::EnableStandardLevelWindow()
{
levelWindowWidget->disconnect(this);
levelWindowWidget->SetDataStorage(mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetDataStorage());
levelWindowWidget->show();
}
void QmitkStdMultiWidget::DisableStandardLevelWindow()
{
levelWindowWidget->disconnect(this);
levelWindowWidget->hide();
}
// CAUTION: Legacy code for enabling Qt-signal-controlled view initialization.
// Use RenderingManager::InitializeViews() instead.
bool QmitkStdMultiWidget::InitializeStandardViews( const mitk::Geometry3D * geometry )
{
return m_RenderingManager->InitializeViews( geometry );
}
void QmitkStdMultiWidget::RequestUpdate()
{
m_RenderingManager->RequestUpdate(mitkWidget1->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget2->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget3->GetRenderWindow());
m_RenderingManager->RequestUpdate(mitkWidget4->GetRenderWindow());
}
void QmitkStdMultiWidget::ForceImmediateUpdate()
{
m_RenderingManager->ForceImmediateUpdate(mitkWidget1->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget2->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget3->GetRenderWindow());
m_RenderingManager->ForceImmediateUpdate(mitkWidget4->GetRenderWindow());
}
void QmitkStdMultiWidget::wheelEvent( QWheelEvent * e )
{
emit WheelMoved( e );
}
void QmitkStdMultiWidget::mousePressEvent(QMouseEvent * e)
{
}
void QmitkStdMultiWidget::moveEvent( QMoveEvent* e )
{
QWidget::moveEvent( e );
// it is necessary to readjust the position of the overlays as the StdMultiWidget has moved
// unfortunately it's not done by QmitkRenderWindow::moveEvent -> must be done here
emit Moved();
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow1() const
{
return mitkWidget1;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow2() const
{
return mitkWidget2;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow3() const
{
return mitkWidget3;
}
QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow4() const
{
return mitkWidget4;
}
const mitk::Point3D QmitkStdMultiWidget::GetCrossPosition() const
{
const mitk::PlaneGeometry *plane1 =
mitkWidget1->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane2 =
mitkWidget2->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane3 =
mitkWidget3->GetSliceNavigationController()->GetCurrentPlaneGeometry();
mitk::Line3D line;
if ( (plane1 != NULL) && (plane2 != NULL)
&& (plane1->IntersectionLine( plane2, line )) )
{
mitk::Point3D point;
if ( (plane3 != NULL)
&& (plane3->IntersectionPoint( line, point )) )
{
return point;
}
}
// TODO BUG POSITIONTRACKER;
mitk::Point3D p;
return p;
//return m_LastLeftClickPositionSupplier->GetCurrentPoint();
}
void QmitkStdMultiWidget::EnablePositionTracking()
{
}
void QmitkStdMultiWidget::DisablePositionTracking()
{
}
void QmitkStdMultiWidget::EnsureDisplayContainsPoint(
mitk::BaseRenderer* renderer, const mitk::Point3D& p)
{
mitk::Point2D pointOnDisplay;
renderer->WorldToDisplay(p,pointOnDisplay);
if(pointOnDisplay[0] < renderer->GetVtkRenderer()->GetOrigin()[0]
|| pointOnDisplay[1] < renderer->GetVtkRenderer()->GetOrigin()[1]
|| pointOnDisplay[0] > renderer->GetVtkRenderer()->GetOrigin()[0]+renderer->GetViewportSize()[0]
|| pointOnDisplay[1] > renderer->GetVtkRenderer()->GetOrigin()[1]+renderer->GetViewportSize()[1])
{
mitk::Point2D pointOnPlane;
renderer->GetCurrentWorldPlaneGeometry()->Map(p,pointOnPlane);
renderer->GetCameraController()->MoveCameraToPoint(pointOnPlane);
}
}
void QmitkStdMultiWidget::MoveCrossToPosition(const mitk::Point3D& newPosition)
{
mitkWidget1->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
mitkWidget2->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
mitkWidget3->GetSliceNavigationController()->SelectSliceByPoint(newPosition);
m_RenderingManager->RequestUpdateAll();
}
void QmitkStdMultiWidget::HandleCrosshairPositionEvent()
{
if(!m_PendingCrosshairPositionEvent)
{
m_PendingCrosshairPositionEvent=true;
QTimer::singleShot(0,this,SLOT( HandleCrosshairPositionEventDelayed() ) );
}
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetTopLayerNode(mitk::DataStorage::SetOfObjects::ConstPointer nodes)
{
mitk::Point3D crosshairPos = this->GetCrossPosition();
mitk::DataNode::Pointer node;
int maxlayer = -32768;
if(nodes.IsNotNull())
{
mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer();
// find node with largest layer, that is the node shown on top in the render window
for (unsigned int x = 0; x < nodes->size(); x++)
{
if ( (nodes->at(x)->GetData()->GetGeometry() != NULL) &&
nodes->at(x)->GetData()->GetGeometry()->IsInside(crosshairPos) )
{
int layer = 0;
if(!(nodes->at(x)->GetIntProperty("layer", layer))) continue;
if(layer > maxlayer)
{
if( static_cast<mitk::DataNode::Pointer>(nodes->at(x))->IsVisible( baseRenderer ) )
{
node = nodes->at(x);
maxlayer = layer;
}
}
}
}
}
return node;
}
void QmitkStdMultiWidget::HandleCrosshairPositionEventDelayed()
{
m_PendingCrosshairPositionEvent = false;
// find image with highest layer
mitk::TNodePredicateDataType<mitk::Image>::Pointer isImageData = mitk::TNodePredicateDataType<mitk::Image>::New();
mitk::DataStorage::SetOfObjects::ConstPointer nodes = this->m_DataStorage->GetSubset(isImageData).GetPointer();
mitk::DataNode::Pointer node;
mitk::DataNode::Pointer topSourceNode;
mitk::Image::Pointer image;
bool isBinary = false;
node = this->GetTopLayerNode(nodes);
int component = 0;
if(node.IsNotNull())
{
node->GetBoolProperty("binary",isBinary);
if(isBinary)
{
mitk::DataStorage::SetOfObjects::ConstPointer sourcenodes = m_DataStorage->GetSources(node, NULL, true);
if(!sourcenodes->empty())
{
topSourceNode = this->GetTopLayerNode(sourcenodes);
}
if(topSourceNode.IsNotNull())
{
image = dynamic_cast<mitk::Image*>(topSourceNode->GetData());
topSourceNode->GetIntProperty("Image.Displayed Component", component);
}
else
{
image = dynamic_cast<mitk::Image*>(node->GetData());
node->GetIntProperty("Image.Displayed Component", component);
}
}
else
{
image = dynamic_cast<mitk::Image*>(node->GetData());
node->GetIntProperty("Image.Displayed Component", component);
}
}
mitk::Point3D crosshairPos = this->GetCrossPosition();
std::string statusText;
std::stringstream stream;
itk::Index<3> p;
mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer();
unsigned int timestep = baseRenderer->GetTimeStep();
if(image.IsNotNull() && (image->GetTimeSteps() > timestep ))
{
image->GetGeometry()->WorldToIndex(crosshairPos, p);
stream.precision(2);
stream<<"Position: <" << std::fixed <<crosshairPos[0] << ", " << std::fixed << crosshairPos[1] << ", " << std::fixed << crosshairPos[2] << "> mm";
stream<<"; Index: <"<<p[0] << ", " << p[1] << ", " << p[2] << "> ";
mitk::ScalarType pixelValue;
mitkPixelTypeMultiplex5(
mitk::FastSinglePixelAccess,
image->GetChannelDescriptor().GetPixelType(),
image,
image->GetVolumeData(baseRenderer->GetTimeStep()),
p,
pixelValue,
component);
if (fabs(pixelValue)>1000000 || fabs(pixelValue) < 0.01)
{
stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< std::scientific<< pixelValue <<" ";
}
else
{
stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< pixelValue <<" ";
}
}
else
{
stream << "No image information at this position!";
}
statusText = stream.str();
mitk::StatusBar::GetInstance()->DisplayGreyValueText(statusText.c_str());
}
int QmitkStdMultiWidget::GetLayout() const
{
return m_Layout;
}
bool QmitkStdMultiWidget::GetGradientBackgroundFlag() const
{
return m_GradientBackgroundFlag;
}
void QmitkStdMultiWidget::EnableGradientBackground()
{
// gradient background is by default only in widget 4, otherwise
// interferences between 2D rendering and VTK rendering may occur.
for(unsigned int i = 0; i < 4; ++i)
{
GetRenderWindow(i)->GetRenderer()->GetVtkRenderer()->GradientBackgroundOn();
}
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::DisableGradientBackground()
{
for(unsigned int i = 0; i < 4; ++i)
{
GetRenderWindow(i)->GetRenderer()->GetVtkRenderer()->GradientBackgroundOff();
}
m_GradientBackgroundFlag = false;
}
void QmitkStdMultiWidget::EnableDepartmentLogo()
{
m_LogoRendering->SetVisibility(true);
RequestUpdate();
}
void QmitkStdMultiWidget::DisableDepartmentLogo()
{
m_LogoRendering->SetVisibility(false);
RequestUpdate();
}
bool QmitkStdMultiWidget::IsDepartmentLogoEnabled() const
{
return m_LogoRendering->IsVisible(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()));
}
void QmitkStdMultiWidget::SetWidgetPlaneVisibility(const char* widgetName, bool visible, mitk::BaseRenderer *renderer)
{
if (m_DataStorage.IsNotNull())
{
mitk::DataNode* n = m_DataStorage->GetNamedNode(widgetName);
if (n != NULL)
n->SetVisibility(visible, renderer);
}
}
void QmitkStdMultiWidget::SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer)
{
if (m_PlaneNode1.IsNotNull())
{
m_PlaneNode1->SetVisibility(visible, renderer);
}
if (m_PlaneNode2.IsNotNull())
{
m_PlaneNode2->SetVisibility(visible, renderer);
}
if (m_PlaneNode3.IsNotNull())
{
m_PlaneNode3->SetVisibility(visible, renderer);
}
m_RenderingManager->RequestUpdateAll();
}
void QmitkStdMultiWidget::SetWidgetPlanesLocked(bool locked)
{
//do your job and lock or unlock slices.
GetRenderWindow1()->GetSliceNavigationController()->SetSliceLocked(locked);
GetRenderWindow2()->GetSliceNavigationController()->SetSliceLocked(locked);
GetRenderWindow3()->GetSliceNavigationController()->SetSliceLocked(locked);
}
void QmitkStdMultiWidget::SetWidgetPlanesRotationLocked(bool locked)
{
//do your job and lock or unlock slices.
GetRenderWindow1()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
GetRenderWindow2()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
GetRenderWindow3()->GetSliceNavigationController()->SetSliceRotationLocked(locked);
}
void QmitkStdMultiWidget::SetWidgetPlanesRotationLinked( bool link )
{
emit WidgetPlanesRotationLinked( link );
}
void QmitkStdMultiWidget::SetWidgetPlaneMode( int userMode )
{
MITK_DEBUG << "Changing crosshair mode to " << userMode;
emit WidgetNotifyNewCrossHairMode( userMode );
// Convert user interface mode to actual mode
{
switch(userMode)
{
case 0:
m_MouseModeSwitcher->SetInteractionScheme(mitk::MouseModeSwitcher::InteractionScheme::MITK);
break;
case 1:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::ROTATION);
break;
case 2:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::ROTATIONLINKED);
break;
case 3:
m_MouseModeSwitcher->SetInteractionScheme( mitk::MouseModeSwitcher::InteractionScheme::SWIVEL);
break;
}
}
}
void QmitkStdMultiWidget::SetGradientBackgroundColorForRenderWindow( const mitk::Color & upper, const mitk::Color & lower, unsigned int widgetNumber )
{
if(widgetNumber > 3)
{
MITK_ERROR << "Gradientbackground for unknown widget!";
return;
}
m_GradientBackgroundColors[widgetNumber].first = upper;
m_GradientBackgroundColors[widgetNumber].second = lower;
vtkRenderer* renderer = GetRenderWindow(widgetNumber)->GetRenderer()->GetVtkRenderer();
renderer->SetBackground2(upper[0], upper[1], upper[2]);
renderer->SetBackground(lower[0], lower[1], lower[2]);
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::SetGradientBackgroundColors( const mitk::Color & upper, const mitk::Color & lower )
{
for(unsigned int i = 0; i < 4; ++i)
{
vtkRenderer* renderer = GetRenderWindow(i)->GetRenderer()->GetVtkRenderer();
renderer->SetBackground2(upper[0], upper[1], upper[2]);
renderer->SetBackground(lower[0], lower[1], lower[2]);
}
m_GradientBackgroundFlag = true;
}
void QmitkStdMultiWidget::SetDepartmentLogoPath( const char * path )
{
m_LogoRendering->SetLogoImagePath(path);
mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow());
m_LogoRendering->Update(renderer);
RequestUpdate();
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToSlicing( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_SLICING );
}
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToRotation( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_ROTATION );
}
}
void QmitkStdMultiWidget::SetWidgetPlaneModeToSwivel( bool activate )
{
if ( activate )
{
this->SetWidgetPlaneMode( PLANE_MODE_SWIVEL );
}
}
void QmitkStdMultiWidget::OnLayoutDesignChanged( int layoutDesignIndex )
{
switch( layoutDesignIndex )
{
case LAYOUT_DEFAULT:
{
this->changeLayoutToDefault();
break;
}
case LAYOUT_2D_IMAGES_UP:
{
this->changeLayoutTo2DImagesUp();
break;
}
case LAYOUT_2D_IMAGES_LEFT:
{
this->changeLayoutTo2DImagesLeft();
break;
}
case LAYOUT_BIG_3D:
{
this->changeLayoutToBig3D();
break;
}
case LAYOUT_WIDGET1:
{
this->changeLayoutToWidget1();
break;
}
case LAYOUT_WIDGET2:
{
this->changeLayoutToWidget2();
break;
}
case LAYOUT_WIDGET3:
{
this->changeLayoutToWidget3();
break;
}
case LAYOUT_2X_2D_AND_3D_WIDGET:
{
this->changeLayoutTo2x2Dand3DWidget();
break;
}
case LAYOUT_ROW_WIDGET_3_AND_4:
{
this->changeLayoutToRowWidget3And4();
break;
}
case LAYOUT_COLUMN_WIDGET_3_AND_4:
{
this->changeLayoutToColumnWidget3And4();
break;
}
case LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4:
{
this->changeLayoutToRowWidgetSmall3andBig4();
break;
}
case LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4:
{
this->changeLayoutToSmallUpperWidget2Big3and4();
break;
}
case LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET:
{
this->changeLayoutToLeft2Dand3DRight2D();
break;
}
};
}
void QmitkStdMultiWidget::UpdateAllWidgets()
{
mitkWidget1->resize( mitkWidget1Container->frameSize().width()-1, mitkWidget1Container->frameSize().height() );
mitkWidget1->resize( mitkWidget1Container->frameSize().width(), mitkWidget1Container->frameSize().height() );
mitkWidget2->resize( mitkWidget2Container->frameSize().width()-1, mitkWidget2Container->frameSize().height() );
mitkWidget2->resize( mitkWidget2Container->frameSize().width(), mitkWidget2Container->frameSize().height() );
mitkWidget3->resize( mitkWidget3Container->frameSize().width()-1, mitkWidget3Container->frameSize().height() );
mitkWidget3->resize( mitkWidget3Container->frameSize().width(), mitkWidget3Container->frameSize().height() );
mitkWidget4->resize( mitkWidget4Container->frameSize().width()-1, mitkWidget4Container->frameSize().height() );
mitkWidget4->resize( mitkWidget4Container->frameSize().width(), mitkWidget4Container->frameSize().height() );
}
void QmitkStdMultiWidget::HideAllWidgetToolbars()
{
mitkWidget1->HideRenderWindowMenu();
mitkWidget2->HideRenderWindowMenu();
mitkWidget3->HideRenderWindowMenu();
mitkWidget4->HideRenderWindowMenu();
}
void QmitkStdMultiWidget::ActivateMenuWidget( bool state )
{
mitkWidget1->ActivateMenuWidget( state, this );
mitkWidget2->ActivateMenuWidget( state, this );
mitkWidget3->ActivateMenuWidget( state, this );
mitkWidget4->ActivateMenuWidget( state, this );
}
bool QmitkStdMultiWidget::IsMenuWidgetEnabled() const
{
return mitkWidget1->GetActivateMenuWidgetFlag();
}
void QmitkStdMultiWidget::SetDecorationColor(unsigned int widgetNumber, mitk::Color color)
{
switch (widgetNumber) {
case 0:
if(m_PlaneNode1.IsNotNull())
{
m_PlaneNode1->SetColor(color);
}
break;
case 1:
if(m_PlaneNode2.IsNotNull())
{
m_PlaneNode2->SetColor(color);
}
break;
case 2:
if(m_PlaneNode3.IsNotNull())
{
m_PlaneNode3->SetColor(color);
}
break;
case 3:
m_DecorationColorWidget4 = color;
break;
default:
MITK_ERROR << "Decoration color for unknown widget!";
break;
}
}
void QmitkStdMultiWidget::ResetCrosshair()
{
if (m_DataStorage.IsNotNull())
{
m_RenderingManager->InitializeViewsByBoundingObjects(m_DataStorage);
//m_RenderingManager->InitializeViews( m_DataStorage->ComputeVisibleBoundingGeometry3D() );
// reset interactor to normal slicing
this->SetWidgetPlaneMode(PLANE_MODE_SLICING);
}
}
void QmitkStdMultiWidget::EnableColoredRectangles()
{
m_RectangleProps[0]->SetVisibility(1);
m_RectangleProps[1]->SetVisibility(1);
m_RectangleProps[2]->SetVisibility(1);
m_RectangleProps[3]->SetVisibility(1);
}
void QmitkStdMultiWidget::DisableColoredRectangles()
{
m_RectangleProps[0]->SetVisibility(0);
m_RectangleProps[1]->SetVisibility(0);
m_RectangleProps[2]->SetVisibility(0);
m_RectangleProps[3]->SetVisibility(0);
}
bool QmitkStdMultiWidget::IsColoredRectanglesEnabled() const
{
return m_RectangleProps[0]->GetVisibility()>0;
}
mitk::MouseModeSwitcher* QmitkStdMultiWidget::GetMouseModeSwitcher()
{
return m_MouseModeSwitcher;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane1()
{
return this->m_PlaneNode1;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane2()
{
return this->m_PlaneNode2;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane3()
{
return this->m_PlaneNode3;
}
mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane(int id)
{
switch(id)
{
case 1: return this->m_PlaneNode1;
break;
case 2: return this->m_PlaneNode2;
break;
case 3: return this->m_PlaneNode3;
break;
default: return NULL;
}
}
| bsd-3-clause |
wayfinder/Wayfinder-CppCore-v2 | cpp/Targets/MapLibNG/Shared/include/HttpClientConnection.h | 7143 | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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.
*/
#ifndef HTTP_CLIENT_CONNECTUION_H
#define HTTP_CLIENT_CONNECTUION_H
#include "config.h"
#include "MC2SimpleString.h"
#include <list>
#include "TCPClientConnection.h"
#include "TCPConnectionHandler.h"
class HttpClientConnectionListener;
class SharedBuffer;
class TCPConnectionHandler;
class HttpClientConnectionReader;
class HttpClientConnectionWriter;
/**
* Class that handles a HttpConnection to one host and port.
*/
class HttpClientConnection : public TCPClientConnection {
public:
friend class HttpClientConnectionReader;
/**
* State of the
*/
enum state_t {
NOT_CONNECTED = 0,
CONNECTED = 1,
} m_state;
/**
* Creates a new HttpClientConnection to the supplied
* host and port.
*/
HttpClientConnection(const char* host, unsigned int port,
HttpClientConnectionListener* listener,
TCPConnectionHandler* connectionHandler);
/**
* Sets listener.
*/
void setListener(HttpClientConnectionListener* listener);
/**
* Deletes the data associated with the connection.
* Closes connection.
*/
virtual ~HttpClientConnection();
/**
* Sends a get-request for the supplied filespec, if there
* is enough place in the queue.
* @param filespec1 File from server.
* @param filespec2 Will be concatenated to filespec1 if not NULL.
* @param urlParams [Optional] The url parameters
* (for instance containing the session).
* Should begin with a "?".
* @return A positive number is a request id and a negative number
* means that the queue is full.
*/
int get(const char* filespec1,
const char* filespec2 = NULL,
const char* filespec3 = NULL,
const char* urlParams = "");
/**
* Sends a post-request for the supplied filespec.
* @param urlParams [Optional] The url parameters
* (for instance containing the session).
* Should begin with a "?".
*/
int post(const char* filespecPart1,
const char* filespecPart2,
const char* mimeType,
const SharedBuffer& body,
const char* urlParams = "");
/**
* To be called when the connection is established or has
* failed.
*/
void connectDone(status_t status);
/**
* To be called when a read is done.
*
*/
void readDone(status_t status,
const byte* bytes,
int nbrBytes);
/**
* Informs the ClientConnection that the last write is completed.
*/
void writeDone(status_t status);
/**
* Informs the ClientConnection that the connection is closed.
*/
void connectionClosed(status_t status);
/**
* Informs the HttpClientConnection that the timeout
* with id timerID has expired.
*/
void timerExpired(int timerID);
/**
* Returns the number of requests to send.
*/
int getNbrSent() const { return m_waitingFor.size(); }
/**
* Writes a new request
*/
void oneRequestComplete();
/**
* Returns the number of the current request we are
* waiting for.
*/
int getCurrentRequestNbr() const;
/**
* Sets hostname and port.
*/
void setHostAndPort(const char* host, unsigned int port);
/**
*
*/
void forceDisconnect();
protected:
/**
* Tries to write a request to the socket.
*/
void writeNextRequest();
/**
* Tries to read a request from the socket.
*/
void readNextRequest();
private:
/**
* Hostname.
*/
MC2SimpleString m_host;
/**
* Number of the port to use for the connection.
*/
unsigned int m_port;
/**
* User agent string to send to the server.
*/
MC2SimpleString m_userAgent;
/**
* Prefix all the url:s with this string.
* To be used when using proxy.
*/
MC2SimpleString m_urlPrefix;
/**
* Maximum number of requests to have at a certain time.
*/
int m_maxNbrGet;
/**
* Type of list to keep the requests in.
*/
typedef std::list<std::pair<int, SharedBuffer*> > requestList_t;
/**
* The outgoing requests.
*/
requestList_t m_requestsToSend;
/**
* The requests we are waiting for.
*/
requestList_t m_waitingFor;
/**
* List containing zero or one requests that are currently
* written.
*/
requestList_t m_currentlyWriting;
/**
* Next id for the requests.
*/
int m_nextID;
/**
* The connection handler.
*/
TCPConnectionHandler* m_connHandler;
/**
* True if the connection is connecting.
*/
bool m_connecting;
/**
* True if there is a pending read.
*/
bool m_reading;
/**
* True if there is a pending write.
*/
bool m_writing;
/**
* The number of written requests for which
* we haven't got any answers yet.
*/
int m_nbrWaiting;
/**
* The number of failed attempts in a row.
*/
int m_nbrRetries;
/**
* Handles all reads from the connection.
*/
HttpClientConnectionReader* m_connReader;
/**
* The listener.
*/
HttpClientConnectionListener* m_listener;
/**
* The maximum number of retries.
*/
const int m_maxNbrRetries;
/**
* Header lines that should only be used when using proxy.
*/
const char* m_proxyHeaderLines;
};
#endif
| bsd-3-clause |
awebc/web_yi | yunsong/order/controllers/pay/AlipayController.php | 5332 | <?php
/**
* Created by PhpStorm.
* User: yunsong
* Date: 16-10-10
* Time: 下午3:12
*/
namespace yunsong\order\controllers\pay;
use izyue\alipay\AlipayConfig;
use izyue\alipay\AlipayNotify;
use izyue\alipay\AlipaySubmit;
use Yii;
use yii\web\Controller;
class AlipayController extends Controller
{
public function beforeAction($action)
{
if ('notify' == $action->id) {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionIndex($orderId)
{
/**************************请求参数**************************/
//服务器异步通知页面路径
$notify_url = Yii::$app->urlManager->createAbsoluteUrl(['/order/pay/alipay/notify']);
//需http://格式的完整路径,不允许加?id=123这类自定义参数
//付款账号
$email = '[email protected]';
// $email = $_POST['WIDemail'];
//必填
//付款账户名
$account_name = "北京纽斯洛网络科技有限公司";
//必填,个人支付宝账号是真实姓名公司支付宝账号是公司名称
//付款当天日期
$pay_date = date("Y-m-d");
//必填,格式:年[4位]月[2位]日[2位],如:20100801
//批次号
$batch_no = date("YmdHis");
//必填,格式:当天日期[8位]+序列号[3至16位],如:201008010000001
//付款总金额
$batch_fee = 0.02;
//必填,即参数detail_data的值中所有金额的总和
//付款笔数
$batch_num = 2;
//必填,即参数detail_data的值中,“|”字符出现的数量加1,最大支持1000笔(即“|”字符出现的数量999个)
//付款详细数据
$detail_data = "流水号1^收款方帐号1^真实姓名^0.01^测试付款1,这是备注|流水号2^收款方帐号2^真实姓名^0.01^测试付款2,这是备注";
//必填,格式:流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....
/************************************************************/
$alipayConfig = (new AlipayConfig())->getAlipayConfig();
//构造要请求的参数数组,无需改动
$parameter = array(
"service" => "batch_trans_notify",
"partner" => trim($alipayConfig['partner']),
"notify_url" => $notify_url,
"email" => trim($alipayConfig['seller_email']),
"account_name" => $account_name,
"pay_date" => $pay_date,
"batch_no" => $batch_no,
"batch_fee" => $batch_fee,
"batch_num" => $batch_num,
"detail_data" => $detail_data,
"_input_charset" => trim(strtolower($alipayConfig['input_charset']))
);
//建立请求
$alipaySubmit = new AlipaySubmit($alipayConfig);
$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
return $html_text;
}
public function actionNotify()
{
$alipayConfig = (new AlipayConfig())->getAlipayConfig();
// Yii::getLogger()->log("alipay Notify Start", Logger::LEVEL_ERROR);
//
// Yii::getLogger()->log("↓↓↓↓↓↓↓↓↓↓alipayConfig↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓", Logger::LEVEL_ERROR);
// Yii::getLogger()->log(print_r($alipayConfig, true), Logger::LEVEL_ERROR);
$notify = new AlipayNotify($alipayConfig);
if ($notify->verifyNotify()) {
Yii::trace('verify Notify success');
//通知时间 2009-08-12 11:08:32
$notify_time = Yii::$app->request->post('notify_time');
//通知类型 batch_trans_notify
$notifyType = Yii::$app->request->post('notify_type');
//通知校验ID 70fec0c2730b27528665af4517c27b95
$notifyId = Yii::$app->request->post('notify_id');
//签名方式 MD5
$signType = Yii::$app->request->post('sign_type');
//签名 e7d51bf34a1317714d93fab13bbeab73
$sign = Yii::$app->request->post('sign');
//批次号
$batchNo = Yii::$app->request->post('batch_no');
//付款账号ID
$payUserId = Yii::$app->request->post('pay_user_id');
//付款账号姓名
$payUserName = Yii::$app->request->post('pay_user_name');
//付款账号
$payAccountNo = Yii::$app->request->post('pay_account_no');
//批量付款数据中转账成功的详细信息
$successDetails = Yii::$app->request->post('success_details');
//批量付款数据中转账失败的详细信息
$failDetails = Yii::$app->request->post('fail_details');
//请在这里加上商户的业务逻辑程序代
//判断是否在商户网站中已经做过了这次通知返回的处理
//如果没有做过处理,那么执行商户的业务程序
//如果有做过处理,那么不执行商户的业务程序
return "success";
} else {
Yii::trace('verify Notify failed');
return "fail";
}
}
} | bsd-3-clause |
marrocamp/nasa-VICAR | vos/java/jpl/mipl/jade/jadis/package.html | 666 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>JADE Component Library</title>
<meta name="Generator" content="Cocoa HTML Writer">
<meta name="CocoaVersion" content="824.47">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times}
</style>
</head>
<body>
<p class="p1">Package containing all of the user-accessible JADIS components. Any pieces of JADIS that normal user code will use should be in this package.</p>
</body>
</html>
| bsd-3-clause |
erdbehrmund/blogyr | db/migrate/20130117003258_create_post_category_join_table.rb | 201 | class CreatePostCategoryJoinTable < ActiveRecord::Migration
def change
create_table :categories_posts, :id => false do |t|
t.integer :post_id
t.integer :category_id
end
end
end
| bsd-3-clause |
highweb-project/highweb-webcl-html5spec | media/mojo/common/media_type_converters.cc | 29089 | // Copyright 2014 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 "media/mojo/common/media_type_converters.h"
#include <stddef.h>
#include <stdint.h>
#include "base/numerics/safe_conversions.h"
#include "media/base/audio_buffer.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/buffering_state.h"
#include "media/base/cdm_config.h"
#include "media/base/cdm_key_information.h"
#include "media/base/decoder_buffer.h"
#include "media/base/decrypt_config.h"
#include "media/base/decryptor.h"
#include "media/base/demuxer_stream.h"
#include "media/base/media_keys.h"
#include "media/base/video_decoder_config.h"
#include "media/base/video_frame.h"
#include "media/mojo/common/mojo_shared_buffer_video_frame.h"
#include "media/mojo/interfaces/demuxer_stream.mojom.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/public/cpp/system/buffer.h"
namespace mojo {
#define ASSERT_ENUM_EQ(media_enum, media_prefix, mojo_prefix, value) \
static_assert(media::media_prefix##value == \
static_cast<media::media_enum>( \
media::interfaces::media_enum::mojo_prefix##value), \
"Mismatched enum: " #media_prefix #value " != " #media_enum \
"::" #mojo_prefix #value)
#define ASSERT_ENUM_EQ_RAW(media_enum, media_enum_value, mojo_enum_value) \
static_assert( \
media::media_enum_value == \
static_cast<media::media_enum>(media::interfaces::mojo_enum_value), \
"Mismatched enum: " #media_enum_value " != " #mojo_enum_value)
// BufferingState.
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, , HAVE_NOTHING);
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, , HAVE_ENOUGH);
// AudioCodec.
ASSERT_ENUM_EQ_RAW(AudioCodec, kUnknownAudioCodec, AudioCodec::UNKNOWN);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , MP3);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , Vorbis);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , FLAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AMR_NB);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_MULAW);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , GSM_MS);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_S16BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_S24BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , Opus);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , EAC3);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , PCM_ALAW);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , ALAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, , AC3);
ASSERT_ENUM_EQ_RAW(AudioCodec, kAudioCodecMax, AudioCodec::MAX);
// ChannelLayout.
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _NONE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _UNSUPPORTED);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _MONO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _SURROUND);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2_2);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _QUAD);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_0_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _5_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1_WIDE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO_DOWNMIX);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _2POINT1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _3_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _HEXAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _6_1_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _7_1_WIDE_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _OCTAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _DISCRETE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _STEREO_AND_KEYBOARD_MIC);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _4_1_QUAD_SIDE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, k, _MAX);
// SampleFormat.
ASSERT_ENUM_EQ_RAW(SampleFormat, kUnknownSampleFormat, SampleFormat::UNKNOWN);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , U8);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , S16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , S32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , F32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , PlanarS16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , PlanarF32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, , Max);
// DemuxerStream Type. Note: Mojo DemuxerStream's don't have the TEXT type.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::UNKNOWN,
DemuxerStream::Type::UNKNOWN);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::AUDIO,
DemuxerStream::Type::AUDIO);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
DemuxerStream::VIDEO,
DemuxerStream::Type::VIDEO);
static_assert(media::DemuxerStream::NUM_TYPES ==
static_cast<media::DemuxerStream::Type>(
static_cast<int>(
media::interfaces::DemuxerStream::Type::LAST_TYPE) +
2),
"Mismatched enum: media::DemuxerStream::NUM_TYPES != "
"media::interfaces::DemuxerStream::Type::LAST_TYPE + 2");
// DemuxerStream Status.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kOk,
DemuxerStream::Status::OK);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kAborted,
DemuxerStream::Status::ABORTED);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
DemuxerStream::kConfigChanged,
DemuxerStream::Status::CONFIG_CHANGED);
// VideoFormat.
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_UNKNOWN,
VideoFormat::UNKNOWN);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_I420, VideoFormat::I420);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV12, VideoFormat::YV12);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV16, VideoFormat::YV16);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV12A, VideoFormat::YV12A);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YV24, VideoFormat::YV24);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_NV12, VideoFormat::NV12);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_NV21, VideoFormat::NV21);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_UYVY, VideoFormat::UYVY);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_YUY2, VideoFormat::YUY2);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_ARGB, VideoFormat::ARGB);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_XRGB, VideoFormat::XRGB);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_RGB24, VideoFormat::RGB24);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_RGB32, VideoFormat::RGB32);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MJPEG, VideoFormat::MJPEG);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MT21, VideoFormat::MT21);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV420P9,
VideoFormat::YUV420P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV422P9,
VideoFormat::YUV422P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV444P9,
VideoFormat::YUV444P9);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV420P10,
VideoFormat::YUV420P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV422P10,
VideoFormat::YUV422P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat,
PIXEL_FORMAT_YUV444P10,
VideoFormat::YUV444P10);
ASSERT_ENUM_EQ_RAW(VideoPixelFormat, PIXEL_FORMAT_MAX, VideoFormat::FORMAT_MAX);
// ColorSpace.
ASSERT_ENUM_EQ_RAW(ColorSpace,
COLOR_SPACE_UNSPECIFIED,
ColorSpace::UNSPECIFIED);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_JPEG, ColorSpace::JPEG);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_HD_REC709, ColorSpace::HD_REC709);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_SD_REC601, ColorSpace::SD_REC601);
ASSERT_ENUM_EQ_RAW(ColorSpace, COLOR_SPACE_MAX, ColorSpace::MAX);
// VideoCodec
ASSERT_ENUM_EQ_RAW(VideoCodec, kUnknownVideoCodec, VideoCodec::UNKNOWN);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , H264);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , HEVC);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VC1);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , MPEG2);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , MPEG4);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , Theora);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VP8);
ASSERT_ENUM_EQ(VideoCodec, kCodec, , VP9);
ASSERT_ENUM_EQ_RAW(VideoCodec, kVideoCodecMax, VideoCodec::Max);
// VideoCodecProfile
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_UNKNOWN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_BASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MAIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_EXTENDED);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH10PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH422PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_HIGH444PREDICTIVEPROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_SCALABLEBASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_SCALABLEHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_STEREOHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MULTIVIEWHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , , H264PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP8PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VP9PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , , VIDEO_CODEC_PROFILE_MAX);
// Decryptor Status
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kSuccess,
Decryptor::Status::SUCCESS);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kNoKey,
Decryptor::Status::NO_KEY);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kNeedMoreData,
Decryptor::Status::NEED_MORE_DATA);
ASSERT_ENUM_EQ_RAW(Decryptor::Status,
Decryptor::kError,
Decryptor::Status::DECRYPTION_ERROR);
// CdmException
#define ASSERT_CDM_EXCEPTION(value) \
static_assert( \
media::MediaKeys::value == static_cast<media::MediaKeys::Exception>( \
media::interfaces::CdmException::value), \
"Mismatched CDM Exception")
ASSERT_CDM_EXCEPTION(NOT_SUPPORTED_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_STATE_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_ACCESS_ERROR);
ASSERT_CDM_EXCEPTION(QUOTA_EXCEEDED_ERROR);
ASSERT_CDM_EXCEPTION(UNKNOWN_ERROR);
ASSERT_CDM_EXCEPTION(CLIENT_ERROR);
ASSERT_CDM_EXCEPTION(OUTPUT_ERROR);
// CDM Session Type
#define ASSERT_CDM_SESSION_TYPE(value) \
static_assert( \
media::MediaKeys::value == \
static_cast<media::MediaKeys::SessionType>( \
media::interfaces::ContentDecryptionModule::SessionType::value), \
"Mismatched CDM Session Type")
ASSERT_CDM_SESSION_TYPE(TEMPORARY_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_LICENSE_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_RELEASE_MESSAGE_SESSION);
// CDM InitDataType
#define ASSERT_CDM_INIT_DATA_TYPE(value) \
static_assert(media::EmeInitDataType::value == \
static_cast<media::EmeInitDataType>( \
media::interfaces::ContentDecryptionModule:: \
InitDataType::value), \
"Mismatched CDM Init Data Type")
ASSERT_CDM_INIT_DATA_TYPE(UNKNOWN);
ASSERT_CDM_INIT_DATA_TYPE(WEBM);
ASSERT_CDM_INIT_DATA_TYPE(CENC);
ASSERT_CDM_INIT_DATA_TYPE(KEYIDS);
// CDM Key Status
#define ASSERT_CDM_KEY_STATUS(value) \
static_assert(media::CdmKeyInformation::value == \
static_cast<media::CdmKeyInformation::KeyStatus>( \
media::interfaces::CdmKeyStatus::value), \
"Mismatched CDM Key Status")
ASSERT_CDM_KEY_STATUS(USABLE);
ASSERT_CDM_KEY_STATUS(INTERNAL_ERROR);
ASSERT_CDM_KEY_STATUS(EXPIRED);
ASSERT_CDM_KEY_STATUS(OUTPUT_RESTRICTED);
ASSERT_CDM_KEY_STATUS(OUTPUT_DOWNSCALED);
ASSERT_CDM_KEY_STATUS(KEY_STATUS_PENDING);
// CDM Message Type
#define ASSERT_CDM_MESSAGE_TYPE(value) \
static_assert(media::MediaKeys::value == \
static_cast<media::MediaKeys::MessageType>( \
media::interfaces::CdmMessageType::value), \
"Mismatched CDM Message Type")
ASSERT_CDM_MESSAGE_TYPE(LICENSE_REQUEST);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RENEWAL);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RELEASE);
// static
media::interfaces::SubsampleEntryPtr TypeConverter<
media::interfaces::SubsampleEntryPtr,
media::SubsampleEntry>::Convert(const media::SubsampleEntry& input) {
media::interfaces::SubsampleEntryPtr mojo_subsample_entry(
media::interfaces::SubsampleEntry::New());
mojo_subsample_entry->clear_bytes = input.clear_bytes;
mojo_subsample_entry->cypher_bytes = input.cypher_bytes;
return mojo_subsample_entry;
}
// static
media::SubsampleEntry
TypeConverter<media::SubsampleEntry, media::interfaces::SubsampleEntryPtr>::
Convert(const media::interfaces::SubsampleEntryPtr& input) {
return media::SubsampleEntry(input->clear_bytes, input->cypher_bytes);
}
// static
media::interfaces::DecryptConfigPtr TypeConverter<
media::interfaces::DecryptConfigPtr,
media::DecryptConfig>::Convert(const media::DecryptConfig& input) {
media::interfaces::DecryptConfigPtr mojo_decrypt_config(
media::interfaces::DecryptConfig::New());
mojo_decrypt_config->key_id = input.key_id();
mojo_decrypt_config->iv = input.iv();
mojo_decrypt_config->subsamples =
Array<media::interfaces::SubsampleEntryPtr>::From(input.subsamples());
return mojo_decrypt_config;
}
// static
scoped_ptr<media::DecryptConfig>
TypeConverter<scoped_ptr<media::DecryptConfig>,
media::interfaces::DecryptConfigPtr>::
Convert(const media::interfaces::DecryptConfigPtr& input) {
return make_scoped_ptr(new media::DecryptConfig(
input->key_id, input->iv,
input->subsamples.To<std::vector<media::SubsampleEntry>>()));
}
// static
media::interfaces::DecoderBufferPtr
TypeConverter<media::interfaces::DecoderBufferPtr,
scoped_refptr<media::DecoderBuffer>>::
Convert(const scoped_refptr<media::DecoderBuffer>& input) {
DCHECK(input);
media::interfaces::DecoderBufferPtr mojo_buffer(
media::interfaces::DecoderBuffer::New());
if (input->end_of_stream())
return mojo_buffer;
mojo_buffer->timestamp_usec = input->timestamp().InMicroseconds();
mojo_buffer->duration_usec = input->duration().InMicroseconds();
mojo_buffer->is_key_frame = input->is_key_frame();
mojo_buffer->data_size = base::checked_cast<uint32_t>(input->data_size());
mojo_buffer->side_data_size =
base::checked_cast<uint32_t>(input->side_data_size());
mojo_buffer->front_discard_usec =
input->discard_padding().first.InMicroseconds();
mojo_buffer->back_discard_usec =
input->discard_padding().second.InMicroseconds();
mojo_buffer->splice_timestamp_usec =
input->splice_timestamp().InMicroseconds();
// Note: The side data is always small, so this copy is okay.
std::vector<uint8_t> side_data(input->side_data(),
input->side_data() + input->side_data_size());
mojo_buffer->side_data.Swap(&side_data);
if (input->decrypt_config()) {
mojo_buffer->decrypt_config =
media::interfaces::DecryptConfig::From(*input->decrypt_config());
}
// TODO(dalecurtis): We intentionally do not serialize the data section of
// the DecoderBuffer here; this must instead be done by clients via their
// own DataPipe. See http://crbug.com/432960
return mojo_buffer;
}
// static
scoped_refptr<media::DecoderBuffer>
TypeConverter<scoped_refptr<media::DecoderBuffer>,
media::interfaces::DecoderBufferPtr>::
Convert(const media::interfaces::DecoderBufferPtr& input) {
if (!input->data_size)
return media::DecoderBuffer::CreateEOSBuffer();
scoped_refptr<media::DecoderBuffer> buffer(
new media::DecoderBuffer(input->data_size));
if (input->side_data_size)
buffer->CopySideDataFrom(&input->side_data.front(), input->side_data_size);
buffer->set_timestamp(
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
buffer->set_duration(base::TimeDelta::FromMicroseconds(input->duration_usec));
if (input->is_key_frame)
buffer->set_is_key_frame(true);
if (input->decrypt_config) {
buffer->set_decrypt_config(
input->decrypt_config.To<scoped_ptr<media::DecryptConfig>>());
}
media::DecoderBuffer::DiscardPadding discard_padding(
base::TimeDelta::FromMicroseconds(input->front_discard_usec),
base::TimeDelta::FromMicroseconds(input->back_discard_usec));
buffer->set_discard_padding(discard_padding);
buffer->set_splice_timestamp(
base::TimeDelta::FromMicroseconds(input->splice_timestamp_usec));
// TODO(dalecurtis): We intentionally do not deserialize the data section of
// the DecoderBuffer here; this must instead be done by clients via their
// own DataPipe. See http://crbug.com/432960
return buffer;
}
// static
media::interfaces::AudioDecoderConfigPtr TypeConverter<
media::interfaces::AudioDecoderConfigPtr,
media::AudioDecoderConfig>::Convert(const media::AudioDecoderConfig&
input) {
media::interfaces::AudioDecoderConfigPtr config(
media::interfaces::AudioDecoderConfig::New());
config->codec = static_cast<media::interfaces::AudioCodec>(input.codec());
config->sample_format =
static_cast<media::interfaces::SampleFormat>(input.sample_format());
config->channel_layout =
static_cast<media::interfaces::ChannelLayout>(input.channel_layout());
config->samples_per_second = input.samples_per_second();
if (!input.extra_data().empty()) {
config->extra_data = mojo::Array<uint8_t>::From(input.extra_data());
}
config->seek_preroll_usec = input.seek_preroll().InMicroseconds();
config->codec_delay = input.codec_delay();
config->is_encrypted = input.is_encrypted();
return config;
}
// static
media::AudioDecoderConfig
TypeConverter<media::AudioDecoderConfig,
media::interfaces::AudioDecoderConfigPtr>::
Convert(const media::interfaces::AudioDecoderConfigPtr& input) {
media::AudioDecoderConfig config;
config.Initialize(static_cast<media::AudioCodec>(input->codec),
static_cast<media::SampleFormat>(input->sample_format),
static_cast<media::ChannelLayout>(input->channel_layout),
input->samples_per_second, input->extra_data.storage(),
input->is_encrypted,
base::TimeDelta::FromMicroseconds(input->seek_preroll_usec),
input->codec_delay);
return config;
}
// static
media::interfaces::VideoDecoderConfigPtr TypeConverter<
media::interfaces::VideoDecoderConfigPtr,
media::VideoDecoderConfig>::Convert(const media::VideoDecoderConfig&
input) {
media::interfaces::VideoDecoderConfigPtr config(
media::interfaces::VideoDecoderConfig::New());
config->codec = static_cast<media::interfaces::VideoCodec>(input.codec());
config->profile =
static_cast<media::interfaces::VideoCodecProfile>(input.profile());
config->format = static_cast<media::interfaces::VideoFormat>(input.format());
config->color_space =
static_cast<media::interfaces::ColorSpace>(input.color_space());
config->coded_size = Size::From(input.coded_size());
config->visible_rect = Rect::From(input.visible_rect());
config->natural_size = Size::From(input.natural_size());
if (!input.extra_data().empty()) {
config->extra_data = mojo::Array<uint8_t>::From(input.extra_data());
}
config->is_encrypted = input.is_encrypted();
return config;
}
// static
media::VideoDecoderConfig
TypeConverter<media::VideoDecoderConfig,
media::interfaces::VideoDecoderConfigPtr>::
Convert(const media::interfaces::VideoDecoderConfigPtr& input) {
media::VideoDecoderConfig config;
config.Initialize(static_cast<media::VideoCodec>(input->codec),
static_cast<media::VideoCodecProfile>(input->profile),
static_cast<media::VideoPixelFormat>(input->format),
static_cast<media::ColorSpace>(input->color_space),
input->coded_size.To<gfx::Size>(),
input->visible_rect.To<gfx::Rect>(),
input->natural_size.To<gfx::Size>(),
input->extra_data.storage(), input->is_encrypted);
return config;
}
// static
media::interfaces::CdmKeyInformationPtr TypeConverter<
media::interfaces::CdmKeyInformationPtr,
media::CdmKeyInformation>::Convert(const media::CdmKeyInformation& input) {
media::interfaces::CdmKeyInformationPtr info(
media::interfaces::CdmKeyInformation::New());
std::vector<uint8_t> key_id_copy(input.key_id);
info->key_id.Swap(&key_id_copy);
info->status = static_cast<media::interfaces::CdmKeyStatus>(input.status);
info->system_code = input.system_code;
return info;
}
// static
scoped_ptr<media::CdmKeyInformation>
TypeConverter<scoped_ptr<media::CdmKeyInformation>,
media::interfaces::CdmKeyInformationPtr>::
Convert(const media::interfaces::CdmKeyInformationPtr& input) {
return make_scoped_ptr(new media::CdmKeyInformation(
input->key_id.storage(),
static_cast<media::CdmKeyInformation::KeyStatus>(input->status),
input->system_code));
}
// static
media::interfaces::CdmConfigPtr
TypeConverter<media::interfaces::CdmConfigPtr, media::CdmConfig>::Convert(
const media::CdmConfig& input) {
media::interfaces::CdmConfigPtr config(media::interfaces::CdmConfig::New());
config->allow_distinctive_identifier = input.allow_distinctive_identifier;
config->allow_persistent_state = input.allow_persistent_state;
config->use_hw_secure_codecs = input.use_hw_secure_codecs;
return config;
}
// static
media::CdmConfig
TypeConverter<media::CdmConfig, media::interfaces::CdmConfigPtr>::Convert(
const media::interfaces::CdmConfigPtr& input) {
media::CdmConfig config;
config.allow_distinctive_identifier = input->allow_distinctive_identifier;
config.allow_persistent_state = input->allow_persistent_state;
config.use_hw_secure_codecs = input->use_hw_secure_codecs;
return config;
}
// static
media::interfaces::AudioBufferPtr
TypeConverter<media::interfaces::AudioBufferPtr,
scoped_refptr<media::AudioBuffer>>::
Convert(const scoped_refptr<media::AudioBuffer>& input) {
media::interfaces::AudioBufferPtr buffer(
media::interfaces::AudioBuffer::New());
buffer->sample_format =
static_cast<media::interfaces::SampleFormat>(input->sample_format_);
buffer->channel_layout =
static_cast<media::interfaces::ChannelLayout>(input->channel_layout());
buffer->channel_count = input->channel_count();
buffer->sample_rate = input->sample_rate();
buffer->frame_count = input->frame_count();
buffer->end_of_stream = input->end_of_stream();
buffer->timestamp_usec = input->timestamp().InMicroseconds();
if (!input->end_of_stream()) {
std::vector<uint8_t> input_data(input->data_.get(),
input->data_.get() + input->data_size_);
buffer->data.Swap(&input_data);
}
return buffer;
}
// static
scoped_refptr<media::AudioBuffer>
TypeConverter<scoped_refptr<media::AudioBuffer>,
media::interfaces::AudioBufferPtr>::
Convert(const media::interfaces::AudioBufferPtr& input) {
if (input->end_of_stream)
return media::AudioBuffer::CreateEOSBuffer();
// Setup channel pointers. AudioBuffer::CopyFrom() will only use the first
// one in the case of interleaved data.
std::vector<const uint8_t*> channel_ptrs(input->channel_count, nullptr);
std::vector<uint8_t> storage = input->data.storage();
const size_t size_per_channel = storage.size() / input->channel_count;
DCHECK_EQ(0u, storage.size() % input->channel_count);
for (int i = 0; i < input->channel_count; ++i)
channel_ptrs[i] = storage.data() + i * size_per_channel;
return media::AudioBuffer::CopyFrom(
static_cast<media::SampleFormat>(input->sample_format),
static_cast<media::ChannelLayout>(input->channel_layout),
input->channel_count, input->sample_rate, input->frame_count,
&channel_ptrs[0],
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
}
// static
media::interfaces::VideoFramePtr
TypeConverter<media::interfaces::VideoFramePtr,
scoped_refptr<media::VideoFrame>>::
Convert(const scoped_refptr<media::VideoFrame>& input) {
media::interfaces::VideoFramePtr frame(media::interfaces::VideoFrame::New());
frame->end_of_stream =
input->metadata()->IsTrue(media::VideoFrameMetadata::END_OF_STREAM);
if (frame->end_of_stream)
return frame;
// Handle non EOS frame. It must be a MojoSharedBufferVideoFrame.
// TODO(jrummell): Support other types of VideoFrame.
CHECK_EQ(media::VideoFrame::STORAGE_MOJO_SHARED_BUFFER,
input->storage_type());
media::MojoSharedBufferVideoFrame* input_frame =
static_cast<media::MojoSharedBufferVideoFrame*>(input.get());
mojo::ScopedSharedBufferHandle duplicated_handle;
const MojoResult result =
DuplicateBuffer(input_frame->Handle(), nullptr, &duplicated_handle);
CHECK_EQ(MOJO_RESULT_OK, result);
CHECK(duplicated_handle.is_valid());
frame->format = static_cast<media::interfaces::VideoFormat>(input->format());
frame->coded_size = Size::From(input->coded_size());
frame->visible_rect = Rect::From(input->visible_rect());
frame->natural_size = Size::From(input->natural_size());
frame->timestamp_usec = input->timestamp().InMicroseconds();
frame->frame_data = std::move(duplicated_handle);
frame->frame_data_size = input_frame->MappedSize();
frame->y_stride = input_frame->stride(media::VideoFrame::kYPlane);
frame->u_stride = input_frame->stride(media::VideoFrame::kUPlane);
frame->v_stride = input_frame->stride(media::VideoFrame::kVPlane);
frame->y_offset = input_frame->PlaneOffset(media::VideoFrame::kYPlane);
frame->u_offset = input_frame->PlaneOffset(media::VideoFrame::kUPlane);
frame->v_offset = input_frame->PlaneOffset(media::VideoFrame::kVPlane);
return frame;
}
// static
scoped_refptr<media::VideoFrame>
TypeConverter<scoped_refptr<media::VideoFrame>,
media::interfaces::VideoFramePtr>::
Convert(const media::interfaces::VideoFramePtr& input) {
if (input->end_of_stream)
return media::VideoFrame::CreateEOSFrame();
return media::MojoSharedBufferVideoFrame::Create(
static_cast<media::VideoPixelFormat>(input->format),
input->coded_size.To<gfx::Size>(), input->visible_rect.To<gfx::Rect>(),
input->natural_size.To<gfx::Size>(), std::move(input->frame_data),
input->frame_data_size, input->y_offset, input->u_offset, input->v_offset,
input->y_stride, input->u_stride, input->v_stride,
base::TimeDelta::FromMicroseconds(input->timestamp_usec));
}
} // namespace mojo
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.