answer
stringlengths 15
1.25M
|
|---|
<?php
namespace SilverShop\ORM\FieldType;
use SilverShop\Extension\ShopConfigExtension;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\FieldType\DBVarchar;
class ShopCountry extends DBVarchar
{
public function __construct($name = null, $size = 3, $options = [])
{
parent::__construct($name, $size = 3, $options);
}
public function forTemplate()
{
return $this->Nice();
}
/**
* Convert ISO abbreviation to full, translated country name
*/
public function Nice()
{
$val = ShopConfigExtension::countryCode2name($this->value);
if (!$val) {
$val = $this->value;
}
return _t(__CLASS__ . '.' . $this->value, $val);
}
public function XML()
{
return Convert::raw2xml($this->Nice());
}
}
|
<!DOCTYPE html>
<html lang="en" dir="ltr"
xmlns:dc="http://purl.org/dc/terms/">
<head>
<meta charset="utf-8" />
<meta name="generator" content="diff2html.py (http://git.droids-corp.org/gitweb/?p=diff2html)" />
<!--meta name="author" content="Fill in" /
<title>HTML Diff futures/daytime_client.cpp</title>
<link rel="shortcut icon" href="data:image/png;base64,<API key>///+K/HwIAAAAJUlEQVQI12NYBQQM2IgGBQ4mCIEQW7oyK4phampkGIQAc1G1AQCRxCNbyW92oQAAAABJRU5ErkJggg==" type="image/png" />
<meta property="dc:language" content="en" />
<!--meta property="dc:date" content="" /
<meta property="dc:modified" content="2013-11-15T07:51:48.749891+01:00" />
<meta name="description" content="File comparison" />
<meta property="dc:abstract" content="File comparison" />
<style>
table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
td.line { color:#8080a0 }
th { background: black; color: white }
tr.diffunmodified td { background: #D0D0E0 }
tr.diffhunk td { background: #A0A0A0 }
tr.diffadded td { background: #CCFFCC }
tr.diffdeleted td { background: #FFCCCC }
tr.diffchanged td { background: #FFFFA0 }
span.diffchanged2 { background: #E0C880 }
span.diffponct { color: #B08080 }
tr.diffmisc td {}
tr.diffseparator td {}
</style>
</head>
<body>
<table class="diff">
</table>
<footer>
<p>Modified at 15.11.2013. HTML formatting created by <a href="http://git.droids-corp.org/gitweb/?p=diff2html;a=summary">diff2html</a>. </p>
</footer>
</body></html>
|
def excise(conn, qrelname, tid):
with conn.cursor() as cur:
# Assume 'id' column exists and print that for bookkeeping.
# TODO: Instead should find unique constraints and print
# those, or try to print all attributes that are not corrupt.
sql = 'DELETE FROM {0} WHERE ctid = %s RETURNING id'.format(qrelname)
params = (tid,)
cur.execute(sql, params)
row = cur.fetchone()
if row:
return row[0]
return None
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// | Artisan Smarty |
// | PHP Version 4 |
// | Authors: Akito<akito-artisan@five-foxes.com> |
/**
* ArtisanSmarty plugin
* @package ArtisanSmarty
* @subpackage plugins
*/
function <API key>($string)
{
// find periods with a word before but not after.
return preg_match_all('/[^\s]\.(?!\w)/', $string, $match);
}
/* vim: set expandtab: */
?>
|
package com.github.tototoshi.slick.converter
import org.joda.time._
import java.sql.{ Timestamp, Time }
trait <API key>
extends SqlTypeConverter[String, DateTimeZone] {
def toSqlType(z: DateTimeZone): String =
if (z == null) null else z.getID
def fromSqlType(z: String): DateTimeZone =
if (z == null) null else DateTimeZone.forID(z)
}
trait <API key>
extends SqlTypeConverter[java.sql.Date, LocalDate] {
def toSqlType(d: LocalDate): java.sql.Date =
if (d == null) null else millisToSqlType(d.toDate)
def fromSqlType(d: java.sql.Date): LocalDate =
if (d == null) null else new LocalDate(d.getTime)
}
trait <API key>
extends SqlTypeConverter[Timestamp, DateTime] {
def fromSqlType(t: java.sql.Timestamp): DateTime =
if (t == null) null else new DateTime(t.getTime)
def toSqlType(t: DateTime): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.getMillis)
}
trait <API key>
extends SqlTypeConverter[Timestamp, Instant] {
def fromSqlType(t: java.sql.Timestamp): Instant =
if (t == null) null else new Instant(t.getTime)
def toSqlType(t: Instant): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.getMillis)
}
trait <API key>
extends SqlTypeConverter[Timestamp, LocalDateTime] {
def fromSqlType(t: java.sql.Timestamp): LocalDateTime =
if (t == null) null else new LocalDateTime(t.getTime)
def toSqlType(t: LocalDateTime): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.toDate.getTime)
}
trait <API key>
extends SqlTypeConverter[Time, LocalTime] {
def fromSqlType(t: java.sql.Time): LocalTime =
if (t == null) null else new LocalTime(t.getTime)
def toSqlType(t: LocalTime): java.sql.Time = {
if (t == null) null else new java.sql.Time(t.toDateTimeToday.getMillis)
}
}
|
# <API key>: true
require_relative '../helpers/load_file'
module WavefrontCli
module Subcommand
# Stuff to import an object
class Import
attr_reader :wf, :options
def initialize(calling_class, options)
@calling_class = calling_class
@wf = calling_class.wf
@options = options
@message = 'IMPORTED'
end
def run!
errs = 0
[raw_input].flatten.each do |obj|
resp = import_object(obj)
next if options[:noop]
errs += 1 unless resp.ok?
puts import_message(obj, resp)
end
exit errs
end
private
def raw_input
WavefrontCli::Helper::LoadFile.new(options[:'<file>']).load
end
def import_message(obj, resp)
format('%-15<id>s %-10<status>s %<message>s',
id: obj[:id] || obj[:url],
status: resp.ok? ? @message : 'FAILED',
message: resp.status.message)
end
def import_object(raw)
raw = preprocess_rawfile(raw) if respond_to?(:preprocess_rawfile)
prepped = @calling_class.import_to_create(raw)
if options[:upsert]
import_upsert(raw, prepped)
elsif options[:update]
@message = 'UPDATED'
import_update(raw)
else
wf.create(prepped)
end
end
def import_upsert(raw, prepped)
update_call = import_update(raw)
if update_call.ok?
@message = 'UPDATED'
return update_call
end
puts 'update failed, inserting' if options[:verbose] || options[:debug]
wf.create(prepped)
end
def import_update(raw)
wf.update(raw[:id], raw, false)
end
end
end
end
|
#include "global.h"
#include "lexer.h"
struct KL_Lexer {
char fname[BFILE];
FILE* stream;
char lexbuf[BSIZE];
int lineno;
int bsize;
int pos;
KL_Boolean eof;
};
enum KL_LexState {
LEX_STATE_BEGIN = 0,
LEX_STATE_FINISH,
LEX_STATE_IN_CINT,
LEX_STATE_IN_CREAL,
LEX_STATE_IN_CSTR,
LEX_STATE_IN_ID,
<API key>,
<API key>,
LEX_STATE_IN_GTGE,
LEX_STATE_IN_AND,
LEX_STATE_IN_OR,
<API key>,
};
static const struct {
const char* lexptr;
int token;
} kReserveds[] = {
{"nil", TT_NIL},
{"true", TT_TRUE},
{"false", TT_FALSE},
{"if", TT_IF},
{"else", TT_ELSE},
{"while", TT_WHILE},
{"break", TT_BREAK},
{"func", TT_FUNC},
{"return", TT_RET},
};
static int
get_char(KL_Lexer* lex)
{
if (lex->pos >= lex->bsize) {
if (NULL != fgets(lex->lexbuf, sizeof(lex->lexbuf), lex->stream)) {
lex->pos = 0;
lex->bsize = (int)strlen(lex->lexbuf);
}
else {
lex->eof = BOOL_YES;
return EOF;
}
}
return lex->lexbuf[lex->pos++];
}
static void
unget_char(KL_Lexer* lex)
{
if (!lex->eof)
--lex->pos;
}
static int
lookup_reserved(const char* s)
{
int i, count = countof(kReserveds);
for (i = 0; i < count; ++i) {
if (0 == strcmp(kReserveds[i].lexptr, s))
return kReserveds[i].token;
}
return TT_ID;
}
KL_Lexer*
KL_lexer_create(const char* fname)
{
KL_Lexer* lex = (KL_Lexer*)malloc(sizeof(*lex));
if (NULL == lex)
return NULL;
do {
lex->stream = fopen(fname, "r");
if (NULL == lex->stream)
break;
strcpy(lex->fname, fname);
lex->lineno = 1;
lex->bsize = 0;
lex->pos = 0;
lex->eof = BOOL_NO;
return lex;
} while (0);
if (NULL != lex)
free(lex);
return NULL;
}
void
KL_lexer_release(KL_Lexer** lex)
{
if (NULL != *lex) {
if (NULL != (*lex)->stream)
fclose((*lex)->stream);
free(*lex);
*lex = NULL;
}
}
int
KL_lexer_token(KL_Lexer* lex, KL_Token* tok)
{
int type = TT_ERR;
int i = 0;
int state = LEX_STATE_BEGIN;
KL_Boolean save = BOOL_NO;
int c;
while (LEX_STATE_FINISH != state) {
c = get_char(lex);
save = BOOL_YES;
switch (state) {
case LEX_STATE_BEGIN:
if (' ' == c || '\t' == c) {
save = BOOL_NO;
}
else if ('\n' == c) {
save = BOOL_NO;
++lex->lineno;
}
else if (isdigit(c)) {
state = LEX_STATE_IN_CINT;
}
else if ('\'' == c) {
save = BOOL_NO;
state = LEX_STATE_IN_CSTR;
}
else if (isdigit(c) || '_' == c) {
state = LEX_STATE_IN_ID;
}
else if ('=' == c) {
state = <API key>;
}
else if ('>' == c) {
state = LEX_STATE_IN_GTGE;
}
else if ('<' == c) {
state = <API key>;
}
else if ('&' == c) {
state = LEX_STATE_IN_AND;
}
else if ('|' == c) {
state = LEX_STATE_IN_OR;
}
else if ('
state = <API key>;
}
else {
state = LEX_STATE_FINISH;
switch (c) {
case EOF:
save = BOOL_NO;
type = TT_EOF;
break;
case '+':
type = TT_ADD;
break;
case '-':
type = TT_SUB;
break;
case '*':
type = TT_MUL;
break;
case '/':
type = TT_DIV;
break;
case '%':
type = TT_MOD;
break;
case '.':
type = TT_DOT;
break;
case ',':
type = TT_COMMA;
break;
case ';':
type = TT_SEMI;
break;
case '(':
type = TT_LPAREN;
break;
case ')':
type = TT_RPAREN;
break;
case '[':
type = TT_LBRACKET;
break;
case ']':
type = TT_RBRACKET;
break;
case '{':
type = TT_LBRACE;
break;
case '}':
type = TT_RBRACE;
break;
default:
save = BOOL_NO;
type = TT_ERR;
break;
}
}
break;
case LEX_STATE_IN_CINT:
if ('.' == c) {
state = LEX_STATE_IN_CREAL;
}
else {
if (!isdigit(c)) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CINT;
}
}
break;
case LEX_STATE_IN_CREAL:
if (!isdigit(c)) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CREAL;
}
break;
case LEX_STATE_IN_CSTR:
if ('\'' == c) {
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CSTR;
}
break;
case LEX_STATE_IN_ID:
if (!isalnum(c) && '_' != c) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_ID;
}
break;
case <API key>:
if ('=' == c) {
type = TT_EQ;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ASSIGN;
}
state = LEX_STATE_FINISH;
break;
case <API key>:
if ('>' == c) {
type = TT_NEQ;
}
else if ('=' == c) {
type = TT_LE;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_LT;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_GTGE:
if ('=' == c) {
type = TT_GE;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_GT;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_AND:
if ('&' == c) {
type = TT_ADD;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ERR;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_OR:
if ('|' == c) {
type = TT_OR;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ERR;
}
state = LEX_STATE_FINISH;
break;
case <API key>:
save = BOOL_NO;
if (EOF == c) {
state = LEX_STATE_FINISH;
type = TT_ERR;
}
else if ('\n' == c) {
++lex->lineno;
state = LEX_STATE_BEGIN;
}
break;
case LEX_STATE_FINISH:
default:
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_ERR;
break;
}
if (save && i < BSIZE)
tok->name[i++] = (char)c;
if (LEX_STATE_FINISH == state) {
tok->name[i] = 0;
tok->type = type;
tok->line.lineno = lex->lineno;
strcpy(tok->line.fname, lex->fname);
if (TT_ID == type)
tok->type = type = lookup_reserved(tok->name);
}
}
return type;
}
|
import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Question
class QuestionMethodTests(TestCase):
def <API key>(self):
"""
<API key>() should return False for questions whose
pub_date is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.<API key>(), False)
def <API key>(self):
"""
<API key>() should return False for questions whose
pub_date is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertIs(old_question.<API key>(), False)
def <API key>(self):
"""
<API key>() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.<API key>(), True)
def create_question(question_text, days):
"""
Creates a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class QuestionViewTests(TestCase):
def <API key>(self):
"""
If no questions exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['<API key>'], [])
def <API key>(self):
"""
Questions with a pub_date in the past should be displayed on the
index page.
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['<API key>'],
['<Question: Past question.>']
)
def <API key>(self):
"""
Questions with a pub_date in the future should not be displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['<API key>'], [])
def <API key>(self):
"""
Even if both past and future questions exist, only past questions
should be displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['<API key>'],
['<Question: Past question.>']
)
def <API key>(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['<API key>'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class <API key>(TestCase):
def <API key>(self):
"""
The detail view of a question with a pub_date in the future should
return a 404 not found.
"""
future_question = create_question(question_text='Future question.', days=5)
url = reverse('polls:detail', args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def <API key>(self):
"""
The detail view of a question with a pub_date in the past should
display the question's text.
"""
past_question = create_question(question_text='Past Question.', days=-5)
url = reverse('polls:detail', args=(past_question.id,))
response = self.client.get(url)
self.assertContains(response, past_question.question_text)
|
class GetIplayer < Formula
desc "Utility for downloading TV and radio programmes from BBC iPlayer"
homepage "https://github.com/get-iplayer/get_iplayer"
url "https://github.com/get-iplayer/get_iplayer/archive/v3.06.tar.gz"
sha256 "<SHA256-like>"
head "https://github.com/get-iplayer/get_iplayer.git", :branch => "develop"
bottle do
cellar :any_skip_relocation
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
sha256 "<SHA256-like>" => :el_capitan
end
depends_on "atomicparsley" => :recommended
depends_on "ffmpeg" => :recommended
depends_on :macos => :yosemite
resource "IO::Socket::IP" do
url "https://cpan.metacpan.org/authors/id/P/PE/PEVANS/IO-Socket-IP-0.39.tar.gz"
sha256 "<SHA256-like>"
end
resource "Mojolicious" do
url "https://cpan.metacpan.org/authors/id/S/SR/SRI/Mojolicious-7.48.tar.gz"
sha256 "<SHA256-like>"
end
def install
ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5"
resources.each do |r|
r.stage do
system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}"
system "make", "install"
end
end
inreplace ["get_iplayer", "get_iplayer.cgi"] do |s|
s.gsub!(/^(my \$version_text);/i, "\\1 = \"#{pkg_version}-homebrew\";")
s.gsub! "#!/usr/bin/env perl", "#!/usr/bin/perl"
end
bin.install "get_iplayer", "get_iplayer.cgi"
bin.<API key>(libexec/"bin", :PERL5LIB => ENV["PERL5LIB"])
man1.install "get_iplayer.1"
end
test do
output = shell_output("\"#{bin}/get_iplayer\" --refresh --refresh-include=\"BBC None\" --quiet dontshowanymatches 2>&1")
assert_match "get_iplayer #{pkg_version}-homebrew", output, "Unexpected version"
assert_match "INFO: 0 matching programmes", output, "Unexpected output"
assert_match "INFO: Indexing tv programmes (concurrent)", output,
"Mojolicious not found"
end
end
|
#include <botan/asn1_print.h>
#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <iomanip>
#include <sstream>
#include <cctype>
namespace Botan {
namespace {
bool all_printable_chars(const uint8_t bits[], size_t bits_len)
{
for(size_t i = 0; i != bits_len; ++i)
{
int c = bits[i];
if(c > 127)
return false;
if((std::isalnum(c) || c == '.' || c == ':' || c == '/' || c == '-') == false)
return false;
}
return true;
}
/*
* Special hack to handle GeneralName [2] and [6] (DNS name and URI)
*/
bool <API key>(const uint8_t bits[], size_t bits_len)
{
if(bits_len <= 2)
return false;
if(bits[0] != 0x82 && bits[0] != 0x86)
return false;
if(bits[1] != bits_len - 2)
return false;
if(all_printable_chars(bits + 2, bits_len - 2) == false)
return false;
return true;
}
}
std::string ASN1_Formatter::print(const uint8_t in[], size_t len) const
{
std::ostringstream output;
print_to_stream(output, in, len);
return output.str();
}
void ASN1_Formatter::print_to_stream(std::ostream& output,
const uint8_t in[],
size_t len) const
{
BER_Decoder dec(in, len);
decode(output, dec, 0);
}
void ASN1_Formatter::decode(std::ostream& output,
BER_Decoder& decoder,
size_t level) const
{
BER_Object obj = decoder.get_next_object();
while(obj.type_tag != NO_OBJECT)
{
const ASN1_Tag type_tag = obj.type_tag;
const ASN1_Tag class_tag = obj.class_tag;
const size_t length = obj.value.size();
/* hack to insert the tag+length back in front of the stuff now
that we've gotten the type info */
DER_Encoder encoder;
encoder.add_object(type_tag, class_tag, obj.value);
const std::vector<uint8_t> bits = encoder.<API key>();
BER_Decoder data(bits);
if(class_tag & CONSTRUCTED)
{
BER_Decoder cons_info(obj.value);
output << format(type_tag, class_tag, level, length, "");
decode(output, cons_info, level + 1); // recurse
}
else if((class_tag & APPLICATION) || (class_tag & CONTEXT_SPECIFIC))
{
bool success_parsing_cs = false;
if(<API key>)
{
try
{
if(<API key>(bits.data(), bits.size()))
{
output << format(type_tag, class_tag, level, level,
std::string(<API key>(&bits[2]), bits.size() - 2));
success_parsing_cs = true;
}
else
{
std::vector<uint8_t> inner_bits;
data.decode(inner_bits, type_tag);
BER_Decoder inner(inner_bits);
std::ostringstream inner_data;
decode(inner_data, inner, level + 1); // recurse
output << inner_data.str();
success_parsing_cs = true;
}
}
catch(...)
{
}
}
if(success_parsing_cs == false)
{
output << format(type_tag, class_tag, level, length,
format_bin(type_tag, class_tag, bits));
}
}
else if(type_tag == OBJECT_ID)
{
OID oid;
data.decode(oid);
std::string out = OIDS::lookup(oid);
if(out.empty())
{
out = oid.as_string();
}
else
{
out += " [" + oid.as_string() + "]";
}
output << format(type_tag, class_tag, level, length, out);
}
else if(type_tag == INTEGER || type_tag == ENUMERATED)
{
BigInt number;
if(type_tag == INTEGER)
{
data.decode(number);
}
else if(type_tag == ENUMERATED)
{
data.decode(number, ENUMERATED, class_tag);
}
const std::vector<uint8_t> rep = BigInt::encode(number, BigInt::Hexadecimal);
std::string str;
for(size_t i = 0; i != rep.size(); ++i)
{
str += static_cast<char>(rep[i]);
}
output << format(type_tag, class_tag, level, length, str);
}
else if(type_tag == BOOLEAN)
{
bool boolean;
data.decode(boolean);
output << format(type_tag, class_tag, level, length, (boolean ? "true" : "false"));
}
else if(type_tag == NULL_TAG)
{
output << format(type_tag, class_tag, level, length, "");
}
else if(type_tag == OCTET_STRING || type_tag == BIT_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
try
{
BER_Decoder inner(decoded_bits);
std::ostringstream inner_data;
decode(inner_data, inner, level + 1); // recurse
output << format(type_tag, class_tag, level, length, "");
output << inner_data.str();
}
catch(...)
{
output << format(type_tag, class_tag, level, length,
format_bin(type_tag, class_tag, decoded_bits));
}
}
else if(ASN1_String::is_string_type(type_tag))
{
ASN1_String str;
data.decode(str);
output << format(type_tag, class_tag, level, length, str.value());
}
else if(type_tag == UTC_TIME || type_tag == GENERALIZED_TIME)
{
X509_Time time;
data.decode(time);
output << format(type_tag, class_tag, level, length, time.readable_string());
}
else
{
output << "Unknown ASN.1 tag class=" << static_cast<int>(class_tag)
<< " type=" << static_cast<int>(type_tag) << "\n";;
}
obj = decoder.get_next_object();
}
}
namespace {
std::string format_type(ASN1_Tag type_tag, ASN1_Tag class_tag)
{
if(class_tag == UNIVERSAL)
return asn1_tag_to_string(type_tag);
if(class_tag == CONSTRUCTED && (type_tag == SEQUENCE || type_tag == SET))
return asn1_tag_to_string(type_tag);
std::string name;
if(class_tag & CONSTRUCTED)
name += "cons ";
name += "[" + std::to_string(type_tag) + "]";
if(class_tag & APPLICATION)
{
name += " appl";
}
if(class_tag & CONTEXT_SPECIFIC)
{
name += " context";
}
return name;
}
}
std::string ASN1_Pretty_Printer::format(ASN1_Tag type_tag,
ASN1_Tag class_tag,
size_t level,
size_t length,
const std::string& value) const
{
bool should_skip = false;
if(value.length() > m_print_limit)
{
should_skip = true;
}
if((type_tag == OCTET_STRING || type_tag == BIT_STRING) &&
value.length() > <API key>)
{
should_skip = true;
}
level += m_initial_level;
std::ostringstream oss;
oss << " d=" << std::setw(2) << level
<< ", l=" << std::setw(4) << length << ":"
<< std::string(level + 1, ' ') << format_type(type_tag, class_tag);
if(value != "" && !should_skip)
{
const size_t current_pos = static_cast<size_t>(oss.tellp());
const size_t spaces_to_align =
(current_pos >= m_value_column) ? 1 : (m_value_column - current_pos);
oss << std::string(spaces_to_align, ' ') << value;
}
oss << "\n";
return oss.str();
}
std::string ASN1_Pretty_Printer::format_bin(ASN1_Tag /*type_tag*/,
ASN1_Tag /*class_tag*/,
const std::vector<uint8_t>& vec) const
{
if(all_printable_chars(vec.data(), vec.size()))
{
return std::string(<API key>(vec.data()), vec.size());
}
else
return hex_encode(vec);
}
}
|
package operations;
import data.Collector;
import graph.implementation.Edge;
import utility.GraphFunctions;
/**
* Set the curve point to an ideal position.
* If source and destination are equal, it would be a line.
* If not, it is a noose on top of the vertex.
*/
public class O_RelaxEdge implements EdgeOperation {
private Edge edge;
public O_RelaxEdge(Edge edge) {
super();
this.edge = edge;
}
@Override
public void run() {
Collector.getSlides().addUndo();
GraphFunctions.relaxEdge(edge);
}
@Override
public void setEdge(Edge edge) {
this.edge = edge;
}
}
|
#include <types_ext.h>
#include <drivers/ps2mouse.h>
#include <drivers/serial.h>
#include <string.h>
#include <keep.h>
#include <trace.h>
#define PS2_CMD_RESET 0xff
#define PS2_CMD_ACK 0xfa
#define <API key> 0xf4
#define PS2_BAT_OK 0xaa
#define PS2_MOUSE_ID 0x00
#define <API key> (1 << 7)
#define <API key> (1 << 6)
#define PS2_BYTE0_Y_SIGN (1 << 5)
#define PS2_BYTE0_X_SIGN (1 << 4)
#define <API key> (1 << 3)
#define <API key> (1 << 2)
#define <API key> (1 << 1)
#define PS2_BYTE0_LEFT_DOWN (1 << 0)
static void call_callback(struct ps2mouse_data *d, uint8_t byte1,
uint8_t byte2, uint8_t byte3)
{
uint8_t button;
int16_t xdelta;
int16_t ydelta;
button = byte1 & (<API key> | <API key> |
PS2_BYTE0_LEFT_DOWN);
if (byte1 & <API key>) {
xdelta = byte1 & PS2_BYTE0_X_SIGN ? -255 : 255;
} else {
xdelta = byte2;
if (byte1 & PS2_BYTE0_X_SIGN)
xdelta |= 0xff00; /* sign extend */
}
if (byte1 & <API key>) {
ydelta = byte1 & PS2_BYTE0_Y_SIGN ? -255 : 255;
} else {
ydelta = byte3;
if (byte1 & PS2_BYTE0_Y_SIGN)
ydelta |= 0xff00; /* sign extend */
}
d->callback(d->callback_data, button, xdelta, -ydelta);
}
static void psm_consume(struct ps2mouse_data *d, uint8_t b)
{
switch (d->state) {
case PS2MS_RESET:
if (b != PS2_CMD_ACK)
goto reset;
d->state = PS2MS_INIT;
return;
case PS2MS_INIT:
if (b != PS2_BAT_OK)
goto reset;
d->state = PS2MS_INIT2;
return;
case PS2MS_INIT2:
if (b != PS2_MOUSE_ID) {
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
d->state = PS2MS_INACTIVE;
return;
}
d->state = PS2MS_INIT3;
d->serial->ops->putc(d->serial, <API key>);
return;
case PS2MS_INIT3:
d->state = PS2MS_ACTIVE1;
return;
case PS2MS_ACTIVE1:
if (!(b & <API key>))
goto reset;
d->bytes[0] = b;
d->state = PS2MS_ACTIVE2;
return;
case PS2MS_ACTIVE2:
d->bytes[1] = b;
d->state = PS2MS_ACTIVE3;
return;
case PS2MS_ACTIVE3:
d->state = PS2MS_ACTIVE1;
call_callback(d, d->bytes[0], d->bytes[1], b);
return;
default:
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
return;
}
reset:
EMSG("Unexpected byte 0x%x in state %d, resetting", b, d->state);
d->state = PS2MS_RESET;
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
static enum itr_return ps2mouse_itr_cb(struct itr_handler *h)
{
struct ps2mouse_data *d = h->data;
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_NONE;
while (true) {
psm_consume(d, d->serial->ops->getchar(d->serial));
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_HANDLED;
}
}
KEEP_PAGER(ps2mouse_itr_cb);
void ps2mouse_init(struct ps2mouse_data *d, struct serial_chip *serial,
size_t serial_it, ps2mouse_callback cb, void *cb_data)
{
memset(d, 0, sizeof(*d));
d->serial = serial;
d->state = PS2MS_RESET;
d->itr_handler.it = serial_it;
d->itr_handler.flags = ITRF_TRIGGER_LEVEL;
d->itr_handler.handler = ps2mouse_itr_cb;
d->itr_handler.data = d;
d->callback = cb;
d->callback_data = cb_data;
itr_add(&d->itr_handler);
itr_enable(&d->itr_handler);
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
|
# Gearman
[)
w := gearman.NewWorker(ctx, nil)
w.AddServers( gearman.NetConn("tcp","localhost:4730") )
w.AddHandler("reverse", gearman.JobHandler(func(payload io.Reader,reply io.Writer) (error){
buff := make([]byte,1<<16)
s,_ := payload.Read(buff)
buff = buff[0:s]
for i:=len(buff); i>0; i
reply.Write([]byte{ buff[i-1] })
}
return nil
} ))
<-ctx.Done()
Client Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w := gearman.SingleServerClient(ctx, nil)
w.AddServers( gearman.NetConn("tcp","localhost:4730") )
bytes_val, err_if_any := cli.Submit( NewTask("some task", []byte("some byte encoded payload")) ).Value()
## Features
* Worker Support
* Client Support
* Access To Raw Packets
* Async Client Task with promise
## Protocol Support
Protocol Plumbing
The protocol implemented is now https://github.com/gearman/gearmand/blob/master/PROTOCOL
* Binary only protocol
* Access Raw Packets
Protocol Porcelain
* PacketFactory for parsing socket
* Multi server Worker
* Single server Client
* Round Robin Client
2-Clause BSD
## Benchmarks
PacketFactory on LoopReader
<API key> 30000000 43.8 ns/op 20 B/op 1 allocs/op
<API key> 30000000 53.1 ns/op 33 B/op 1 allocs/op
<API key> 10000000 145 ns/op 128 B/op 2 allocs/op
Unmarshal
<API key> 100000000 22.7 ns/op 8 B/op 1 allocs/op
<API key> 30000000 45.2 ns/op 48 B/op 1 allocs/op
<API key> 20000000 112 ns/op 96 B/op 2 allocs/op
Marshal
<API key> 300000000 4.25 ns/op 0 B/op 0 allocs/op
<API key> 200000000 9.70 ns/op 0 B/op 0 allocs/op
<API key> 200000000 9.81 ns/op 0 B/op 0 allocs/op
|
#pragma once
#include "UnrealEd.h"
#include "SoundMod.h"
<API key>(LogSoundModImporter, Verbose, All);
#include "<API key>.h"
|
(function(window, angular, undefined) {'use strict';
/* jshint maxlen: false */
angular.module('ngAnimate', ['ng'])
/**
* @ngdoc provider
* @name $animateProvider
* @description
*
* The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.
* When an animation is triggered, the $animate service will query the $animate service to find any animations that match
* the provided name value.
*
* Requires the {@link ngAnimate `ngAnimate`} module to be installed.
*
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
*
*/
//this private service is only used within CSS-enabled animations
//IE8 + IE9 do not support rAF natively, but that is fine since they
//also don't support transitions and keyframes which means that the code
//below will never be used by the two browsers.
.factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {
var bod = $document[0].body;
return function(fn) {
//the returned function acts as the cancellation function
return $$rAF(function() {
//the line below will force the browser to perform a repaint
//so that all the animated elements within the animation frame
//will be properly updated and drawn on screen. This is
//required to perform multi-class CSS based animations with
//Firefox. DO NOT REMOVE THIS LINE.
var a = bod.offsetWidth + 1;
fn();
});
};
}])
.config(['$provide', '$animateProvider', function($provide, $animateProvider) {
var noop = angular.noop;
var forEach = angular.forEach;
var selectors = $animateProvider.$$selectors;
var ELEMENT_NODE = 1;
var NG_ANIMATE_STATE = '$$ngAnimateState';
var <API key> = 'ng-animate';
var rootAnimateState = {running: true};
function extractElementNode(element) {
for(var i = 0; i < element.length; i++) {
var elm = element[i];
if(elm.nodeType == ELEMENT_NODE) {
return elm;
}
}
}
function <API key>(element) {
return angular.element(extractElementNode(element));
}
function isMatchingElement(elm1, elm2) {
return extractElementNode(elm1) == extractElementNode(elm2);
}
$provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document',
function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) {
var <API key> = 0;
$rootElement.data(NG_ANIMATE_STATE, rootAnimateState);
// disable animations during bootstrap, but once we bootstrapped, wait again
// for another digest until enabling animations. The reason why we digest twice
// is because all structural animations (enter, leave and move) all perform a
// post digest operation before animating. If we only wait for a single digest
// to pass then the structural animation would render its animation on page load.
// (which is what we're trying to avoid when the application first boots up.)
$rootScope.$$postDigest(function() {
$rootScope.$$postDigest(function() {
rootAnimateState.running = false;
});
});
var classNameFilter = $animateProvider.classNameFilter();
var <API key> = !classNameFilter
? function() { return true; }
: function(className) {
return classNameFilter.test(className);
};
function lookup(name) {
if (name) {
var matches = [],
flagMap = {},
classes = name.substr(1).split('.');
//the empty string value is the default animation
//operation which performs CSS transition and keyframe
//animations sniffing. This is always included for each
//element animation procedure if the browser supports
//transitions and/or keyframe animations
if ($sniffer.transitions || $sniffer.animations) {
classes.push('');
}
for(var i=0; i < classes.length; i++) {
var klass = classes[i],
selectorFactoryName = selectors[klass];
if(selectorFactoryName && !flagMap[klass]) {
matches.push($injector.get(selectorFactoryName));
flagMap[klass] = true;
}
}
return matches;
}
}
function animationRunner(element, animationEvent, className) {
//transcluded directives may sometimes fire an animation using only comment nodes
//best to catch this early on to prevent any animation operations from occurring
var node = element[0];
if(!node) {
return;
}
var isSetClassOperation = animationEvent == 'setClass';
var isClassBased = isSetClassOperation ||
animationEvent == 'addClass' ||
animationEvent == 'removeClass';
var classNameAdd, classNameRemove;
if(angular.isArray(className)) {
classNameAdd = className[0];
classNameRemove = className[1];
className = classNameAdd + ' ' + classNameRemove;
}
var currentClassName = element.attr('class');
var classes = currentClassName + ' ' + className;
if(!<API key>(classes)) {
return;
}
var beforeComplete = noop,
beforeCancel = [],
before = [],
afterComplete = noop,
afterCancel = [],
after = [];
var animationLookup = (' ' + classes).replace(/\s+/g,'.');
forEach(lookup(animationLookup), function(animationFactory) {
var created = registerAnimation(animationFactory, animationEvent);
if(!created && isSetClassOperation) {
registerAnimation(animationFactory, 'addClass');
registerAnimation(animationFactory, 'removeClass');
}
});
function registerAnimation(animationFactory, event) {
var afterFn = animationFactory[event];
var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];
if(afterFn || beforeFn) {
if(event == 'leave') {
beforeFn = afterFn;
//when set as null then animation knows to skip this phase
afterFn = null;
}
after.push({
event : event, fn : afterFn
});
before.push({
event : event, fn : beforeFn
});
return true;
}
}
function run(fns, cancellations, allCompleteFn) {
var animations = [];
forEach(fns, function(animation) {
animation.fn && animations.push(animation);
});
var count = 0;
function <API key>(index) {
if(cancellations) {
(cancellations[index] || noop)();
if(++count < animations.length) return;
cancellations = null;
}
allCompleteFn();
}
//The code below adds directly to the array in order to work with
//both sync and async animations. Sync animations are when the done()
//operation is called right away. DO NOT REFACTOR!
forEach(animations, function(animation, index) {
var progress = function() {
<API key>(index);
};
switch(animation.event) {
case 'setClass':
cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress));
break;
case 'addClass':
cancellations.push(animation.fn(element, classNameAdd || className, progress));
break;
case 'removeClass':
cancellations.push(animation.fn(element, classNameRemove || className, progress));
break;
default:
cancellations.push(animation.fn(element, progress));
break;
}
});
if(cancellations && cancellations.length === 0) {
allCompleteFn();
}
}
return {
node : node,
event : animationEvent,
className : className,
isClassBased : isClassBased,
isSetClassOperation : isSetClassOperation,
before : function(allCompleteFn) {
beforeComplete = allCompleteFn;
run(before, beforeCancel, function() {
beforeComplete = noop;
allCompleteFn();
});
},
after : function(allCompleteFn) {
afterComplete = allCompleteFn;
run(after, afterCancel, function() {
afterComplete = noop;
allCompleteFn();
});
},
cancel : function() {
if(beforeCancel) {
forEach(beforeCancel, function(cancelFn) {
(cancelFn || noop)(true);
});
beforeComplete(true);
}
if(afterCancel) {
forEach(afterCancel, function(cancelFn) {
(cancelFn || noop)(true);
});
afterComplete(true);
}
}
};
}
/**
* @ngdoc service
* @name $animate
* @function
*
* @description
* The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.
* When any of these operations are run, the $animate service
* will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)
* as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.
*
* The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives
* will work out of the box without any extra configuration.
*
* Requires the {@link ngAnimate `ngAnimate`} module to be installed.
*
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
*
*/
return {
enter : function(element, parentElement, afterElement, doneCallback) {
this.enabled(false, element);
$delegate.enter(element, parentElement, afterElement);
$rootScope.$$postDigest(function() {
element = <API key>(element);
performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback);
});
},
leave : function(element, doneCallback) {
<API key>(element);
this.enabled(false, element);
$rootScope.$$postDigest(function() {
performAnimation('leave', 'ng-leave', <API key>(element), null, null, function() {
$delegate.leave(element);
}, doneCallback);
});
},
move : function(element, parentElement, afterElement, doneCallback) {
<API key>(element);
this.enabled(false, element);
$delegate.move(element, parentElement, afterElement);
$rootScope.$$postDigest(function() {
element = <API key>(element);
performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback);
});
},
addClass : function(element, className, doneCallback) {
element = <API key>(element);
performAnimation('addClass', className, element, null, null, function() {
$delegate.addClass(element, className);
}, doneCallback);
},
removeClass : function(element, className, doneCallback) {
element = <API key>(element);
performAnimation('removeClass', className, element, null, null, function() {
$delegate.removeClass(element, className);
}, doneCallback);
},
/**
*
* @ngdoc function
* @name $animate#setClass
* @function
* @description Adds and/or removes the given CSS classes to and from the element.
* Once complete, the done() callback will be fired (if provided).
* @param {DOMElement} element the element which will it's CSS classes changed
* removed from it
* @param {string} add the CSS classes which will be added to the element
* @param {string} remove the CSS class which will be removed from the element
* @param {Function=} done the callback function (if provided) that will be fired after the
* CSS classes have been set on the element
*/
setClass : function(element, add, remove, doneCallback) {
element = <API key>(element);
performAnimation('setClass', [add, remove], element, null, null, function() {
$delegate.setClass(element, add, remove);
}, doneCallback);
},
/**
* @ngdoc method
* @name $animate#enabled
* @function
*
* @param {boolean=} value If provided then set the animation on or off.
* @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation
* @return {boolean} Current animation state.
*
* @description
* Globally enables/disables animations.
*
*/
enabled : function(value, element) {
switch(arguments.length) {
case 2:
if(value) {
cleanup(element);
} else {
var data = element.data(NG_ANIMATE_STATE) || {};
data.disabled = true;
element.data(NG_ANIMATE_STATE, data);
}
break;
case 1:
rootAnimateState.disabled = !value;
break;
default:
value = !rootAnimateState.disabled;
break;
}
return !!value;
}
};
/*
all animations call this shared animation triggering function internally.
The animationEvent variable refers to the JavaScript animation event that will be triggered
and the className value is the name of the animation that will be applied within the
CSS code. Element, parentElement and afterElement are provided DOM elements for the animation
and the onComplete callback will be fired once the animation is fully complete.
*/
function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) {
var runner = animationRunner(element, animationEvent, className);
if(!runner) {
fireDOMOperation();
<API key>();
<API key>();
closeAnimation();
return;
}
className = runner.className;
var elementEvents = angular.element._data(runner.node);
elementEvents = elementEvents && elementEvents.events;
if (!parentElement) {
parentElement = afterElement ? afterElement.parent() : element.parent();
}
var ngAnimateState = element.data(NG_ANIMATE_STATE) || {};
var runningAnimations = ngAnimateState.active || {};
var <API key> = ngAnimateState.totalActive || 0;
var lastAnimation = ngAnimateState.last;
//only allow animations if the currently running animation is not structural
//or if there is no animation running at all
var skipAnimations = runner.isClassBased ?
ngAnimateState.disabled || (lastAnimation && !lastAnimation.isClassBased) :
false;
//skip the animation if animations are disabled, a parent is already being animated,
//the element is not currently attached to the document body or then completely close
//the animation if any matching animations are not found at all.
//NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.
if (skipAnimations || animationsDisabled(element, parentElement)) {
fireDOMOperation();
<API key>();
<API key>();
closeAnimation();
return;
}
var skipAnimation = false;
if(<API key> > 0) {
var animationsToCancel = [];
if(!runner.isClassBased) {
if(animationEvent == 'leave' && runningAnimations['ng-leave']) {
skipAnimation = true;
} else {
//cancel all animations when a structural animation takes place
for(var klass in runningAnimations) {
animationsToCancel.push(runningAnimations[klass]);
cleanup(element, klass);
}
runningAnimations = {};
<API key> = 0;
}
} else if(lastAnimation.event == 'setClass') {
animationsToCancel.push(lastAnimation);
cleanup(element, className);
}
else if(runningAnimations[className]) {
var current = runningAnimations[className];
if(current.event == animationEvent) {
skipAnimation = true;
} else {
animationsToCancel.push(current);
cleanup(element, className);
}
}
if(animationsToCancel.length > 0) {
forEach(animationsToCancel, function(operation) {
operation.cancel();
});
}
}
if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) {
skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR
}
if(skipAnimation) {
<API key>();
<API key>();
<API key>();
return;
}
if(animationEvent == 'leave') {
//there's no need to ever remove the listener since the element
//will be removed (destroyed) after the leave animation ends or
//is cancelled midway
element.one('$destroy', function(e) {
var element = angular.element(this);
var state = element.data(NG_ANIMATE_STATE);
if(state) {
var <API key> = state.active['ng-leave'];
if(<API key>) {
<API key>.cancel();
cleanup(element, 'ng-leave');
}
}
});
}
//the ng-animate class does nothing, but it's here to allow for
//parent animations to find and cancel child animations when needed
element.addClass(<API key>);
var localAnimationCount = <API key>++;
<API key>++;
runningAnimations[className] = runner;
element.data(NG_ANIMATE_STATE, {
last : runner,
active : runningAnimations,
index : localAnimationCount,
totalActive : <API key>
});
//first we run the before animations and when all of those are complete
//then we perform the DOM operation and run the next set of animations
<API key>();
runner.before(function(cancelled) {
var data = element.data(NG_ANIMATE_STATE);
cancelled = cancelled ||
!data || !data.active[className] ||
(runner.isClassBased && data.active[className].event != animationEvent);
fireDOMOperation();
if(cancelled === true) {
closeAnimation();
} else {
<API key>();
runner.after(closeAnimation);
}
});
function fireDOMCallback(animationPhase) {
var eventName = '$animate:' + animationPhase;
if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {
$$asyncCallback(function() {
element.triggerHandler(eventName, {
event : animationEvent,
className : className
});
});
}
}
function <API key>() {
fireDOMCallback('before');
}
function <API key>() {
fireDOMCallback('after');
}
function <API key>() {
fireDOMCallback('close');
if(doneCallback) {
$$asyncCallback(function() {
doneCallback();
});
}
}
//it is less complicated to use a flag than managing and canceling
//timeouts containing multiple callbacks.
function fireDOMOperation() {
if(!fireDOMOperation.hasBeenRun) {
fireDOMOperation.hasBeenRun = true;
domOperation();
}
}
function closeAnimation() {
if(!closeAnimation.hasBeenRun) {
closeAnimation.hasBeenRun = true;
var data = element.data(NG_ANIMATE_STATE);
if(data) {
/* only structural animations wait for reflow before removing an
animation, but class-based animations don't. An example of this
failing would be when a parent HTML tag has a ng-class attribute
causing ALL directives below to skip animations during the digest */
if(runner && runner.isClassBased) {
cleanup(element, className);
} else {
$$asyncCallback(function() {
var data = element.data(NG_ANIMATE_STATE) || {};
if(localAnimationCount == data.index) {
cleanup(element, className, animationEvent);
}
});
element.data(NG_ANIMATE_STATE, data);
}
}
<API key>();
}
}
}
function <API key>(element) {
var node = extractElementNode(element);
if (node) {
var nodes = angular.isFunction(node.<API key>) ?
node.<API key>(<API key>) :
node.querySelectorAll('.' + <API key>);
forEach(nodes, function(element) {
element = angular.element(element);
var data = element.data(NG_ANIMATE_STATE);
if(data && data.active) {
forEach(data.active, function(runner) {
runner.cancel();
});
}
});
}
}
function cleanup(element, className) {
if(isMatchingElement(element, $rootElement)) {
if(!rootAnimateState.disabled) {
rootAnimateState.running = false;
rootAnimateState.structural = false;
}
} else if(className) {
var data = element.data(NG_ANIMATE_STATE) || {};
var removeAnimations = className === true;
if(!removeAnimations && data.active && data.active[className]) {
data.totalActive
delete data.active[className];
}
if(removeAnimations || !data.totalActive) {
element.removeClass(<API key>);
element.removeData(NG_ANIMATE_STATE);
}
}
}
function animationsDisabled(element, parentElement) {
if (rootAnimateState.disabled) return true;
if(isMatchingElement(element, $rootElement)) {
return rootAnimateState.disabled || rootAnimateState.running;
}
do {
//the element did not reach the root element which means that it
//is not apart of the DOM. Therefore there is no reason to do
//any animations on it
if(parentElement.length === 0) break;
var isRoot = isMatchingElement(parentElement, $rootElement);
var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE);
var result = state && (!!state.disabled || state.running || state.totalActive > 0);
if(isRoot || result) {
return result;
}
if(isRoot) return true;
}
while(parentElement = parentElement.parent());
return true;
}
}]);
$animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',
function($window, $sniffer, $timeout, $$animateReflow) {
// Detect proper transitionend/animationend event names.
var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
// If unprefixed events are not supported but webkit-prefixed are, use the latter.
// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
// Note: Chrome implements `window.<API key>` and doesn't implement `window.onanimationend`
// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
// Register both events in case `window.onanimationend` is not supported because of that,
// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
// therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition
if (window.ontransitionend === undefined && window.<API key> !== undefined) {
CSS_PREFIX = '-webkit-';
TRANSITION_PROP = 'WebkitTransition';
TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
} else {
TRANSITION_PROP = 'transition';
TRANSITIONEND_EVENT = 'transitionend';
}
if (window.onanimationend === undefined && window.<API key> !== undefined) {
CSS_PREFIX = '-webkit-';
ANIMATION_PROP = 'WebkitAnimation';
ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
} else {
ANIMATION_PROP = 'animation';
ANIMATIONEND_EVENT = 'animationend';
}
var DURATION_KEY = 'Duration';
var PROPERTY_KEY = 'Property';
var DELAY_KEY = 'Delay';
var <API key> = 'IterationCount';
var <API key> = '$$ngAnimateKey';
var <API key> = '$$ngAnimateCSS3Data';
var <API key> = '<API key>';
var <API key> = 3;
var CLOSING_TIME_BUFFER = 1.5;
var ONE_SECOND = 1000;
var lookupCache = {};
var parentCounter = 0;
var <API key> = [];
var <API key>;
function afterReflow(element, callback) {
if(<API key>) {
<API key>();
}
<API key>.push(callback);
<API key> = $$animateReflow(function() {
forEach(<API key>, function(fn) {
fn();
});
<API key> = [];
<API key> = null;
lookupCache = {};
});
}
var closingTimer = null;
var closingTimestamp = 0;
var <API key> = [];
function <API key>(element, totalTime) {
var node = extractElementNode(element);
element = angular.element(node);
//this item will be garbage collected by the closing
//animation timeout
<API key>.push(element);
//but it may not need to cancel out the existing timeout
//if the timestamp is less than the previous one
var futureTimestamp = Date.now() + (totalTime * 1000);
if(futureTimestamp <= closingTimestamp) {
return;
}
$timeout.cancel(closingTimer);
closingTimestamp = futureTimestamp;
closingTimer = $timeout(function() {
closeAllAnimations(<API key>);
<API key> = [];
}, totalTime, false);
}
function closeAllAnimations(elements) {
forEach(elements, function(element) {
var elementData = element.data(<API key>);
if(elementData) {
(elementData.closeAnimationFn || noop)();
}
});
}
function <API key>(element, cacheKey) {
var data = cacheKey ? lookupCache[cacheKey] : null;
if(!data) {
var transitionDuration = 0;
var transitionDelay = 0;
var animationDuration = 0;
var animationDelay = 0;
var <API key>;
var animationDelayStyle;
var <API key>;
var <API key>;
//we want all the styles defined before and after
forEach(element, function(element) {
if (element.nodeType == ELEMENT_NODE) {
var elementStyles = $window.getComputedStyle(element) || {};
<API key> = elementStyles[TRANSITION_PROP + DURATION_KEY];
transitionDuration = Math.max(parseMaxTime(<API key>), transitionDuration);
<API key> = elementStyles[TRANSITION_PROP + PROPERTY_KEY];
<API key> = elementStyles[TRANSITION_PROP + DELAY_KEY];
transitionDelay = Math.max(parseMaxTime(<API key>), transitionDelay);
animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];
animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay);
var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);
if(aDuration > 0) {
aDuration *= parseInt(elementStyles[ANIMATION_PROP + <API key>], 10) || 1;
}
animationDuration = Math.max(aDuration, animationDuration);
}
});
data = {
total : 0,
<API key>: <API key>,
<API key>: <API key>,
<API key>: <API key>,
transitionDelay: transitionDelay,
transitionDuration: transitionDuration,
animationDelayStyle: animationDelayStyle,
animationDelay: animationDelay,
animationDuration: animationDuration
};
if(cacheKey) {
lookupCache[cacheKey] = data;
}
}
return data;
}
function parseMaxTime(str) {
var maxValue = 0;
var values = angular.isString(str) ?
str.split(/\s*,\s*/) :
[];
forEach(values, function(value) {
maxValue = Math.max(parseFloat(value) || 0, maxValue);
});
return maxValue;
}
function getCacheKey(element) {
var parentElement = element.parent();
var parentID = parentElement.data(<API key>);
if(!parentID) {
parentElement.data(<API key>, ++parentCounter);
parentID = parentCounter;
}
return parentID + '-' + extractElementNode(element).className;
}
function animateSetup(animationEvent, element, className, <API key>) {
var cacheKey = getCacheKey(element);
var eventCacheKey = cacheKey + ' ' + className;
var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;
var stagger = {};
if(itemIndex > 0) {
var staggerClassName = className + '-stagger';
var staggerCacheKey = cacheKey + ' ' + staggerClassName;
var applyClasses = !lookupCache[staggerCacheKey];
applyClasses && element.addClass(staggerClassName);
stagger = <API key>(element, staggerCacheKey);
applyClasses && element.removeClass(staggerClassName);
}
/* the animation itself may need to add/remove special CSS classes
* before calculating the anmation styles */
<API key> = <API key> ||
function(fn) { return fn(); };
element.addClass(className);
var formerData = element.data(<API key>) || {};
var timings = <API key>(function() {
return <API key>(element, eventCacheKey);
});
var transitionDuration = timings.transitionDuration;
var animationDuration = timings.animationDuration;
if(transitionDuration === 0 && animationDuration === 0) {
element.removeClass(className);
return false;
}
element.data(<API key>, {
running : formerData.running || 0,
itemIndex : itemIndex,
stagger : stagger,
timings : timings,
closeAnimationFn : noop
});
//temporarily disable the transition so that the enter styles
//don't animate twice (this is here to avoid a bug in Chrome/FF).
var <API key> = formerData.running > 0 || animationEvent == 'setClass';
if(transitionDuration > 0) {
blockTransitions(element, className, <API key>);
}
//staggering keyframe animations work by adjusting the `animation-delay` CSS property
//on the given element, however, the delay value can only calculated after the reflow
//since by that time $animate knows how many elements are being animated. Therefore,
//until the reflow occurs the element needs to be blocked (where the keyframe animation
//is set to `none 0s`). This blocking mechanism should only be set for when a stagger
//animation is detected and when the element item index is greater than 0.
if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) {
<API key>(element);
}
return true;
}
function <API key>(className) {
return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave';
}
function blockTransitions(element, className, isAnimating) {
if(<API key>(className) || !isAnimating) {
extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none';
} else {
element.addClass(<API key>);
}
}
function <API key>(element) {
extractElementNode(element).style[ANIMATION_PROP] = 'none 0s';
}
function unblockTransitions(element, className) {
var prop = TRANSITION_PROP + PROPERTY_KEY;
var node = extractElementNode(element);
if(node.style[prop] && node.style[prop].length > 0) {
node.style[prop] = '';
}
element.removeClass(<API key>);
}
function <API key>(element) {
var prop = ANIMATION_PROP;
var node = extractElementNode(element);
if(node.style[prop] && node.style[prop].length > 0) {
node.style[prop] = '';
}
}
function animateRun(animationEvent, element, className, <API key>) {
var node = extractElementNode(element);
var elementData = element.data(<API key>);
if(node.className.indexOf(className) == -1 || !elementData) {
<API key>();
return;
}
var activeClassName = '';
forEach(className.split(' '), function(klass, i) {
activeClassName += (i > 0 ? ' ' : '') + klass + '-active';
});
var stagger = elementData.stagger;
var timings = elementData.timings;
var itemIndex = elementData.itemIndex;
var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);
var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);
var maxDelayTime = maxDelay * ONE_SECOND;
var startTime = Date.now();
var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;
var style = '', appliedStyles = [];
if(timings.transitionDuration > 0) {
var propertyStyle = timings.<API key>;
if(propertyStyle.indexOf('all') == -1) {
style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';';
style += CSS_PREFIX + 'transition-duration: ' + timings.<API key> + ';';
appliedStyles.push(CSS_PREFIX + 'transition-property');
appliedStyles.push(CSS_PREFIX + 'transition-duration');
}
}
if(itemIndex > 0) {
if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {
var delayStyle = timings.<API key>;
style += CSS_PREFIX + 'transition-delay: ' +
prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; ';
appliedStyles.push(CSS_PREFIX + 'transition-delay');
}
if(stagger.animationDelay > 0 && stagger.animationDuration === 0) {
style += CSS_PREFIX + 'animation-delay: ' +
prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; ';
appliedStyles.push(CSS_PREFIX + 'animation-delay');
}
}
if(appliedStyles.length > 0) {
//the element being animated may sometimes contain comment nodes in
//the jqLite object, so we're safe to use a single variable to house
//the styles since there is always only one element being animated
var oldStyle = node.getAttribute('style') || '';
node.setAttribute('style', oldStyle + ' ' + style);
}
element.on(css3AnimationEvents, onAnimationProgress);
element.addClass(activeClassName);
elementData.closeAnimationFn = function() {
onEnd();
<API key>();
};
var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0);
var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;
var totalTime = (staggerTime + animationTime) * ONE_SECOND;
elementData.running++;
<API key>(element, totalTime);
return onEnd;
// This will automatically be called by $animate so
// there is no need to attach this internally to the
// timeout done method.
function onEnd(cancelled) {
element.off(css3AnimationEvents, onAnimationProgress);
element.removeClass(activeClassName);
animateClose(element, className);
var node = extractElementNode(element);
for (var i in appliedStyles) {
node.style.removeProperty(appliedStyles[i]);
}
}
function onAnimationProgress(event) {
event.stopPropagation();
var ev = event.originalEvent || event;
var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
/* Firefox (or possibly just Gecko) likes to not round values up
* when a ms measurement is used for the animation */
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(<API key>));
/* $manualTimeStamp is a mocked timeStamp value which is set
* within browserTrigger(). This is only here so that tests can
* mock animations properly. Real events fallback to event.timeStamp,
* or, if they don't, then a timeStamp is automatically created for them.
* We're checking to see if the timeStamp surpasses the expected delay,
* but we're using elapsedTime instead of the timeStamp on the 2nd
* pre-condition since animations sometimes close off early */
if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
<API key>();
}
}
}
function prepareStaggerDelay(delayStyle, staggerDelay, index) {
var style = '';
forEach(delayStyle.split(','), function(val, i) {
style += (i > 0 ? ',' : '') +
(index * staggerDelay + parseInt(val, 10)) + 's';
});
return style;
}
function animateBefore(animationEvent, element, className, <API key>) {
if(animateSetup(animationEvent, element, className, <API key>)) {
return function(cancelled) {
cancelled && animateClose(element, className);
};
}
}
function animateAfter(animationEvent, element, className, <API key>) {
if(element.data(<API key>)) {
return animateRun(animationEvent, element, className, <API key>);
} else {
animateClose(element, className);
<API key>();
}
}
function animate(animationEvent, element, className, animationComplete) {
//If the animateSetup function doesn't bother returning a
//cancellation function then it means that there is no animation
//to perform at all
var <API key> = animateBefore(animationEvent, element, className);
if(!<API key>) {
animationComplete();
return;
}
//There are two cancellation functions: one is before the first
//reflow animation and the second is during the active state
//animation. The first function will take care of removing the
//data from the element which will not make the 2nd animation
//happen in the first place
var cancel = <API key>;
afterReflow(element, function() {
unblockTransitions(element, className);
<API key>(element);
//once the reflow is complete then we point cancel to
//the new cancellation function which will remove all of the
//animation properties from the active animation
cancel = animateAfter(animationEvent, element, className, animationComplete);
});
return function(cancelled) {
(cancel || noop)(cancelled);
};
}
function animateClose(element, className) {
element.removeClass(className);
var data = element.data(<API key>);
if(data) {
if(data.running) {
data.running
}
if(!data.running || data.running === 0) {
element.removeData(<API key>);
}
}
}
return {
enter : function(element, animationCompleted) {
return animate('enter', element, 'ng-enter', animationCompleted);
},
leave : function(element, animationCompleted) {
return animate('leave', element, 'ng-leave', animationCompleted);
},
move : function(element, animationCompleted) {
return animate('move', element, 'ng-move', animationCompleted);
},
beforeSetClass : function(element, add, remove, animationCompleted) {
var className = suffixClasses(remove, '-remove') + ' ' +
suffixClasses(add, '-add');
var cancellationMethod = animateBefore('setClass', element, className, function(fn) {
var klass = element.attr('class');
element.removeClass(remove);
element.addClass(add);
var timings = fn();
element.attr('class', klass);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
<API key>(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
beforeAddClass : function(element, className, animationCompleted) {
var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) {
/* when a CSS class is added to an element then the transition style that
* is applied is the transition defined on the element when the CSS class
* is added at the time of the animation. This is how CSS3 functions
* outside of ngAnimate. */
element.addClass(className);
var timings = fn();
element.removeClass(className);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
<API key>(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
setClass : function(element, add, remove, animationCompleted) {
remove = suffixClasses(remove, '-remove');
add = suffixClasses(add, '-add');
var className = remove + ' ' + add;
return animateAfter('setClass', element, className, animationCompleted);
},
addClass : function(element, className, animationCompleted) {
return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted);
},
beforeRemoveClass : function(element, className, animationCompleted) {
var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) {
var klass = element.attr('class');
element.removeClass(className);
var timings = fn();
element.attr('class', klass);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
<API key>(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
removeClass : function(element, className, animationCompleted) {
return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted);
}
};
function suffixClasses(classes, suffix) {
var className = '';
classes = angular.isArray(classes) ? classes : classes.split(/\s+/);
forEach(classes, function(klass, i) {
if(klass && klass.length > 0) {
className += (i > 0 ? ' ' : '') + klass + suffix;
}
});
return className;
}
}]);
}]);
})(window, window.angular);
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def <API key>(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(<API key>(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def <API key>(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def <API key>(text):
return <API key>(text)
def <API key>(text):
return <API key>(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
<API key>(data)))
if __name__ == "__main__":
sys.exit(main())
|
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <security/smac/smac.h>
#include <fs/vfs.h>
#include <fs/fsop.h>
#include <fs/flags.h>
#include <kernel/task.h>
#include <sys/xattr.h>
#include <embox/test.h>
#include <kernel/task/resource/security.h>
EMBOX_TEST_SUITE("smac tests with classic modes allows all access");
TEST_SETUP_SUITE(setup_suite);
TEST_TEARDOWN(clear_id);
TEST_TEARDOWN_SUITE(teardown_suite);
#define FS_NAME "ext2"
#define FS_DEV "/dev/hda"
#define FS_DIR "/tmp"
#define FILE_H "/tmp/file_high"
#define FILE_L "/tmp/file_low"
#define HIGH "high_label"
#define LOW "low_label"
static const char *high_static = HIGH;
static const char *low_static = LOW;
static const char *smac_star = "*";
#define SMAC_BACKUP_LEN 1024
static char buf[SMAC_BACKUP_LEN];
static struct smac_env *backup;
static struct smac_env test_env = {
.n = 2,
.entries = {
{HIGH, LOW, FS_MAY_READ },
{LOW, HIGH, FS_MAY_WRITE},
},
};
static mode_t root_backup_mode;
static int setup_suite(void) {
int res;
if (0 != (res = smac_getenv(buf, SMAC_BACKUP_LEN, &backup))) {
return res;
}
if (0 != (res = smac_setenv(&test_env))) {
return res;
}
root_backup_mode = vfs_get_root()->mode;
vfs_get_root()->mode = S_IFDIR | 0777;
if ((res = mount(FS_DEV, FS_DIR, FS_NAME))) {
return res;
}
return 0;
}
static int teardown_suite(void) {
// int res;
vfs_get_root()->mode = root_backup_mode;
return smac_setenv(backup);
}
static int clear_id(void) {
struct smac_task *smac_task = (struct smac_task *) <API key>();
strcpy(smac_task->label, "smac_admin");
return 0;
}
TEST_CASE("Low subject shouldn't read high object") {
int fd;
smac_labelset(low_static);
test_assert_equal(-1, fd = open(FILE_H, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_H, O_RDONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject shouldn't write low object") {
int fd;
smac_labelset(high_static);
test_assert_equal(-1, fd = open(FILE_L, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_L, O_WRONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject should be able r/w high object") {
int fd;
smac_labelset(high_static);
<API key>(-1, fd = open(FILE_H, O_RDWR));
close(fd);
}
TEST_CASE("Low subject should be able r/w low object") {
int fd;
smac_labelset(low_static);
<API key>(-1, fd = open(FILE_L, O_RDWR));
close(fd);
}
TEST_CASE("High subject shouldn't be able change high object label") {
smac_labelset(high_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("Low subject shouldn't be able change high object label") {
smac_labelset(low_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("smac admin should be able change high object label") {
smac_labelset(smac_admin);
test_assert_zero(setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_zero(setxattr(FILE_H, smac_xattrkey, high_static,
strlen(high_static), 0));
}
|
package adf.launcher.connect;
import adf.agent.office.OfficeAmbulance;
import adf.control.ControlAmbulance;
import adf.launcher.AbstractLoader;
import adf.launcher.ConfigKey;
import rescuecore2.components.<API key>;
import rescuecore2.components.ComponentLauncher;
import rescuecore2.config.Config;
import rescuecore2.connection.ConnectionException;
public class <API key> implements Connector
{
@Override
public void connect(ComponentLauncher launcher, Config config, AbstractLoader loader)
{
int count = config.getIntValue(ConfigKey.<API key>, 0);
int connected = 0;
if (count == 0)
{
return;
}
/*
String classStr = config.getValue(ConfigKey.<API key>);
if (classStr == null)
{
System.out.println("[ERROR] Cannot Load AmbulanceCentre Control !!");
return;
}
System.out.println("[START] Connect AmbulanceCentre (teamName:" + classStr + ")");
System.out.println("[INFO ] Load AmbulanceCentre (teamName:" + classStr + ")");
*/
try
{
if (loader.getControlAmbulance() == null)
{
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
return;
}
for (int i = 0; i != count; ++i)
{
ControlAmbulance controlAmbulance = loader.getControlAmbulance();
boolean isPrecompute = config.getBooleanValue(ConfigKey.KEY_PRECOMPUTE, false);
launcher.connect(new OfficeAmbulance(controlAmbulance, isPrecompute));
//System.out.println(name);
connected++;
}
}
catch (<API key> | <API key> | ConnectionException e)
{
//e.printStackTrace();
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
}
System.out.println("[FINISH] Connect AmbulanceCentre (success:" + connected + ")");
}
}
|
<div ui-content-for="title">
<span>Detectors</span>
</div>
<div class="scrollable">
<div class="scrollable-content" ui-scroll-bottom="bottomReached()">
<div class="list-group">
|
class SwiProlog < Formula
desc "ISO/Edinburgh-style Prolog interpreter"
homepage "http:
url "http:
sha256 "<SHA256-like>"
bottle do
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
sha256 "<SHA256-like>" => :el_capitan
sha256 "<SHA256-like>" => :yosemite
end
devel do
url "http:
sha256 "<SHA256-like>"
end
head do
url "https://github.com/SWI-Prolog/swipl-devel.git"
depends_on "autoconf" => :build
end
option "with-lite", "Disable all packages"
option "with-jpl", "Enable JPL (Java Prolog Bridge)"
option "with-xpce", "Enable XPCE (Prolog Native GUI Library)"
deprecated_option "lite" => "with-lite"
depends_on "pkg-config" => :build
depends_on "readline"
depends_on "gmp"
depends_on "openssl"
depends_on "libarchive" => :optional
if build.with? "xpce"
depends_on :x11
depends_on "jpeg"
end
def install
if build.with? "libarchive"
ENV["ARPREFIX"] = Formula["libarchive"].opt_prefix
else
ENV.append "DISABLE_PKGS", "archive"
end
args = ["--prefix=#{libexec}", "--mandir=#{man}"]
ENV.append "DISABLE_PKGS", "jpl" if build.without? "jpl"
ENV.append "DISABLE_PKGS", "xpce" if build.without? "xpce"
# SWI-Prolog's Makefiles don't add CPPFLAGS to the compile command, but do
# include CIFLAGS. Setting it here. Also, they clobber CFLAGS, so including
# the Homebrew-generated CFLAGS into COFLAGS here.
ENV["CIFLAGS"] = ENV.cppflags
ENV["COFLAGS"] = ENV.cflags
# Build the packages unless --with-lite option specified
args << "--with-world" if build.without? "lite"
# './prepare' prompts the user to build documentation
# (which requires other modules). '3' is the option
# to ignore documentation.
system "echo 3 | ./prepare" if build.head?
system "./configure", *args
system "make"
system "make", "install"
|
// Authors:
// Thomas Wiest (twiest@novell.com)
// Rusty Howell (rhowell@novell.com)
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Management.Internal
{
internal class CimTable
{
public CimTable()
{
throw new Exception("Not yet implemented");
}
}
}
|
# Autogenerated by Thrift Compiler (0.8.0)
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
require 5.6.0;
use strict;
use warnings;
use Thrift;
use EDAMUserStore::Types;
# HELPER FUNCTIONS AND STRUCTURES
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( clientName edamVersionMajor edamVersionMinor ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{clientName} = undef;
$self->{edamVersionMajor} = 1;
$self->{edamVersionMinor} = 21;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{clientName}) {
$self->{clientName} = $vals->{clientName};
}
if (defined $vals->{edamVersionMajor}) {
$self->{edamVersionMajor} = $vals->{edamVersionMajor};
}
if (defined $vals->{edamVersionMinor}) {
$self->{edamVersionMinor} = $vals->{edamVersionMinor};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{clientName});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::I16) {
$xfer += $input->readI16(\$self->{edamVersionMajor});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::I16) {
$xfer += $input->readI16(\$self->{edamVersionMinor});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{clientName}) {
$xfer += $output->writeFieldBegin('clientName', TType::STRING, 1);
$xfer += $output->writeString($self->{clientName});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{edamVersionMajor}) {
$xfer += $output->writeFieldBegin('edamVersionMajor', TType::I16, 2);
$xfer += $output->writeI16($self->{edamVersionMajor});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{edamVersionMinor}) {
$xfer += $output->writeFieldBegin('edamVersionMinor', TType::I16, 3);
$xfer += $output->writeI16($self->{edamVersionMinor});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::BOOL) {
$xfer += $input->readBool(\$self->{success});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::BOOL, 0);
$xfer += $output->writeBool($self->{success});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( locale ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{locale} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{locale}) {
$self->{locale} = $vals->{locale};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{locale});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{locale}) {
$xfer += $output->writeFieldBegin('locale', TType::STRING, 1);
$xfer += $output->writeString($self->{locale});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::BootstrapInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( username password consumerKey consumerSecret ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{username} = undef;
$self->{password} = undef;
$self->{consumerKey} = undef;
$self->{consumerSecret} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{username}) {
$self->{username} = $vals->{username};
}
if (defined $vals->{password}) {
$self->{password} = $vals->{password};
}
if (defined $vals->{consumerKey}) {
$self->{consumerKey} = $vals->{consumerKey};
}
if (defined $vals->{consumerSecret}) {
$self->{consumerSecret} = $vals->{consumerSecret};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{username});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{password});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{consumerKey});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^4$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{consumerSecret});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{username}) {
$xfer += $output->writeFieldBegin('username', TType::STRING, 1);
$xfer += $output->writeString($self->{username});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{password}) {
$xfer += $output->writeFieldBegin('password', TType::STRING, 2);
$xfer += $output->writeString($self->{password});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{consumerKey}) {
$xfer += $output->writeFieldBegin('consumerKey', TType::STRING, 3);
$xfer += $output->writeString($self->{consumerKey});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{consumerSecret}) {
$xfer += $output->writeFieldBegin('consumerSecret', TType::STRING, 4);
$xfer += $output->writeString($self->{consumerSecret});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_<API key>>mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::<API key>();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_refresh<API key>>mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_refresh<API key>;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_refresh<API key>>mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_refresh<API key>;
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::<API key>();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_refresh<API key>);
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMTypes::User();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( username ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{username} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{username}) {
$self->{username} = $vals->{username};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{username});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{username}) {
$xfer += $output->writeFieldBegin('username', TType::STRING, 1);
$xfer += $output->writeString($self->{username});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{notFoundException} = undef;
$self->{systemException} = undef;
$self->{userException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{notFoundException}) {
$self->{notFoundException} = $vals->{notFoundException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::PublicUserInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{notFoundException} = new EDAMErrors::<API key>();
$xfer += $self->{notFoundException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{notFoundException}) {
$xfer += $output->writeFieldBegin('notFoundException', TType::STRUCT, 1);
$xfer += $self->{notFoundException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 3);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::PremiumInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::<API key>;
use base qw(Class::Accessor);
EDAMUserStore::<API key>->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return '<API key>';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{success});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('<API key>');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($self->{success});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStoreIf;
use strict;
sub checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
die 'implement interface';
}
sub getBootstrapInfo{
my $self = shift;
my $locale = shift;
die 'implement interface';
}
sub authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
die 'implement interface';
}
sub <API key>{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getUser{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getPublicUserInfo{
my $self = shift;
my $username = shift;
die 'implement interface';
}
sub getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getNoteStoreUrl{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
package EDAMUserStore::UserStoreRest;
use strict;
sub new {
my ($classname, $impl) = @_;
my $self ={ impl => $impl };
return bless($self,$classname);
}
sub checkVersion{
my ($self, $request) = @_;
my $clientName = ($request->{'clientName'}) ? $request->{'clientName'} : undef;
my $edamVersionMajor = ($request->{'edamVersionMajor'}) ? $request->{'edamVersionMajor'} : undef;
my $edamVersionMinor = ($request->{'edamVersionMinor'}) ? $request->{'edamVersionMinor'} : undef;
return $self->{impl}->checkVersion($clientName, $edamVersionMajor, $edamVersionMinor);
}
sub getBootstrapInfo{
my ($self, $request) = @_;
my $locale = ($request->{'locale'}) ? $request->{'locale'} : undef;
return $self->{impl}->getBootstrapInfo($locale);
}
sub authenticate{
my ($self, $request) = @_;
my $username = ($request->{'username'}) ? $request->{'username'} : undef;
my $password = ($request->{'password'}) ? $request->{'password'} : undef;
my $consumerKey = ($request->{'consumerKey'}) ? $request->{'consumerKey'} : undef;
my $consumerSecret = ($request->{'consumerSecret'}) ? $request->{'consumerSecret'} : undef;
return $self->{impl}->authenticate($username, $password, $consumerKey, $consumerSecret);
}
sub <API key>{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}-><API key>($authenticationToken);
}
sub getUser{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getUser($authenticationToken);
}
sub getPublicUserInfo{
my ($self, $request) = @_;
my $username = ($request->{'username'}) ? $request->{'username'} : undef;
return $self->{impl}->getPublicUserInfo($username);
}
sub getPremiumInfo{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getPremiumInfo($authenticationToken);
}
sub getNoteStoreUrl{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getNoteStoreUrl($authenticationToken);
}
package EDAMUserStore::UserStoreClient;
use base qw(EDAMUserStore::UserStoreIf);
sub new {
my ($classname, $input, $output) = @_;
my $self = {};
$self->{input} = $input;
$self->{output} = defined $output ? $output : $input;
$self->{seqid} = 0;
return bless($self,$classname);
}
sub checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
$self->send_checkVersion($clientName, $edamVersionMajor, $edamVersionMinor);
return $self->recv_checkVersion();
}
sub send_checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
$self->{output}->writeMessageBegin('checkVersion', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{clientName} = $clientName;
$args->{edamVersionMajor} = $edamVersionMajor;
$args->{edamVersionMinor} = $edamVersionMinor;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_checkVersion{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
die "checkVersion failed: unknown result";
}
sub getBootstrapInfo{
my $self = shift;
my $locale = shift;
$self-><API key>($locale);
return $self-><API key>();
}
sub <API key>{
my $self = shift;
my $locale = shift;
$self->{output}->writeMessageBegin('getBootstrapInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{locale} = $locale;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub <API key>{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
die "getBootstrapInfo failed: unknown result";
}
sub authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
$self->send_authenticate($username, $password, $consumerKey, $consumerSecret);
return $self->recv_authenticate();
}
sub send_authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
$self->{output}->writeMessageBegin('authenticate', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{username} = $username;
$args->{password} = $password;
$args->{consumerKey} = $consumerKey;
$args->{consumerSecret} = $consumerSecret;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_authenticate{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "authenticate failed: unknown result";
}
sub <API key>{
my $self = shift;
my $authenticationToken = shift;
$self-><API key>($authenticationToken);
return $self-><API key>();
}
sub <API key>{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('<API key>', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub <API key>{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_refresh<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "<API key> failed: unknown result";
}
sub getUser{
my $self = shift;
my $authenticationToken = shift;
$self->send_getUser($authenticationToken);
return $self->recv_getUser();
}
sub send_getUser{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getUser', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getUser{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getUser failed: unknown result";
}
sub getPublicUserInfo{
my $self = shift;
my $username = shift;
$self-><API key>($username);
return $self-><API key>();
}
sub <API key>{
my $self = shift;
my $username = shift;
$self->{output}->writeMessageBegin('getPublicUserInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{username} = $username;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub <API key>{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{notFoundException}) {
die $result->{notFoundException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
if (defined $result->{userException}) {
die $result->{userException};
}
die "getPublicUserInfo failed: unknown result";
}
sub getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
$self->send_getPremiumInfo($authenticationToken);
return $self->recv_getPremiumInfo();
}
sub send_getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getPremiumInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getPremiumInfo{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getPremiumInfo failed: unknown result";
}
sub getNoteStoreUrl{
my $self = shift;
my $authenticationToken = shift;
$self-><API key>($authenticationToken);
return $self-><API key>();
}
sub <API key>{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getNoteStoreUrl', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::<API key>();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub <API key>{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new <API key>();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::<API key>();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getNoteStoreUrl failed: unknown result";
}
package EDAMUserStore::UserStoreProcessor;
use strict;
sub new {
my ($classname, $handler) = @_;
my $self = {};
$self->{handler} = $handler;
return bless ($self, $classname);
}
sub process {
my ($self, $input, $output) = @_;
my $rseqid = 0;
my $fname = undef;
my $mtype = 0;
$input->readMessageBegin(\$fname, \$mtype, \$rseqid);
my $methodname = 'process_'.$fname;
if (!$self->can($methodname)) {
$input->skip(TType::STRUCT);
$input->readMessageEnd();
my $x = new <API key>('Function '.$fname.' not implemented.', <API key>::UNKNOWN_METHOD);
$output->writeMessageBegin($fname, TMessageType::EXCEPTION, $rseqid);
$x->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
return;
}
$self->$methodname($rseqid, $input, $output);
return 1;
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
$result->{success} = $self->{handler}->checkVersion($args->clientName, $args->edamVersionMajor, $args->edamVersionMinor);
$output->writeMessageBegin('checkVersion', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
$result->{success} = $self->{handler}->getBootstrapInfo($args->locale);
$output->writeMessageBegin('getBootstrapInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
eval {
$result->{success} = $self->{handler}->authenticate($args->username, $args->password, $args->consumerKey, $args->consumerSecret);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('authenticate', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_refresh<API key>();
eval {
$result->{success} = $self->{handler}-><API key>($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('<API key>', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getUser {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
eval {
$result->{success} = $self->{handler}->getUser($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getUser', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
eval {
$result->{success} = $self->{handler}->getPublicUserInfo($args->username);
}; if( UNIVERSAL::isa($@,'EDAMErrors::<API key>') ){
$result->{notFoundException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}
$output->writeMessageBegin('getPublicUserInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
eval {
$result->{success} = $self->{handler}->getPremiumInfo($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getPremiumInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub <API key> {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::<API key>();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::<API key>();
eval {
$result->{success} = $self->{handler}->getNoteStoreUrl($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getNoteStoreUrl', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
1;
|
require "language/haskell"
class Ghc < Formula
include Language::Haskell::Cabal
desc "Glorious Glasgow Haskell Compilation System"
homepage "https://haskell.org/ghc/"
url "https://downloads.haskell.org/~ghc/8.6.3/ghc-8.6.3-src.tar.xz"
sha256 "<SHA256-like>"
bottle do
sha256 "<SHA256-like>" => :mojave
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
end
head do
url "https://git.haskell.org/ghc.git", :branch => "ghc-8.6"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
resource "cabal" do
url "https://hackage.haskell.org/package/cabal-install-2.4.0.0/cabal-install-2.4.0.0.tar.gz"
sha256 "<SHA256-like>"
end
end
depends_on "python" => :build
depends_on "sphinx-doc" => :build
resource "gmp" do
url "https://ftp.gnu.org/gnu/gmp/gmp-6.1.2.tar.xz"
mirror "https://gmplib.org/download/gmp/gmp-6.1.2.tar.xz"
mirror "https://ftpmirror.gnu.org/gmp/gmp-6.1.2.tar.xz"
sha256 "<SHA256-like>"
end
# "This is a distribution for Mac OS X, 10.7 or later."
resource "binary" do
url "https://downloads.haskell.org/~ghc/8.4.4/ghc-8.4.<API key>.tar.xz"
sha256 "<SHA256-like>"
end
def install
ENV["CC"] = ENV.cc
ENV["LD"] = "ld"
# Build a static gmp rather than in-tree gmp, otherwise all ghc-compiled
# executables link to Homebrew's GMP.
gmp = libexec/"integer-gmp"
# GMP *does not* use PIC by default without shared libs so --with-pic
resource("gmp").stage do
system "./configure", "--prefix=#{gmp}", "--with-pic", "--disable-shared",
"--build=#{Hardware.oldest_cpu}-apple-darwin#{`uname -r`.to_i}"
system "make"
system "make", "check"
system "make", "install"
end
args = ["--with-gmp-includes=#{gmp}/include",
"--with-gmp-libraries=#{gmp}/lib"]
# As of Xcode 7.3 (and the corresponding CLT) `nm` is a symlink to `llvm-nm`
# and the old `nm` is renamed `nm-classic`. Building with the new `nm`, a
# segfault occurs with the following error:
# make[1]: * [compiler/stage2/dll-split.stamp] Segmentation fault: 11
# Upstream is aware of the issue and is recommending the use of nm-classic
# until Apple restores POSIX compliance:
# LLVM itself has already fixed the bug: llvm-mirror/llvm@ae7cf585
# rdar://25311883 and rdar://25299678
if DevelopmentTools.clang_build_version >= 703 && DevelopmentTools.clang_build_version < 800
args << "--with-nm=#{`xcrun --find nm-classic`.chomp}"
end
resource("binary").stage do
binary = buildpath/"binary"
system "./configure", "--prefix=#{binary}", *args
ENV.deparallelize { system "make", "install" }
ENV.prepend_path "PATH", binary/"bin"
end
if build.head?
resource("cabal").stage do
system "sh", "bootstrap.sh", "--sandbox"
(buildpath/"bootstrap-tools/bin").install ".cabal-sandbox/bin/cabal"
end
ENV.prepend_path "PATH", buildpath/"bootstrap-tools/bin"
cabal_sandbox do
cabal_install "--only-dependencies", "happy", "alex"
cabal_install "--prefix=#{buildpath}/bootstrap-tools", "happy", "alex"
end
system "./boot"
end
system "./configure", "--prefix=#{prefix}", *args
system "make"
ENV.deparallelize { system "make", "install" }
Dir.glob(lib/"*/package.conf.d/package.cache") { |f| rm f }
end
def post_install
system "#{bin}/ghc-pkg", "recache"
end
test do
(testpath/"hello.hs").write('main = putStrLn "Hello Homebrew"')
system "#{bin}/runghc", testpath/"hello.hs"
end
end
|
using System;
using System.Text;
using Microsoft.Extensions.Configuration;
using NLog.Common;
using NLog.Config;
using NLog.LayoutRenderers;
namespace NLog.Extensions.Logging
{
<summary>
Layout renderer that can lookup values from Microsoft Extension Configuration Container (json, xml, ini)
</summary>
<remarks>Not to be confused with NLog.AppConfig that includes ${appsetting}</remarks>
<example>
Example: appsettings.json
{
"Mode":"Prod",
"Options":{
"<API key>":"<API key>=true",
}
}
Config Setting Lookup:
${configsetting:name=Mode} = "Prod"
${configsetting:name=Options.<API key>} = "<API key>=true"
${configsetting:name=Options.TableName:default=MyTable} = "MyTable"
Config Setting Lookup Cached:
${configsetting:cached=True:name=Mode}
</example>
[LayoutRenderer("configsetting")]
[ThreadAgnostic]
[ThreadSafe]
public class <API key> : LayoutRenderer
{
<summary>
Global Configuration Container
</summary>
public static IConfiguration <API key> { get; set; }
<summary>
Item in the setting container
</summary>
[RequiredParameter]
[DefaultParameter]
public string Item
{
get => _item;
set
{
_item = value;
_itemLookup = value?.Replace(".", ":");
}
}
private string _item;
private string _itemLookup;
<summary>
Name of the Item
</summary>
[Obsolete("Replaced by Item-property")]
public string Name { get => Item; set => Item = value; }
<summary>
The default value to render if the setting value is null.
</summary>
public string Default { get; set; }
<inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (string.IsNullOrEmpty(_itemLookup))
return;
string value = null;
var configurationRoot = <API key>;
if (configurationRoot != null)
{
value = configurationRoot[_itemLookup];
}
else
{
#if NETCORE1_0
InternalLogger.Debug("Missing <API key>. Remember to provide IConfiguration when calling AddNLog");
#else
InternalLogger.Debug("Missing <API key>. Remember to register IConfiguration by calling UseNLog");
#endif
}
builder.Append(value ?? Default);
}
}
}
|
# pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, <API key>, SimTypeBottom, SimUnion, SimTypeBool
from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64
from .. import SIM_PROCEDURES as P
from . import SimLibrary
_l = logging.getLogger(name=__name__)
lib = SimLibrary()
lib.set_default_cc('X86', SimCCStdcall)
lib.set_default_cc('AMD64', SimCCMicrosoftAMD64)
lib.set_library_names("aclui.dll")
prototypes = \
{
'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="<API key>")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]),
'EditSecurity': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="<API key>")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]),
'<API key>': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="<API key>"), SimTypeInt(signed=False, label="SI_PAGE_TYPE")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi", "uSIPage"]),
}
lib.set_prototypes(prototypes)
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>RMedia.GetOffset</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body bgcolor="#ffffff">
<table border="0" width="100%" bgcolor="#F0F0FF">
<tr>
<td>Concept Framework 2.2 documentation</td>
<td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td>
</tr>
</table>
<h2><a href="RMedia.html">RMedia</a>.GetOffset</h2>
<table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr bgcolor="#f0f0f0">
<td><i>Name</i></td>
<td><i>Type</i></td>
<td><i>Access</i></td>
<td><i>Version</i></td>
<td><i>Deprecated</i></td>
</tr>
<tr bgcolor="#fafafa">
<td><b>GetOffset</b></td>
<td>function</td>
<td>public</td>
<td>version 1</td>
<td>no</td>
</tr>
</table>
<br />
<b>Prototype:</b><br />
<table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>public function GetOffset()</b></td></tr></table>
<br />
<br />
<b>Description:</b><br />
<table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr><td>
TODO: Document this
</td></tr>
</table>
<br />
<b>Returns:</b><br />
// TO DO
<br />
<br />
<!
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http:
alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" border="0"/>
</a>
</p>
<table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Devronium Autodocumenter Alpha, generation time: Sun Jan 27 18:15:28 2013
GMT</td><td align="right">(c)2013 <a href="http:
</body>
</html>
|
require_relative 'model'
Record.where(version: 10606).delete_all
|
# -*- coding: utf-8 -*-
"""
femagtools.plot
~~~~~~~~~~~~
Creating plots
"""
import numpy as np
import scipy.interpolate as ip
import logging
try:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
matplotlibversion = matplotlib.__version__
except ImportError: # ModuleNotFoundError:
matplotlibversion = 0
logger = logging.getLogger("femagtools.plot")
def _create_3d_axis():
"""creates a subplot with 3d projection if one does not already exist"""
from matplotlib.projections import <API key>
from matplotlib import _pylab_helpers
create_axis = True
if _pylab_helpers.Gcf.get_active() is not None:
if isinstance(plt.gca(), <API key>('3d')):
create_axis = False
if create_axis:
plt.figure()
plt.subplot(111, projection='3d')
def _plot_surface(ax, x, y, z, labels, azim=None):
"""helper function for surface plots"""
# ax.tick_params(axis='both', which='major', pad=-3)
assert np.size(x) > 1 and np.size(y) > 1 and np.size(z) > 1
if azim is not None:
ax.azim = azim
X, Y = np.meshgrid(x, y)
Z = np.ma.masked_invalid(z)
ax.plot_surface(X, Y, Z,
rstride=1, cstride=1,
cmap=cm.viridis, alpha=0.85,
vmin=np.nanmin(z), vmax=np.nanmax(z),
linewidth=0, antialiased=True)
# edgecolor=(0, 0, 0, 0))
# ax.set_xticks(xticks)
# ax.set_yticks(yticks)
# ax.set_zticks(zticks)
ax.set_xlabel(labels[0])
ax.set_ylabel(labels[1])
ax.set_title(labels[2])
# plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
def __phasor_plot(ax, up, idq, uxdq):
uref = max(up, uxdq[0])
uxd = uxdq[0]/uref
uxq = uxdq[1]/uref
u1d, u1q = (uxd, 1+uxq)
u1 = np.sqrt(u1d**2 + u1q**2)*uref
i1 = np.linalg.norm(idq)
i1d, i1q = (idq[0]/i1, idq[1]/i1)
qhw = 6 # width arrow head
qhl = 15 # length arrow head
qlw = 2 # line width
qts = 10 # textsize
# Length of the Current adjust to Ud: Initally 0.9, Maier(Oswald) = 0.5
curfac = max(0.9, 1.5*i1q/up)
def label_line(ax, X, Y, U, V, label, color='k', size=8):
x1, x2 = X, X + U
y1, y2 = Y, Y + V
if y2 == 0:
y2 = y1
if x2 == 0:
x2 = x1
x = (x1 + x2) / 2
y = (y1 + y2) / 2
slope_degrees = np.rad2deg(np.angle(U + V * 1j))
if slope_degrees < 0:
slope_degrees += 180
if 90 < slope_degrees <= 270:
slope_degrees += 180
x_offset = np.sin(np.deg2rad(slope_degrees))
y_offset = np.cos(np.deg2rad(slope_degrees))
bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0)
text = ax.annotate(label, xy=(x, y), xytext=(x_offset * 10, y_offset * 8),
textcoords='offset points',
size=size, color=color,
horizontalalignment='center',
verticalalignment='center',
fontfamily='monospace', fontweight='bold', bbox=bbox_props)
text.set_rotation(slope_degrees)
return text
if ax == 0:
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
# ax.set_aspect('equal')
ax.set_title(
r'$U_1$={0} V, $I_1$={1} A, $U_p$={2} V'.format(
round(u1, 1), round(i1, 1), round(up, 1)), fontsize=14)
up /= uref
ax.quiver(0, 0, 0, up, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw/2, headlength=qhl/2, headaxislength=qhl/2, width=qlw*2, color='k')
label_line(ax, 0, 0, 0, up, '$U_p$', 'k', qts)
ax.quiver(0, 0, u1d, u1q, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='r')
label_line(ax, 0, 0, u1d, u1q, '$U_1$', 'r', qts)
ax.quiver(0, 1, uxd, 0, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g')
label_line(ax, 0, 1, uxd, 0, '$U_d$', 'g', qts)
ax.quiver(uxd, 1, 0, uxq, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g')
label_line(ax, uxd, 1, 0, uxq, '$U_q$', 'g', qts)
ax.quiver(0, 0, curfac*i1d, curfac*i1q, angles='xy', scale_units='xy', scale=1,
units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='b')
label_line(ax, 0, 0, curfac*i1d, curfac*i1q, '$I_1$', 'b', qts)
xmin, xmax = (min(0, uxd, i1d), max(0, i1d, uxd))
ymin, ymax = (min(0, i1q, 1-uxq), max(1, i1q, 1+uxq))
ax.set_xlim([xmin-0.1, xmax+0.1])
ax.set_ylim([ymin-0.1, ymax+0.1])
ax.grid(True)
def i1beta_phasor(up, i1, beta, r1, xd, xq, ax=0):
"""creates a phasor plot
up: internal voltage
i1: current
beta: angle i1 vs up [deg]
r1: resistance
xd: reactance in direct axis
xq: reactance in quadrature axis"""
i1d, i1q = (i1*np.sin(beta/180*np.pi), i1*np.cos(beta/180*np.pi))
uxdq = ((r1*i1d - xq*i1q), (r1*i1q + xd*i1d))
__phasor_plot(ax, up, (i1d, i1q), uxdq)
def iqd_phasor(up, iqd, uqd, ax=0):
"""creates a phasor plot
up: internal voltage
iqd: current
uqd: terminal voltage"""
uxdq = (uqd[1]/np.sqrt(2), (uqd[0]/np.sqrt(2)-up))
__phasor_plot(ax, up, (iqd[1]/np.sqrt(2), iqd[0]/np.sqrt(2)), uxdq)
def phasor(bch, ax=0):
"""create phasor plot from bch"""
f1 = bch.machine['p']*bch.dqPar['speed']
w1 = 2*np.pi*f1
xd = w1*bch.dqPar['ld'][-1]
xq = w1*bch.dqPar['lq'][-1]
r1 = bch.machine['r1']
i1beta_phasor(bch.dqPar['up'][-1],
bch.dqPar['i1'][-1], bch.dqPar['beta'][-1],
r1, xd, xq, ax)
def airgap(airgap, ax=0):
"""creates plot of flux density in airgap"""
if ax == 0:
ax = plt.gca()
ax.set_title('Airgap Flux Density [T]')
ax.plot(airgap['pos'], airgap['B'],
label='Max {:4.2f} T'.format(max(airgap['B'])))
ax.plot(airgap['pos'], airgap['B_fft'],
label='Base Ampl {:4.2f} T'.format(airgap['Bamp']))
ax.set_xlabel('Position/°')
ax.legend()
ax.grid(True)
def airgap_fft(airgap, bmin=1e-2, ax=0):
"""plot airgap harmonics"""
unit = 'T'
if ax == 0:
ax = plt.gca()
ax.set_title('Airgap Flux Density Harmonics / {}'.format(unit))
ax.grid(True)
order, fluxdens = np.array([(n, b) for n, b in zip(airgap['nue'],
airgap['B_nue']) if b > bmin]).T
try:
markerline1, stemlines1, _ = ax.stem(order, fluxdens, '-.', basefmt=" ",
use_line_collection=True)
ax.set_xticks(order)
except ValueError: # empty sequence
pass
def torque(pos, torque, ax=0):
"""creates plot from torque vs position"""
k = 20
alpha = np.linspace(pos[0], pos[-1],
k*len(torque))
f = ip.interp1d(pos, torque, kind='quadratic')
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if ax == 0:
ax = plt.gca()
ax.set_title('Torque / {}'.format(unit))
ax.grid(True)
ax.plot(pos, [scale*t for t in torque], 'go')
ax.plot(alpha, scale*f(alpha))
if np.min(torque) > 0 and np.max(torque) > 0:
ax.set_ylim(bottom=0)
elif np.min(torque) < 0 and np.max(torque) < 0:
ax.set_ylim(top=0)
def torque_fft(order, torque, ax=0):
"""plot torque harmonics"""
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if ax == 0:
ax = plt.gca()
ax.set_title('Torque Harmonics / {}'.format(unit))
ax.grid(True)
try:
bw = 2.5E-2*max(order)
ax.bar(order, [scale*t for t in torque], width=bw, align='center')
ax.set_xlim(left=-bw/2)
except ValueError: # empty sequence
pass
def force(title, pos, force, xlabel='', ax=0):
"""plot force vs position"""
unit = 'N'
scale = 1
if min(force) < -9.9e3 or max(force) > 9.9e3:
scale = 1e-3
unit = 'kN'
if ax == 0:
ax = plt.gca()
ax.set_title('{} / {}'.format(title, unit))
ax.grid(True)
ax.plot(pos, [scale*f for f in force])
if xlabel:
ax.set_xlabel(xlabel)
if min(force) > 0:
ax.set_ylim(bottom=0)
def force_fft(order, force, ax=0):
"""plot force harmonics"""
unit = 'N'
scale = 1
if min(force) < -9.9e3 or max(force) > 9.9e3:
scale = 1e-3
unit = 'kN'
if ax == 0:
ax = plt.gca()
ax.set_title('Force Harmonics / {}'.format(unit))
ax.grid(True)
try:
bw = 2.5E-2*max(order)
ax.bar(order, [scale*t for t in force], width=bw, align='center')
ax.set_xlim(left=-bw/2)
except ValueError: # empty sequence
pass
def forcedens(title, pos, fdens, ax=0):
"""plot force densities"""
if ax == 0:
ax = plt.gca()
ax.set_title(title)
ax.grid(True)
ax.plot(pos, [1e-3*ft for ft in fdens[0]], label='F tang')
ax.plot(pos, [1e-3*fn for fn in fdens[1]], label='F norm')
ax.legend()
ax.set_xlabel('Pos / deg')
ax.set_ylabel('Force Density / kN/m²')
def forcedens_surface(fdens, ax=0):
if ax == 0:
_create_3d_axis()
ax = plt.gca()
xpos = [p for p in fdens.positions[0]['X']]
ypos = [p['position'] for p in fdens.positions]
z = 1e-3*np.array([p['FN']
for p in fdens.positions])
_plot_surface(ax, xpos, ypos, z,
(u'Rotor pos/°', u'Pos/°', u'F N / kN/m²'))
def forcedens_fft(title, fdens, ax=0):
"""plot force densities FFT
Args:
title: plot title
fdens: force density object
"""
if ax == 0:
ax = plt.axes(projection="3d")
F = 1e-3*fdens.fft()
fmin = 0.2
num_bars = F.shape[0] + 1
_xx, _yy = np.meshgrid(np.arange(1, num_bars),
np.arange(1, num_bars))
z_size = F[F > fmin]
x_pos, y_pos = _xx[F > fmin], _yy[F > fmin]
z_pos = np.zeros_like(z_size)
x_size = 2
y_size = 2
ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size)
ax.view_init(azim=120)
ax.set_xlim(0, num_bars+1)
ax.set_ylim(0, num_bars+1)
ax.set_title(title)
ax.set_xlabel('M')
ax.set_ylabel('N')
ax.set_zlabel('kN/m²')
def winding_flux(pos, flux, ax=0):
"""plot flux vs position"""
if ax == 0:
ax = plt.gca()
ax.set_title('Winding Flux / Vs')
ax.grid(True)
for p, f in zip(pos, flux):
ax.plot(p, f)
def winding_current(pos, current, ax=0):
"""plot winding currents"""
if ax == 0:
ax = plt.gca()
ax.set_title('Winding Currents / A')
ax.grid(True)
for p, i in zip(pos, current):
ax.plot(p, i)
def voltage(title, pos, voltage, ax=0):
"""plot voltage vs. position"""
if ax == 0:
ax = plt.gca()
ax.set_title('{} / V'.format(title))
ax.grid(True)
ax.plot(pos, voltage)
def voltage_fft(title, order, voltage, ax=0):
"""plot FFT harmonics of voltage"""
if ax == 0:
ax = plt.gca()
ax.set_title('{} / V'.format(title))
ax.grid(True)
if max(order) < 5:
order += [5]
voltage += [0]
try:
bw = 2.5E-2*max(order)
ax.bar(order, voltage, width=bw, align='center')
except ValueError: # empty sequence
pass
def mcv_hbj(mcv, log=True, ax=0):
"""plot H, B, J of mcv dict"""
import femagtools.mcv
MUE0 = 4e-7*np.pi
ji = []
csiz = len(mcv['curve'])
if ax == 0:
ax = plt.gca()
ax.set_title(mcv['name'])
for k, c in enumerate(mcv['curve']):
bh = [(bi, hi*1e-3)
for bi, hi in zip(c['bi'],
c['hi'])]
try:
if csiz == 1 and mcv['ctype'] in (femagtools.mcv.MAGCRV,
femagtools.mcv.ORIENT_CRV):
ji = [b-MUE0*h*1e3 for b, h in bh]
except Exception:
pass
bi, hi = zip(*bh)
label = 'Flux Density'
if csiz > 1:
label = 'Flux Density ({0}°)'.format(mcv.mc1_angle[k])
if log:
ax.semilogx(hi, bi, label=label)
if ji:
ax.semilogx(hi, ji, label='Polarisation')
else:
ax.plot(hi, bi, label=label)
if ji:
ax.plot(hi, ji, label='Polarisation')
ax.set_xlabel('H / kA/m')
ax.set_ylabel('T')
if ji or csiz > 1:
ax.legend(loc='lower right')
ax.grid()
def mcv_muer(mcv, ax=0):
"""plot rel. permeability vs. B of mcv dict"""
MUE0 = 4e-7*np.pi
bi, ur = zip(*[(bx, bx/hx/MUE0)
for bx, hx in zip(mcv['curve'][0]['bi'],
mcv['curve'][0]['hi']) if not hx == 0])
if ax == 0:
ax = plt.gca()
ax.plot(bi, ur)
ax.set_xlabel('B / T')
ax.set_title('rel. Permeability')
ax.grid()
def mtpa(pmrel, i1max, title='', projection='', ax=0):
"""create a line or surface plot with torque and mtpa curve"""
nsamples = 10
i1 = np.linspace(0, i1max, nsamples)
iopt = np.array([pmrel.mtpa(x) for x in i1]).T
iqmax, idmax = pmrel.iqdmax(i1max)
iqmin, idmin = pmrel.iqdmin(i1max)
if projection == '3d':
nsamples = 50
else:
if iqmin == 0:
iqmin = 0.1*iqmax
id = np.linspace(idmin, idmax, nsamples)
iq = np.linspace(iqmin, iqmax, nsamples)
torque_iqd = np.array(
[[pmrel.torque_iqd(x, y)
for y in id] for x in iq])
if projection == '3d':
ax = idq_torque(id, iq, torque_iqd, ax)
ax.plot(iopt[1], iopt[0], iopt[2],
color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format(
np.max(iopt[2][-1])))
else:
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
x, y = np.meshgrid(id, iq)
CS = ax.contour(x, y, torque_iqd, 6, colors='k')
ax.clabel(CS, fmt='%d', inline=1)
ax.set_xlabel('Id/A')
ax.set_ylabel('Iq/A')
ax.plot(iopt[1], iopt[0],
color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format(
np.max(iopt[2][-1])))
ax.grid()
if title:
ax.set_title(title)
ax.legend()
def mtpv(pmrel, u1max, i1max, title='', projection='', ax=0):
"""create a line or surface plot with voltage and mtpv curve"""
w1 = pmrel.w2_imax_umax(i1max, u1max)
nsamples = 20
if projection == '3d':
nsamples = 50
iqmax, idmax = pmrel.iqdmax(i1max)
iqmin, idmin = pmrel.iqdmin(i1max)
id = np.linspace(idmin, idmax, nsamples)
iq = np.linspace(iqmin, iqmax, nsamples)
u1_iqd = np.array(
[[np.linalg.norm(pmrel.uqd(w1, iqx, idx))/np.sqrt(2)
for idx in id] for iqx in iq])
u1 = np.mean(u1_iqd)
imtpv = np.array([pmrel.mtpv(wx, u1, i1max)
for wx in np.linspace(w1, 20*w1, nsamples)]).T
if projection == '3d':
torque_iqd = np.array(
[[pmrel.torque_iqd(x, y)
for y in id] for x in iq])
ax = idq_torque(id, iq, torque_iqd, ax)
ax.plot(imtpv[1], imtpv[0], imtpv[2],
color='red', linewidth=2)
else:
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
x, y = np.meshgrid(id, iq)
CS = ax.contour(x, y, u1_iqd, 4, colors='b') # linestyles='dashed')
ax.clabel(CS, fmt='%d', inline=1)
ax.plot(imtpv[1], imtpv[0],
color='red', linewidth=2,
label='MTPV: {0:5.0f} Nm'.format(np.max(imtpv[2])))
# beta = np.arctan2(imtpv[1][0], imtpv[0][0])
# b = np.linspace(beta, 0)
# ax.plot(np.sqrt(2)*i1max*np.sin(b), np.sqrt(2)*i1max*np.cos(b), 'r-')
ax.grid()
ax.legend()
ax.set_xlabel('Id/A')
ax.set_ylabel('Iq/A')
if title:
ax.set_title(title)
def <API key>(lf):
if 'force_r' in lf:
return ['Force r', 'Force z'], ['force_r', 'force_z']
return ['Force x', 'Force y'], ['force_x', 'force_y']
def pmrelsim(bch, title=''):
"""creates a plot of a PM/Rel motor simulation"""
cols = 2
rows = 4
if len(bch.flux['1']) > 1:
rows += 1
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
tq = list(bch.torque_fft[-1]['torque'])
order = list(bch.torque_fft[-1]['order'])
if order and max(order) < 5:
order += [15]
tq += [0]
torque_fft(order, tq)
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = <API key>(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos,
[f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos,
[f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def multcal(bch, title=''):
"""creates a plot of a MULT CAL simulation"""
cols = 2
rows = 4
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
tq = list(bch.torque_fft[-1]['torque'])
order = list(bch.torque_fft[-1]['order'])
if order and max(order) < 5:
order += [15]
tq += [0]
torque_fft(order, tq)
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = <API key>(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos,
[f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos,
[f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def fasttorque(bch, title=''):
"""creates a plot of a Fast Torque simulation"""
cols = 2
rows = 4
if len(bch.flux['1']) > 1:
rows += 1
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
torque_fft(bch.torque_fft[-1]['order'], bch.torque_fft[-1]['torque'])
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = <API key>(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos, [f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos, [f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def cogging(bch, title=''):
"""creates a cogging plot"""
cols = 2
rows = 3
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[0]['angle'], bch.torque[0]['torque'])
plt.subplot(rows, cols, row+1)
if bch.torque_fft:
torque_fft(bch.torque_fft[0]['order'], bch.torque_fft[0]['torque'])
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[0]['angle'], bch.torque[0]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[0]['angle'], bch.torque[0]['force_y'])
row += 3
elif bch.linearForce:
title, keys = <API key>(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
voltage('Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+2)
voltage_fft('Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
fig.tight_layout(h_pad=2)
if title:
fig.subplots_adjust(top=0.92)
def transientsc(bch, title=''):
"""creates a transient short circuit plot"""
cols = 1
rows = 2
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
ax = plt.gca()
ax.set_title('Currents / A')
ax.grid(True)
for i in ('ia', 'ib', 'ic'):
ax.plot(bch.scData['time'], bch.scData[i], label=i)
ax.set_xlabel('Time / s')
ax.legend()
row = 2
plt.subplot(rows, cols, row)
ax = plt.gca()
ax.set_title('Torque / Nm')
ax.grid(True)
ax.plot(bch.scData['time'], bch.scData['torque'])
ax.set_xlabel('Time / s')
fig.tight_layout(h_pad=2)
if title:
fig.subplots_adjust(top=0.92)
def i1beta_torque(i1, beta, torque, title='', ax=0):
"""creates a surface plot of torque vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 210
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -60
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if title:
_plot_surface(ax, i1, beta, scale*np.asarray(torque),
(u'I1/A', u'Beta/°', title),
azim=azim)
else:
_plot_surface(ax, i1, beta, scale*np.asarray(torque),
(u'I1/A', u'Beta/°', u'Torque/{}'.format(unit)),
azim=azim)
def i1beta_ld(i1, beta, ld, ax=0):
"""creates a surface plot of ld vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, np.asarray(ld)*1e3,
(u'I1/A', u'Beta/°', u'Ld/mH'),
azim=60)
def i1beta_lq(i1, beta, lq, ax=0):
"""creates a surface plot of ld vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 60
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -120
_plot_surface(ax, i1, beta, np.asarray(lq)*1e3,
(u'I1/A', u'Beta/°', u'Lq/mH'),
azim=azim)
def i1beta_psim(i1, beta, psim, ax=0):
"""creates a surface plot of psim vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, psim,
(u'I1/A', u'Beta/°', u'Psi m/Vs'),
azim=60)
def i1beta_up(i1, beta, up, ax=0):
"""creates a surface plot of up vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, up,
(u'I1/A', u'Beta/°', u'Up/V'),
azim=60)
def i1beta_psid(i1, beta, psid, ax=0):
"""creates a surface plot of psid vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = -60
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = 60
_plot_surface(ax, i1, beta, psid,
(u'I1/A', u'Beta/°', u'Psi d/Vs'),
azim=azim)
def i1beta_psiq(i1, beta, psiq, ax=0):
"""creates a surface plot of psiq vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 210
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -60
_plot_surface(ax, i1, beta, psiq,
(u'I1/A', u'Beta/°', u'Psi q/Vs'),
azim=azim)
def idq_torque(id, iq, torque, ax=0):
"""creates a surface plot of torque vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
_plot_surface(ax, id, iq, scale*np.asarray(torque),
(u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)),
azim=-60)
return ax
def idq_psid(id, iq, psid, ax=0):
"""creates a surface plot of psid vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psid,
(u'Id/A', u'Iq/A', u'Psi d/Vs'),
azim=210)
def idq_psiq(id, iq, psiq, ax=0):
"""creates a surface plot of psiq vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psiq,
(u'Id/A', u'Iq/A', u'Psi q/Vs'),
azim=210)
def idq_psim(id, iq, psim, ax=0):
"""creates a surface plot of psim vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psim,
(u'Id/A', u'Iq/A', u'Psi m [Vs]'),
azim=120)
def idq_ld(id, iq, ld, ax=0):
"""creates a surface plot of ld vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, np.asarray(ld)*1e3,
(u'Id/A', u'Iq/A', u'L d/mH'),
azim=120)
def idq_lq(id, iq, lq, ax=0):
"""creates a surface plot of lq vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, np.asarray(lq)*1e3,
(u'Id/A', u'Iq/A', u'L q/mH'),
azim=120)
def ldlq(bch):
"""creates the surface plots of a BCH reader object
with a ld-lq identification"""
beta = bch.ldq['beta']
i1 = bch.ldq['i1']
torque = bch.ldq['torque']
ld = np.array(bch.ldq['ld'])
lq = np.array(bch.ldq['lq'])
psid = bch.ldq['psid']
psiq = bch.ldq['psiq']
rows = 3
fig = plt.figure(figsize=(10, 4*rows))
fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16)
fig.add_subplot(rows, 2, 1, projection='3d')
i1beta_torque(i1, beta, torque)
fig.add_subplot(rows, 2, 2, projection='3d')
i1beta_psid(i1, beta, psid)
fig.add_subplot(rows, 2, 3, projection='3d')
i1beta_psiq(i1, beta, psiq)
fig.add_subplot(rows, 2, 4, projection='3d')
try:
i1beta_psim(i1, beta, bch.ldq['psim'])
except:
i1beta_up(i1, beta, bch.ldq['up'])
fig.add_subplot(rows, 2, 5, projection='3d')
i1beta_ld(i1, beta, ld)
fig.add_subplot(rows, 2, 6, projection='3d')
i1beta_lq(i1, beta, lq)
def psidq(bch):
"""creates the surface plots of a BCH reader object
with a psid-psiq identification"""
id = bch.psidq['id']
iq = bch.psidq['iq']
torque = bch.psidq['torque']
ld = np.array(bch.psidq_ldq['ld'])
lq = np.array(bch.psidq_ldq['lq'])
psim = bch.psidq_ldq['psim']
psid = bch.psidq['psid']
psiq = bch.psidq['psiq']
rows = 3
fig = plt.figure(figsize=(10, 4*rows))
fig.suptitle('Psid-Psiq Identification {}'.format(
bch.filename), fontsize=16)
fig.add_subplot(rows, 2, 1, projection='3d')
idq_torque(id, iq, torque)
fig.add_subplot(rows, 2, 2, projection='3d')
idq_psid(id, iq, psid)
fig.add_subplot(rows, 2, 3, projection='3d')
idq_psiq(id, iq, psiq)
fig.add_subplot(rows, 2, 4, projection='3d')
idq_psim(id, iq, psim)
fig.add_subplot(rows, 2, 5, projection='3d')
idq_ld(id, iq, ld)
fig.add_subplot(rows, 2, 6, projection='3d')
idq_lq(id, iq, lq)
def felosses(losses, coeffs, title='', log=True, ax=0):
"""plot iron losses with steinmetz or jordan approximation
Args:
losses: dict with f, B, pfe values
coeffs: list with steinmetz (cw, alpha, beta) or
jordan (cw, alpha, ch, beta, gamma) coeffs
title: title string
log: log scale for x and y axes if True
"""
import femagtools.losscoeffs as lc
if ax == 0:
ax = plt.gca()
fo = losses['fo']
Bo = losses['Bo']
B = plt.np.linspace(0.9*np.min(losses['B']),
1.1*0.9*np.max(losses['B']))
for i, f in enumerate(losses['f']):
pfe = [p for p in np.array(losses['pfe'])[i] if p]
if f > 0:
if len(coeffs) == 5:
ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo))
elif len(coeffs) == 3:
ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo))
plt.plot(losses['B'][:len(pfe)], pfe,
marker='o', label="{} Hz".format(f))
ax.set_title("Fe Losses/(W/kg) " + title)
if log:
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel("Flux Density [T]")
# plt.ylabel("Pfe [W/kg]")
ax.legend()
ax.grid(True)
def spel(isa, with_axis=False, ax=0):
"""plot super elements of I7/ISA7 model
Args:
isa: Isa7 object
"""
from matplotlib.patches import Polygon
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
for se in isa.superelements:
ax.add_patch(Polygon([n.xy
for nc in se.nodechains
for n in nc.nodes],
color=isa.color[se.color], lw=0))
ax.autoscale(enable=True)
if not with_axis:
ax.axis('off')
def mesh(isa, with_axis=False, ax=0):
"""plot mesh of I7/ISA7 model
Args:
isa: Isa7 object
"""
from matplotlib.lines import Line2D
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
for el in isa.elements:
pts = [list(i) for i in zip(*[v.xy for v in el.vertices])]
ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25))
# for nc in isa.nodechains:
# pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])]
# ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25,
# marker=".", ms="2", mec="None"))
# for nc in isa.nodechains:
# if nc.nodemid is not None:
# plt.plot(*nc.nodemid.xy, "rx")
ax.autoscale(enable=True)
if not with_axis:
ax.axis('off')
def _contour(ax, title, elements, values, label='', isa=None):
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
ax.set_title(title, fontsize=18)
if isa:
for se in isa.superelements:
ax.add_patch(Polygon([n.xy
for nc in se.nodechains
for n in nc.nodes],
color='gray', alpha=0.1, lw=0))
valid_values = np.logical_not(np.isnan(values))
patches = np.array([Polygon([v.xy for v in e.vertices])
for e in elements])[valid_values]
# , cmap=matplotlib.cm.jet, alpha=0.4)
p = PatchCollection(patches, alpha=1.0, match_original=False)
p.set_array(np.asarray(values)[valid_values])
ax.add_collection(p)
cb = plt.colorbar(p)
for patch in np.array([Polygon([v.xy for v in e.vertices],
fc='white', alpha=1.0)
for e in elements])[np.isnan(values)]:
ax.add_patch(patch)
if label:
cb.set_label(label=label, fontsize=18)
ax.autoscale(enable=True)
ax.axis('off')
def demag(isa, ax=0):
"""plot demag of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
emag = [e for e in isa.elements if e.is_magnet()]
demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag])
_contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C',
emag, demag, '-H / kA/m', isa)
logger.info("Max demagnetization %f", np.max(demag))
def demag_pos(isa, pos, icur=-1, ibeta=-1, ax=0):
"""plot demag of NC/I7/ISA7 model at rotor position
Args:
isa: Isa7/NC object
pos: rotor position in degree
icur: cur amplitude index or last index if -1
ibeta: beta angle index or last index if -1
"""
emag = [e for e in isa.elements if e.is_magnet()]
demag = np.array([isa.demagnetization(e, icur, ibeta)[1]
for e in emag])
for i, x in enumerate(isa.pos_el_fe_induction):
if x >= pos/180*np.pi:
break
hpol = demag[:, i]
hpol[hpol == 0] = np.nan
_contour(ax, f'Demagnetization at Pos. {round(x/np.pi*180)}° ({isa.MAGN_TEMPERATURE} °C)',
emag, hpol, '-H / kA/m', isa)
logger.info("Max demagnetization %f kA/m", np.nanmax(hpol))
def flux_density(isa, subreg=[], ax=0):
"""plot flux density of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
if subreg:
if isinstance(subreg, list):
sr = subreg
else:
sr = [subreg]
elements = [e for s in sr for se in isa.get_subregion(s).elements()
for e in se]
else:
elements = [e for e in isa.elements]
fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements])
_contour(ax, f'Flux Density T', elements, fluxd)
logger.info("Max flux dens %f", np.max(fluxd))
def loss_density(isa, subreg=[], ax=0):
"""plot loss density of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
if subreg:
if isinstance(subreg, list):
sr = subreg
else:
sr = [subreg]
elements = [e for s in sr for sre in isa.get_subregion(s).elements()
for e in sre]
else:
elements = [e for e in isa.elements]
lossd = np.array([e.loss_density*1e-3 for e in elements])
_contour(ax, 'Loss Density kW/m³', elements, lossd)
def mmf(f, title='', ax=0):
"""plot magnetomotive force (mmf) of winding"""
if ax == 0:
ax = plt.gca()
if title:
ax.set_title(title)
ax.plot(np.array(f['pos'])/np.pi*180, f['mmf'])
ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft'])
ax.set_xlabel('Position / Deg')
phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180]
y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])]
ax.plot(phi, y, '
alfa0 = round(f['alfa0']/np.pi*180, 3)
ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°",
ha="center", va="bottom")
ax.annotate(f"", xy=(phi[0], y[0]),
xytext=(0, y[0]), arrowprops=dict(arrowstyle="->"))
ax.grid()
def mmf_fft(f, title='', mmfmin=1e-2, ax=0):
"""plot winding mmf harmonics"""
if ax == 0:
ax = plt.gca()
if title:
ax.set_title(title)
else:
ax.set_title('MMF Harmonics')
ax.grid(True)
order, mmf = np.array([(n, m) for n, m in zip(f['nue'],
f['mmf_nue']) if m > mmfmin]).T
try:
markerline1, stemlines1, _ = ax.stem(order, mmf, '-.', basefmt=" ",
use_line_collection=True)
ax.set_xticks(order)
except ValueError: # empty sequence
pass
def zoneplan(wdg, ax=0):
"""plot zone plan of winding wdg"""
from matplotlib.patches import Rectangle
upper, lower = wdg.zoneplan()
Qb = len([n for l in upper for n in l])
from femagtools.windings import coil_color
rh = 0.5
if lower:
yl = rh
ymax = 2*rh + 0.2
else:
yl = 0
ymax = rh + 0.2
if ax == 0:
ax = plt.gca()
ax.axis('off')
ax.set_xlim([-0.5, Qb-0.5])
ax.set_ylim([0, ymax])
ax.set_aspect(Qb/6+0.3)
for i, p in enumerate(upper):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl+rh/2, s, color='black',
ha="center", va="center")
for i, p in enumerate(lower):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl-rh/2, s, color='black',
ha="center", va="center")
yu = yl+rh
step = 1 if Qb < 25 else 2
if lower:
yl -= rh
margin = 0.05
ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}',
ha='left', va='bottom', size=15)
for i in range(0, Qb, step):
ax.text(i, yl-margin, f'{i+1}', ha="center", va="top")
def winding_factors(wdg, n=8, ax=0):
"""plot winding factors"""
ax = plt.gca()
ax.set_title(f'Winding factors Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}')
ax.grid(True)
order, kwp, kwd, kw = np.array([(n, k1, k2, k3)
for n, k1, k2, k3 in zip(wdg.kw_order(n),
wdg.kwp(n),
wdg.kwd(n),
wdg.kw(n))]).T
try:
markerline1, stemlines1, _ = ax.stem(order-1, kwp, 'C1:', basefmt=" ",
markerfmt='C1.',
use_line_collection=True, label='Pitch')
markerline2, stemlines2, _ = ax.stem(order+1, kwd, 'C2:', basefmt=" ",
markerfmt='C2.',
use_line_collection=True, label='Distribution')
markerline3, stemlines3, _ = ax.stem(order, kw, 'C0-', basefmt=" ",
markerfmt='C0o',
use_line_collection=True, label='Total')
ax.set_xticks(order)
ax.legend()
except ValueError: # empty sequence
pass
def winding(wdg, ax=0):
"""plot coils of windings wdg"""
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
from femagtools.windings import coil_color
coil_len = 25
coil_height = 4
dslot = 8
arrow_head_length = 2
arrow_head_width = 2
if ax == 0:
ax = plt.gca()
z = wdg.zoneplan()
xoff = 0
if z[-1]:
xoff = 0.75
yd = dslot*wdg.yd
mh = 2*coil_height/yd
slots = sorted([abs(n) for m in z[0] for n in m])
smax = slots[-1]*dslot
for n in slots:
x = n*dslot
ax.add_patch(Rectangle((x + dslot/4, 1), dslot /
2, coil_len - 2, fc="lightblue"))
ax.text(x, coil_len / 2,
str(n),
horizontalalignment="center",
verticalalignment="center",
backgroundcolor="white",
bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0))
line_thickness = [0.6, 1.2]
for i, layer in enumerate(z):
b = -xoff if i else xoff
lw = line_thickness[i]
for m, mslots in enumerate(layer):
for k in mslots:
x = abs(k) * dslot + b
xpoints = []
ypoints = []
if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))):
# first layer, positive dir or neg. dir and 2-layers:
# from right bottom
if x + yd > smax+b:
dx = dslot if yd > dslot else yd/4
xpoints = [x + yd//2 + dx - xoff]
ypoints = [-coil_height + mh*dx]
xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x + yd > smax+b:
xpoints += [x + yd//2 + dx - xoff]
ypoints += [coil_len+coil_height - mh*dx]
else:
# from left bottom
if x - yd < 0: # and x - yd/2 > -3*dslot:
dx = dslot if yd > dslot else yd/4
xpoints = [x - yd//2 - dx + xoff]
ypoints = [- coil_height + mh*dx]
xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x - yd < 0: # and x - yd > -3*dslot:
xpoints += [x - yd//2 - dx + xoff]
ypoints += [coil_len + coil_height - mh*dx]
ax.add_line(Line2D(xpoints, ypoints,
color=coil_color[m], lw=lw))
if k > 0:
h = arrow_head_length
y = coil_len * 0.8
else:
h = -arrow_head_length
y = coil_len * 0.2
ax.arrow(x, y, 0, h,
<API key>=True,
head_starts_at_zero=False,
head_length=arrow_head_length,
head_width=arrow_head_width,
fc=coil_color[m], lw=0)
if False: # TODO show winding connections
m = 0
for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]:
if k < len(slots):
x = k * dslot + b + yd/2 - xoff
ax.add_line(Line2D([x, x],
[-2*coil_height, -coil_height],
color=coil_color[m], lw=lw))
ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m])
m += 1
ax.autoscale(enable=True)
ax.set_axis_off()
def main():
import io
import sys
import argparse
from .__init__ import __version__
from femagtools.bch import Reader
argparser = argparse.ArgumentParser(
description='Read BCH/BATCH/PLT file and create a plot')
argparser.add_argument('filename',
help='name of BCH/BATCH/PLT file')
argparser.add_argument(
"--version",
"-v",
action="version",
version="%(prog)s {}, Python {}".format(__version__, sys.version),
help="display version information",
)
args = argparser.parse_args()
if not matplotlibversion:
sys.exit(0)
if not args.filename:
sys.exit(0)
ext = args.filename.split('.')[-1].upper()
if ext.startswith('MC'):
import femagtools.mcv
mcv = femagtools.mcv.read(sys.argv[1])
if mcv['mc1_type'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV):
ncols = 2
else: # Permanent Magnet
ncols = 1
fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(10, 6))
if ncols > 1:
plt.subplot(1, 2, 1)
mcv_hbj(mcv)
plt.subplot(1, 2, 2)
mcv_muer(mcv)
else:
mcv_hbj(mcv, log=False)
fig.tight_layout()
fig.subplots_adjust(top=0.94)
plt.show()
return
if ext.startswith('PLT'):
import femagtools.forcedens
fdens = femagtools.forcedens.read(args.filename)
cols = 1
rows = 2
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 10*rows))
title = '{}, Rotor position {}'.format(
fdens.title, fdens.positions[0]['position'])
pos = fdens.positions[0]['X']
FT_FN = (fdens.positions[0]['FT'],
fdens.positions[0]['FN'])
plt.subplot(rows, cols, 1)
forcedens(title, pos, FT_FN)
title = 'Force Density Harmonics'
plt.subplot(rows, cols, 2)
forcedens_fft(title, fdens)
# fig.tight_layout(h_pad=3.5)
# if title:
# fig.subplots_adjust(top=0.92)
plt.show()
return
bchresults = Reader()
with io.open(args.filename, encoding='latin1', errors='ignore') as f:
bchresults.read(f.readlines())
if (bchresults.type.lower().find(
'<API key> simulation') >= 0 or
bchresults.type.lower().find(
'<API key>') >= 0 or
bchresults.type.lower().find(
'simulation pm/universal-motor') >= 0):
pmrelsim(bchresults, bchresults.filename)
elif bchresults.type.lower().find(
'multiple calculation of forces and flux') >= 0:
multcal(bchresults, bchresults.filename)
elif bchresults.type.lower().find('cogging calculation') >= 0:
cogging(bchresults, bchresults.filename)
elif bchresults.type.lower().find('<API key>') >= 0:
ldlq(bchresults)
elif bchresults.type.lower().find('<API key>') >= 0:
psidq(bchresults)
elif bchresults.type.lower().find('fast_torque calculation') >= 0:
fasttorque(bchresults)
elif bchresults.type.lower().find('transient sc') >= 0:
transientsc(bchresults, bchresults.filename)
else:
raise ValueError("BCH type {} not yet supported".format(
bchresults.type))
plt.show()
def characteristics(char, title=''):
fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True)
if title:
fig.suptitle(title)
n = np.array(char['n'])*60
pmech = np.array(char['pmech'])*1e-3
axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque')
axs[0, 0].set_ylabel("Torque / Nm")
axs[0, 0].grid()
axs[0, 0].legend(loc='center left')
ax1 = axs[0, 0].twinx()
ax1.plot(n, pmech, 'C1-', label='P mech')
ax1.set_ylabel("Power / kW")
ax1.legend(loc='lower center')
axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage')
axs[0, 1].set_ylabel("Voltage / V",)
axs[0, 1].grid()
axs[0, 1].legend(loc='center left')
ax2 = axs[0, 1].twinx()
ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi')
ax2.set_ylabel("Cos Phi")
ax2.legend(loc='lower right')
if 'id' in char:
axs[1, 0].plot(n, np.array(char['id']), label='Id')
if 'iq' in char:
axs[1, 0].plot(n, np.array(char['iq']), label='Iq')
axs[1, 0].plot(n, np.array(char['i1']), label='I1')
axs[1, 0].set_xlabel("Speed / rpm")
axs[1, 0].set_ylabel("Current / A")
axs[1, 0].legend(loc='center left')
if 'beta' in char:
ax3 = axs[1, 0].twinx()
ax3.plot(n, char['beta'], 'C3-', label='Beta')
ax3.set_ylabel("Beta / °")
ax3.legend(loc='center right')
axs[1, 0].grid()
plfe = np.array(char['plfe'])*1e-3
plcu = np.array(char['plcu'])*1e-3
pl = np.array(char['losses'])*1e-3
axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses')
axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses')
axs[1, 1].set_ylabel("Losses / kW")
axs[1, 1].legend(loc='center left')
axs[1, 1].grid()
axs[1, 1].set_xlabel("Speed / rpm")
ax4 = axs[1, 1].twinx()
ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta")
ax4.legend(loc='upper center')
ax4.set_ylabel("Efficiency")
fig.tight_layout()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(message)s')
main()
|
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'application',
template: `<div>Hello!</div>`
})
export class <API key> {}
@NgModule({
imports: [BrowserModule],
declarations: [<API key>],
bootstrap: [<API key>],
})
export class BasicInlineModule {}
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return tup
def symarray(prefix, shape):
import numpy as np
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbol('%s_%s' % (
prefix, '_'.join(map(str, index))))
return arr
def lambdify(args, exprs):
"""
lambdify mimics sympy.lambdify
"""
try:
nargs = len(args)
except TypeError:
args = (args,)
nargs = 1
try:
nexprs = len(exprs)
except TypeError:
exprs = (exprs,)
nexprs = 1
@_wrap_numbers
def f(*inp):
if len(inp) != nargs:
raise TypeError("Incorrect number of arguments")
try:
len(inp)
except TypeError:
inp = (inp,)
subsd = dict(zip(args, inp))
return [expr.subs(subsd).evalf() for expr in exprs][
0 if nexprs == 1 else slice(None)]
return f
class Lambdify(object):
"""
Lambdify mimics symengine.Lambdify
"""
def __init__(self, syms, exprs):
self.syms = syms
self.exprs = exprs
def __call__(self, inp, out=None):
inp = tuple(map(Number.make, inp))
subsd = dict(zip(self.syms, inp))
def _eval(expr_iter):
return [expr.subs(subsd).evalf() for expr in expr_iter]
exprs = self.exprs
if out is not None:
try:
out.flat = _eval(exprs.flatten())
except AttributeError:
out.flat = _eval(exprs)
elif isinstance(exprs, Matrix):
import numpy as np
nr, nc = exprs.nrows, exprs.ncols
out = np.empty((nr, nc))
for ri in range(nr):
for ci in range(nc):
out[ri, ci] = exprs._get_element(
ri*nc + ci).subs(subsd).evalf()
return out
# return Matrix(nr, nc, _eval(exprs._get_element(i) for
# i in range(nr*nc)))
elif hasattr(exprs, 'reshape'):
# NumPy like container:
container = exprs.__class__(exprs.shape, dtype=float, order='C')
container.flat = _eval(exprs.flatten())
return container
else:
return _eval(exprs)
|
const maps = require('source-map-support');
maps.install({environment: 'node'});
|
var thisVals = [];
var nextResult = {
done: false,
value: {}
};
var nextNextResult = {
done: false,
value: {}
};
var firstReturnVal = {};
var secondReturnVal = {};
var mapFn = function(value, idx) {
var returnVal = nextReturnVal;
nextReturnVal = nextNextReturnVal;
nextNextReturnVal = null;
return returnVal;
};
var nextReturnVal = firstReturnVal;
var nextNextReturnVal = secondReturnVal;
var items = {};
var result;
items[Symbol.iterator] = function() {
return {
next: function() {
var result = nextResult;
nextResult = nextNextResult;
nextNextResult = {
done: true
};
return result;
}
};
};
result = Array.from(items, mapFn);
assert.sameValue(result.length, 2);
assert.sameValue(result[0], firstReturnVal);
assert.sameValue(result[1], secondReturnVal);
|
package com.mithos.bfg.loop;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
/**
* This class is an adapter for {@link OnEvent}. All methods do
* nothing and return true, so you need only implement the methods
* that you need to.
* @author James McMahon
*
*/
public class OnEventAdapter implements OnEvent {
@Override
public boolean keyPressed(KeyEvent e) {
return true;
}
@Override
public boolean keyReleased(KeyEvent e) {
return true;
}
@Override
public boolean mousePressed(MouseEvent e) {
return true;
}
@Override
public boolean mouseMoved(MouseEvent e) {
return true;
}
@Override
public boolean mouseReleased(MouseEvent e) {
return true;
}
@Override
public boolean mouseWheel(MouseWheelEvent e) {
return true;
}
}
|
using Esprima.Ast;
namespace Jint.Runtime.Interpreter
{
<summary>
Per Engine.Evalute() call context.
</summary>
internal sealed class EvaluationContext
{
public EvaluationContext(Engine engine, in Completion? resumedCompletion = null)
{
Engine = engine;
DebugMode = engine._isDebugMode;
ResumedCompletion = resumedCompletion ?? default; // TODO later
<API key> = engine.Options.Interop.<API key>;
}
public Engine Engine { get; }
public Completion ResumedCompletion { get; }
public bool DebugMode { get; }
public Node LastSyntaxNode { get; set; }
public bool <API key> { get; }
}
}
|
log.enableAll();
(function(){
function animate() {
<API key>(animate);
TWEEN.update();
}
animate();
})();
var transform = getStyleProperty('transform');
var getStyle = ( function() {
var getStyleFn = getComputedStyle ?
function( elem ) {
return getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
return function getStyle( elem ) {
var style = getStyleFn( elem );
if ( !style ) {
log.error( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See http://bit.ly/getsizebug1' );
}
return style;
};
})();
var cache = {
imgW: 5100,
imgH: 852,
panOffsetX: 0,
ring: 0,
deg: 0,
runDeg: 0,
minOffsetDeg: 8,
rotationOffsetDeg: 0,
<API key>: 0,
nowOffset: 0,
len: 0,
touchLock: false,
timer: null
};
var tween1, tween2;
var util = {
setTranslateX: function setTranslateX(el, num) {
el.style[transform] = "translate3d(" + num + "px,0,0)";
}
};
var initPanoramaBox = function initPanoramaBox($el, opts) {
var elH = $el.height();
var elW = $el.width();
var $panoramaBox = $('<div class="panorama-box">' +
'<div class="panorama-item"></div>' +
'<div class="panorama-item"></div>' +
'</div>');
var $panoramaItem = $('.panorama-item', $panoramaBox);
var scal = elH / opts.height;
$panoramaItem.css({
width: opts.width,
height: opts.height
});
$panoramaBox.css({
width: elW / scal,
height: opts.height,
transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')',
'transform-origin': '0 0'
});
util.setTranslateX($panoramaItem.get(0), 0);
util.setTranslateX($panoramaItem.get(1), -opts.width);
$el.append($panoramaBox);
var offset = function offset(num) {
var width = opts.width;
var num1 = num % opts.width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 2;
} else {
num2 = -width + num1 + 2;
}
util.setTranslateX($panoramaItem.get(0), num1);
util.setTranslateX($panoramaItem.get(1), num2);
};
var run = function (subBox1, subBox2, width) {
return function offset(num) {
num = parseInt(num);
cache.len = num;
var num1 = num % width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 1;
} else {
num2 = -width + num1 + 2;
}
util.setTranslateX(subBox1, num1);
util.setTranslateX(subBox2, num2);
};
};
return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width);
};
var $el = {};
$el.main = $('.wrapper');
var offset = initPanoramaBox($el.main, {
width: cache.imgW,
height: cache.imgH
});
var animOffset = function animOffset(length){
if(tween1){
tween1.stop();
}
tween1 = new TWEEN.Tween({x: cache.len});
tween1.to({x: length}, 600);
tween1.onUpdate(function(){
offset(this.x);
});
tween1.start();
};
var animPanEnd = function animPanEnd(velocityX){
if(tween2){
tween2.stop();
}
var oldLen = cache.len;
var offsetLen ;
tween2 = new TWEEN.Tween({x: cache.len});
tween2.to({x: cache.len - 200 * velocityX}, 600);
tween2.easing(TWEEN.Easing.Cubic.Out);
tween2.onUpdate(function(){
offset(this.x);
offsetLen =oldLen - this.x;
cache.nowOffset += + offsetLen;
cache.panOffsetX += + offsetLen;
});
tween2.start();
};
var <API key> = function () {
FULLTILT.<API key>({'type': 'world'})
.then(function (orientationControl) {
var orientationFunc = function orientationFunc() {
var screenAdjustedEvent = orientationControl.<API key>();
cache.navDeg = 360 - screenAdjustedEvent.alpha;
if (cache.navDeg > 270 && cache.navOldDeg < 90) {
cache.ring -= 1;
} else if (cache.navDeg < 90 && cache.navOldDeg > 270) {
cache.ring += 1;
}
cache.navOldDeg = cache.navDeg;
cache.oldDeg = cache.deg;
cache.deg = cache.ring * 360 + cache.navDeg;
var offsetDeg = cache.deg - cache.runDeg;
if (!cache.touchLock &&
(Math.abs(offsetDeg) > cache.minOffsetDeg)) {
var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX;
cache.runDeg = cache.deg;
cache.nowOffset = length;
animOffset(length);
}
};
orientationControl.listen(orientationFunc);
})
.catch(function(e){
log.error(e);
});
};
var initTouch = function(){
var mc = new Hammer.Manager($el.main.get(0));
var pan = new Hammer.Pan();
$el.main.on('touchstart', function (evt) {
if (cache.timer) {
clearTimeout(cache.timer);
cache.timer = null;
}
cache.touchLock = true;
if(tween1){
tween1.stop();
}
if(tween2){
tween2.stop();
}
cache.nowOffset = cache.len;
});
$el.main.on('touchend', function (evt) {
cache.timer = setTimeout(function () {
cache.<API key> = cache.deg - cache.runDeg;
cache.runDeg = cache.deg + cache.<API key>;
cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.<API key>;
cache.touchLock = false;
}, 1000);
});
mc.add(pan);
mc.on('pan', function (evt) {
offset(cache.nowOffset + evt.deltaX);
});
mc.on('panend', function (evt) {
cache.nowOffset += + evt.deltaX;
cache.panOffsetX += + evt.deltaX;
//animPanEnd(evt.velocityX);
});
};
initTouch();
<API key>();
|
#include "WNNetworking/inc/<API key>.h"
#include "WNNetworking/inc/<API key>.h"
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
namespace wn {
namespace networking {
network_error <API key>::connect_to(logging::log* _log,
const containers::string_view& target, uint32_t _connection_type,
uint16_t _port) {
char port_array[11] = {0};
memory::writeuint32(port_array, _port, 10);
addrinfo* result;
addrinfo* ptr;
if (0 != getaddrinfo(target.to_string(m_allocator).c_str(), port_array,
nullptr, &result)) {
_log->log_error("Could not resolve local port ", port_array);
return network_error::could_not_resolve;
}
ptr = result;
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
if ((_connection_type == 0xFFFFFFFF &&
(ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)) ||
ptr->ai_family == static_cast<int>(_connection_type)) {
m_sock_fd = socket(ptr->ai_family, SOCK_STREAM, IPPROTO_TCP);
if (m_sock_fd == -1) {
continue;
}
if (0 != connect(m_sock_fd, ptr->ai_addr, ptr->ai_addrlen)) {
::close(m_sock_fd);
m_sock_fd = -1;
continue;
}
break;
}
}
freeaddrinfo(result);
if (ptr == nullptr) {
_log->log_error("Could not resolve target ", target, ":", port_array);
return network_error::could_not_resolve;
}
return network_error::ok;
}
network_error <API key>::do_send(
const send_ranges& _buffers) {
iovec* send_buffers =
static_cast<iovec*>(WN_STACK_ALLOC(sizeof(iovec) * _buffers.size()));
size_t total_bytes = 0;
for (size_t i = 0; i < _buffers.size(); ++i) {
total_bytes += _buffers[i].size();
send_buffers[i].iov_base =
const_cast<void*>(static_cast<const void*>(_buffers[i].data()));
send_buffers[i].iov_len = _buffers[i].size();
}
using iovlen_type = decltype(msghdr().msg_iovlen);
msghdr header = {nullptr, // msg_name
0, // msg_namelen
send_buffers, // msg_iov
static_cast<iovlen_type>(_buffers.size()), // msg_iovlen
nullptr, // msg_control
0, // msg_controllen
0};
ssize_t num_sent = 0;
if (0 > (num_sent = sendmsg(m_sock_fd, &header, 0))) {
return network_error::could_not_send;
}
if (num_sent != static_cast<ssize_t>(total_bytes)) {
return network_error::could_not_send;
::close(m_sock_fd);
m_sock_fd = -1;
}
return network_error::ok;
}
WNReceiveBuffer <API key>::recv_sync() {
WNReceiveBuffer buffer(m_manager->acquire_buffer());
ssize_t received = 0;
if (0 >=
(received = recv(m_sock_fd, buffer.data.data(), buffer.data.size(), 0))) {
return WNReceiveBuffer(network_error::could_not_receive);
}
buffer.data =
containers::contiguous_range<char>(buffer.data.data(), received);
return buffer;
}
} // namespace networking
} // namespace wn
|
#ifndef <API key>
#define <API key>
#include "eavlDataSet.h"
#include "eavlCellSet.h"
#include "eavlColor.h"
#include "eavlColorTable.h"
#include "eavlSceneRenderer.h"
#include "<API key>.h"
#include "eavlTimer.h"
// Class: eavlSceneRendererRT
// Purpose:
// Programmer: Matt Larsen
// Creation: July 17, 2014
// Modifications:
class eavlSceneRendererRT : public eavlSceneRenderer
{
private:
<API key>* tracer;
bool canRender;
bool setLight;
string ctName;
float pointRadius;
float lineWidth;
public:
eavlSceneRendererRT()
{
tracer = new <API key>();
tracer->setDepth(1);
// /tracer->setVerbose(true);
tracer->setAOMax(5);
tracer->setOccSamples(4);
tracer->setAO(true);
tracer->setBVHCache(false); // don't use cache
tracer->setCompactOp(false);
tracer->setShadowsOn(true);
setLight = true;
ctName = "";
tracer->setDefaultMaterial(Ka,Kd,Ks);
pointRadius = .1f;
lineWidth = .05f;
}
~eavlSceneRendererRT()
{
delete tracer;
}
void SetPointRadius(float r)
{
if(r > 0) pointRadius = r;
}
void SetBackGroundColor(float r, float g, float b)
{
tracer->setBackgroundColor(r,g,b);
}
virtual void SetActiveColor(eavlColor c)
{
glColor3fv(c.c);
glDisable(GL_TEXTURE_1D);
//cout<<"Setting Active Color"<<endl;
}
virtual void SetActiveColorTable(eavlColorTable ct)
{
eavlSceneRenderer::SetActiveColorTable(ct);
if(ct.GetName()!=ctName)
{
ctName=ct.GetName();
tracer->setColorMap3f(colors,ncolors);
//cout<<"Setting Active Color Table"<<endl;
}
}
virtual void StartScene()
{
//cout<<"Calling Start scene"<<endl;
//tracer->startScene();
}
virtual void StartTriangles()
{
//cout<<"Calling Start Tris"<<endl;
tracer->startScene();
}
virtual void EndTriangles()
{
//cout<<"Calling End Tris"<<endl;
}
virtual void AddTriangleVnVs(double x0, double y0, double z0,
double x1, double y1, double z1,
double x2, double y2, double z2,
double u0, double v0, double w0,
double u1, double v1, double w1,
double u2, double v2, double w2,
double s0, double s1, double s2)
{
tracer->scene->addTriangle(eavlVector3(x0,y0,z0) , eavlVector3(x1,y1,z1), eavlVector3(x2,y2,z2),
eavlVector3(u0,v0,w0) , eavlVector3(u1,v1,w1), eavlVector3(u2,v2,w2),
s0,s1,s2, "default");
}
virtual void StartPoints()
{
tracer->startScene();
}
virtual void EndPoints()
{
//glEnd();
}
virtual void AddPointVs(double x, double y, double z, double r, double s)
{
tracer->scene->addSphere(pointRadius,x,y,z,s,"default");
}
virtual void StartLines()
{
tracer->startScene();
}
virtual void EndLines()
{
//glEnd();
}
virtual void AddLineVs(double x0, double y0, double z0,
double x1, double y1, double z1,
double s0, double s1)
{
//cout<<"ADDING LINE"<<endl;
tracer->scene->addLine(lineWidth, eavlVector3(x0,y0,z0),s0, eavlVector3(x1,y1,z1),s1 );
}
virtual void Render()
{
int tframe = eavlTimer::Start();
tracer->setDefaultMaterial(Ka,Kd,Ks);
tracer->setResolution(view.h,view.w);
float magnitude=tracer->scene-><API key>();
tracer->setAOMax(magnitude*.2f);
/*Set up field of view: tracer takes the half FOV in degrees*/
float fovx= 2.f*atan(tan(view.view3d.fov/2.f)*view.w/view.h);
fovx*=180.f/M_PI;
tracer->setFOVy((view.view3d.fov*(180.f/M_PI))/2.f);
tracer->setFOVx( fovx/2.f );
tracer->setZoom(view.view3d.zoom);
eavlVector3 lookdir = (view.view3d.at - view.view3d.from).normalized();
eavlVector3 right = (lookdir % view.view3d.up).normalized();
/* Tracer is a lefty, so this is flip so down is not up */
eavlVector3 up = ( lookdir % right).normalized();
tracer->lookAtPos(view.view3d.at.x,view.view3d.at.y,view.view3d.at.z);
tracer->setCameraPos(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z);
tracer->setUp(up.x,up.y,up.z);
/*Otherwise the light will move with the camera*/
if(eyeLight)//setLight)
{
eavlVector3 minersLight(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z);
minersLight = minersLight+ up*magnitude*.3f;
tracer->setLightParams(minersLight.x,minersLight.y,minersLight.z, 1.f, 1.f, 0.f, 0.f); /*Light params: intensity, constant, linear and exponential coefficeints*/
}
else
{
tracer->setLightParams(Lx, Ly, Lz, 1.f, 1.f , 0.f , 0.f);
}
tracer->Execute();
cerr<<"\nTotal Frame Time : "<<eavlTimer::Stop(tframe,"")<<endl;
}
virtual unsigned char *GetRGBAPixels()
{
return (unsigned char *) tracer->getFrameBuffer()->GetHostArray();
}
virtual float *GetDepthPixels()
{
float proj22=view.P(2,2);
float proj23=view.P(2,3);
float proj32=view.P(3,2);
return (float *) tracer->getDepthBuffer(proj22,proj23,proj32)->GetHostArray();
}
};
#endif
|
module WavefrontOBJs
export loadOBJ, loadMTL, load_obj_mtl, numVertices, numFaces
include("geotypes.jl")
include("types.jl")
include("utils.jl")
include("obj.jl")
include("material.jl")
# convenience for loading OBJ and MTL simultaneously
function load_obj_mtl(fpath::ASCIIString)
objpath=string(fpath,".obj")
mtlpath=string(fpath,".mtl")
if !isfile(objpath)
error("OBJ file $objpath not found")
end
if !isfile(mtlpath)
error("MTL file $mtlpath not found")
end
loadOBJ(objpath), loadMTL(mtlpath)
end
end # module
|
var _ = require('lodash');
var requireAll = require('require-all');
function load(router, options) {
if (_.isString(options))
options = {dirname: options};
return requireAll(_.defaults(options, {
filter: /(.*Controller)\.js$/,
recursive: true,
resolve: function (Controller) {
var c = new (Controller.__esModule ? Controller.default : Controller)();
c.register && c.register(router);
return c;
}
}));
}
module.exports = load;
|
package net.java.jinterval.ir;
import com.cflex.util.lpSolve.LpConstant;
import com.cflex.util.lpSolve.LpModel;
import com.cflex.util.lpSolve.LpSolver;
import java.util.ArrayList;
//import org.apache.commons.math3.exception.<API key>;
//TODO: Add exceptions and throws
public class IRPredictor {
private double[][] X;
private double[] Y;
private double[] E;
private boolean dataAreGiven;
// Number of observations
private int ObsNumber;
// Number of variables
private int VarNumber;
// Storage for predictions
private double PredictionMin;
private double PredictionMax;
private double[] PredictionMins;
private double[] PredictionMaxs;
// Last error
int ExitCode;
public IRPredictor(){
ObsNumber = 0;
VarNumber = 0;
dataAreGiven = false;
}
public IRPredictor(double[][] X, double[] Y, double[] E){
setData(X,Y,E);
}
public final void setData(double[][] X, double[] Y, double[] E)
// throws <API key>
{
// if(X.length != Y.length || X.length != E.length)
// throw <API key>;
this.X=X;
this.Y=Y;
this.E=E;
ObsNumber = X.length;
VarNumber = X[0].length;
dataAreGiven = true;
}
public int getExitCode() {
return ExitCode;
}
private boolean solveLpp(double[] Objective)
// throws <API key>
{
if (Objective.length != VarNumber){
// throw <API key>;
ExitCode = -1;
return false;
}
try {
// Init LP Solver
LpModel Lpp = new LpModel(0, VarNumber);
// Define LPP
double[] zObjective = new double[VarNumber+1];
System.arraycopy(Objective, 0, zObjective, 1, VarNumber);
Lpp.setObjFn(zObjective);
double[] zX=new double[VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
System.arraycopy(X[i], 0, zX, 1, VarNumber);
Lpp.addConstraint(zX, LpConstant.LE, Y[i]+E[i]);
Lpp.addConstraint(zX, LpConstant.GE, Y[i]-E[i]);
// Solver.add_constraint(Lpp, zX, constant.LE, Y[i]+E[i]);
// Solver.add_constraint(Lpp, zX, constant.GE, Y[i]-E[i]);
}
//Solver.set_minim(Lpp);
//Lpp.setMinimum();
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
// ExitCode = Solver.solve(Lpp);
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMin = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
// Solver.set_maxim(Lpp);
Lpp.setMaximum();
ExitCode = Solver.solve();
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMax = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
} catch (Exception e){
//e.printStackTrace();
}
return ExitCode == LpConstant.OPTIMAL;
}
public boolean isDataConsistent(){
return solveLpp(X[0]);
}
public void compressData(){
}
public boolean predictAt(double[] x){
return solveLpp(x);
}
public boolean <API key>(){
PredictionMins = new double[ObsNumber];
PredictionMaxs = new double[ObsNumber];
boolean Solved = true;
for (int i=0; i<ObsNumber; i++){
Solved = Solved && predictAt(X[i]);
if(!Solved) {
break;
}
PredictionMins[i] = getMin();
PredictionMaxs[i] = getMax();
}
return Solved;
}
public double getMin(){
return PredictionMin;
}
public double getMax(){
return PredictionMax;
}
public double getMin(int i) {
return PredictionMins[i];
}
public double getMax(int i) {
return PredictionMaxs[i];
}
public double[] getMins() {
return PredictionMins;
}
public double[] getMaxs() {
return PredictionMaxs;
}
public double[] getResiduals(){
//Residuals=(y-(vmax+vmin)/2)/beta
double v;
double[] residuals = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMins[i]+PredictionMaxs[i])/2;
residuals[i] = (Y[i]-v)/E[i];
}
return residuals;
}
public double[] getLeverages(){
//Leverage=((vmax-vmin)/2)/beta
double v;
double[] leverages = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMaxs[i]-PredictionMins[i])/2;
leverages[i] = v/E[i];
}
return leverages;
}
public int[] getBoundary(){
final double EPSILON = 1.0e-6;
ArrayList<Integer> boundary = new ArrayList<Integer>();
double yp, ym, vp, vm;
for (int i=0; i<ObsNumber; i++){
yp = Y[i]+E[i];
vp = PredictionMaxs[i];
ym = Y[i]-E[i];
vm = PredictionMins[i];
if ( Math.abs(yp - vp) < EPSILON || Math.abs(ym - vm) < EPSILON ) {
boundary.add(1);
}
else {
boundary.add(0);
}
}
int[] a_boundary = new int[boundary.size()];
for (int i=0; i<a_boundary.length; i++){
a_boundary[i] = boundary.get(i).intValue();
}
return a_boundary;
}
public int[] getBoundaryNumbers(){
int Count = 0;
int[] boundary = getBoundary();
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
Count++;
}
}
int j = 0;
int[] numbers = new int[Count];
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
numbers[j++] = i;
}
}
return numbers;
}
//TODO: Implement getOutliers()
// public int[] getOutliers(){
//TODO: Implement getOutliersNumbers()
// public int[] getOutliersNumbers(){
public double[] getOutliersWeights(){
double[] outliers = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
outliers[i]=0;
}
try {
LpModel Lpp = new LpModel(0, ObsNumber+VarNumber);
// Build and set objective of LPP
double[] zObjective = new double[ObsNumber+VarNumber+1];
for(int i=1;i<=VarNumber; i++) {
zObjective[i] = 0;
}
for(int i=1;i<=ObsNumber; i++) {
zObjective[VarNumber+i] = 1;
}
Lpp.setObjFn(zObjective);
//Solver.set_minim(Lpp);
// Build and set constraints of LPP
double[] Row = new double[ObsNumber+VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
for (int j=1; j<=VarNumber; j++) {
Row[j]=X[i][j-1];
}
for(int j=1; j<=ObsNumber; j++) {
Row[VarNumber+j] = 0;
}
Row[VarNumber+i+1] = -E[i];
// Solver.add_constraint(Lpp, Row, constant.LE, Y[i]);
Lpp.addConstraint(Row, LpConstant.LE, Y[i]);
Row[VarNumber+i+1] = E[i];
// Solver.add_constraint(Lpp, Row, constant.GE, Y[i]);
Lpp.addConstraint(Row, LpConstant.GE, Y[i]);
for (int j=1; j<=ObsNumber+VarNumber; j++) {
Row[j] = 0;
}
Row[VarNumber+i+1] = 1;
// Solver.add_constraint(Lpp, Row, constant.GE, 1);
Lpp.addConstraint(Row, LpConstant.GE, 1);
}
// Solve LPP and get outliers' weights
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
for(int i = 0; i < ObsNumber; i++) {
outliers[i] = Lpp.getBestSolution(Lpp.getRows()+VarNumber+i+1);
}
} catch(Exception e){
//e.printStackTrace();
}
return outliers;
}
}
|
#include "compare.h"
#include "Sample.h"
#include <sqlpp11/sqlpp11.h>
#include <iostream>
namespace
{
auto getTrue() -> std::string
{
MockDb::<API key> printer = {};
return serialize(sqlpp::value(true), printer).str();
}
auto getFalse() -> std::string
{
MockDb::<API key> printer = {};
return serialize(sqlpp::value(false), printer).str();
}
} // namespace
int Where(int, char*[])
{
const auto foo = test::TabFoo{};
const auto bar = test::TabBar{};
// Unconditionally
compare(__LINE__, select(foo.omega).from(foo).unconditionally(), "SELECT tab_foo.omega FROM tab_foo");
compare(__LINE__, remove_from(foo).unconditionally(), "DELETE FROM tab_foo");
compare(__LINE__, update(foo).set(foo.omega = 42).unconditionally(), "UPDATE tab_foo SET omega=42");
compare(__LINE__, update(foo).set(foo.omega = foo.omega - -1).unconditionally(),
"UPDATE tab_foo SET omega=(tab_foo.omega - -1)");
compare(__LINE__, where(sqlpp::value(true)), " WHERE " + getTrue());
// Never
compare(__LINE__, where(sqlpp::value(false)), " WHERE " + getFalse());
// Sometimes
compare(__LINE__, where(bar.gamma), " WHERE tab_bar.gamma");
compare(__LINE__, where(bar.gamma == false), " WHERE (tab_bar.gamma=" + getFalse() + ")");
compare(__LINE__, where(bar.beta.is_null()), " WHERE (tab_bar.beta IS NULL)");
compare(__LINE__, where(bar.beta == "SQL"), " WHERE (tab_bar.beta='SQL')");
compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null("SQL"))), " WHERE (tab_bar.beta='SQL')");
compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null<sqlpp::text>(::sqlpp::null))),
" WHERE (tab_bar.beta IS NULL)");
#if __cplusplus >= 201703L
// string_view argument
std::string_view sqlString = "SQL";
compare(__LINE__, where(bar.beta == sqlString), " WHERE (tab_bar.beta='SQL')");
#endif
return 0;
}
|
#include <iostream>
#include <string>
#include <map>
#include <unistd.h>
#include <utility>
#include <sstream>
#include "./patricia-tree.hpp"
int main(void) {
std::cout << "Add new command!\n";
PatriciaTree<Node<std::string, StringKeySpec>> pt;
std::string command = "command";
std::string key;
while(command != "exit") {
getline(std::cin, key);
pt.insertNode(key, command);
std::cout << pt << "\n";
}
return 0;
}
|
# urlwatch
A Puppet module for managing urlwatch and urlwatch cronjobs. This module also supports urlwatch's
built-in filtering features (hooks.py).
# Module usage
Example using Hiera: monitor Trac WikiStart and RecentChanges pages for edits:
classes:
- urlwatch
urlwatch::userconfigs:
john:
hour: '*'
minute: '20'
urls:
trac_wikistart:
url: 'https://trac.example.org/openvpn/wiki/WikiStart'
filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago'
trac_recentchanges:
url: 'https://trac.example.org/openvpn/wiki/RecentChanges'
filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago'
If you want the email to user 'john' to go to a public address, you can use the
puppetfinland/postfix module:
classes:
- postfix
postfix::mailaliases:
john:
recipient: 'john@example.org'
For details please refer to [init.pp](manifests/init.pp) and [userconfig.pp](manifests/userconfig.pp).
If you want to use the cron functionality in this module you probably want to
set up some mail aliases. One way to do this is to use ::postfix::mailaliases
hash parameter in the Puppet-Finland [postfix module](https://github.com/Puppet-Finland/postfix).
|
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
|
#include "<API key>.h"
static void <API key>( struct <API key> *ss,
struct <API key> *vi,
enum <API key> *<API key> );
void <API key>( struct <API key> *ss,
enum <API key> query_type,
void *query_input,
void *query_output )
{
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : query_type can be any value in its range
<API key>;
switch( query_type )
{
case <API key>:
{
ptrdiff_t
se;
LFDS720_PAL_ASSERT( query_input == NULL );
LFDS720_PAL_ASSERT( query_output != NULL );
*(lfds720_pal_uint_t *) query_output = 0;
// TRD : count the elements on the stack_np
se = ss->top[LFDS720_MISC_OFFSET];
while( se != 0 )
{
( *(lfds720_pal_uint_t *) query_output )++;
se = <API key>( ss, se, struct <API key> )->next;
}
}
break;
case <API key>:
// TRD : query_input can be NULL
LFDS720_PAL_ASSERT( query_output != NULL );
<API key>( ss, (struct <API key> *) query_input, (enum <API key> *) query_output );
break;
}
return;
}
static void <API key>( struct <API key> *ss,
struct <API key> *vi,
enum <API key> *<API key> )
{
lfds720_pal_uint_t
number_elements = 0;
ptrdiff_t
se_slow,
se_fast;
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : vi can be NULL
LFDS720_PAL_ASSERT( <API key> != NULL );
*<API key> = <API key>;
se_slow = se_fast = ss->top[LFDS720_MISC_OFFSET];
/* TRD : first, check for a loop
we have two pointers
both of which start at the top of the stack_np
we enter a loop
and on each iteration
we advance one pointer by one element
and the other by two
we exit the loop when both pointers are NULL
(have reached the end of the stack_np)
or
if we fast pointer 'sees' the slow pointer
which means we have a loop
*/
if( se_slow != 0 )
do
{
// se_slow = ( (struct <API key> *) ( (void *) ss + se_slow ) )->next;
se_slow = <API key>( ss, se_slow, struct <API key> )->next;
if( se_fast != 0 )
// se_fast = ( (struct <API key> *) ( (void *) ss + se_fast ) )->next;
se_fast = <API key>( ss, se_fast, struct <API key> )->next;
if( se_fast != 0 )
// se_fast = ( (struct <API key> *) ( (void *) ss + se_fast ) )->next;
se_fast = <API key>( ss, se_fast, struct <API key> )->next;
}
while( se_slow != 0 and se_fast != se_slow );
if( se_fast != 0 and se_slow != 0 and se_fast == se_slow )
*<API key> = <API key>;
/* TRD : now check for expected number of elements
vi can be NULL, in which case we do not check
we know we don't have a loop from our earlier check
*/
if( *<API key> == <API key> and vi != NULL )
{
<API key>( ss, <API key>, NULL, (void *) &number_elements );
if( number_elements < vi->min_elements )
*<API key> = <API key>;
if( number_elements > vi->max_elements )
*<API key> = <API key>;
}
return;
}
|
package com.jme3.gde.core.properties;
import com.jme3.gde.core.scene.SceneApplication;
import com.jme3.scene.Spatial;
import java.beans.PropertyEditor;
import java.lang.reflect.<API key>;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.nodes.PropertySupport;
import org.openide.util.Exceptions;
/**
*
* @author normenhansen
*/
public class UserDataProperty extends PropertySupport.ReadWrite<String> {
private Spatial spatial;
private String name = "null";
private int type = 0;
private List<<API key>> listeners = new LinkedList<<API key>>();
public UserDataProperty(Spatial node, String name) {
super(name, String.class, name, "");
this.spatial = node;
this.name = name;
this.type = getObjectType(node.getUserData(name));
}
public static int getObjectType(Object type) {
if (type instanceof Integer) {
return 0;
} else if (type instanceof Float) {
return 1;
} else if (type instanceof Boolean) {
return 2;
} else if (type instanceof String) {
return 3;
} else if (type instanceof Long) {
return 4;
} else {
Logger.getLogger(UserDataProperty.class.getName()).log(Level.WARNING, "UserData not editable" + (type == null ? "null" : type.getClass()));
return -1;
}
}
@Override
public String getValue() throws <API key>, <API key> {
return spatial.getUserData(name) + "";
}
@Override
public void setValue(final String val) throws <API key>, <API key>, <API key> {
if (spatial == null) {
return;
}
try {
SceneApplication.getApplication().enqueue(new Callable<Void>() {
public Void call() throws Exception {
switch (type) {
case 0:
spatial.setUserData(name, Integer.parseInt(val));
break;
case 1:
spatial.setUserData(name, Float.parseFloat(val));
break;
case 2:
spatial.setUserData(name, Boolean.parseBoolean(val));
break;
case 3:
spatial.setUserData(name, val);
break;
case 4:
spatial.setUserData(name, Long.parseLong(val));
break;
default:
// throw new <API key>();
}
return null;
}
}).get();
notifyListeners(null, val);
} catch (<API key> ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public PropertyEditor getPropertyEditor() {
return null;
// return new <API key>(control);
}
public void <API key>(<API key> listener) {
listeners.add(listener);
}
public void <API key>(<API key> listener) {
listeners.remove(listener);
}
private void notifyListeners(Object before, Object after) {
for (Iterator<<API key>> it = listeners.iterator(); it.hasNext();) {
<API key> <API key> = it.next();
<API key>.propertyChange(getName(), before, after);
}
}
}
|
#ifndef <API key>
#define <API key>
#include "aos/common/controls/polytope.h"
#ifdef <API key>
#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#endif //<API key>
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/drivetrain/drivetrain_config.h"
namespace frc971 {
namespace control_loops {
namespace drivetrain {
class PolyDrivetrain {
public:
enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
PolyDrivetrain(const DrivetrainConfig &dt_config);
int controller_index() const { return loop_->controller_index(); }
bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
// Computes the speed of the motor given the hall effect position and the
// speed of the robot.
double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
double shifter_position, double velocity);
// Computes the states of the shifters for the left and right drivetrain sides
// given a requested state.
void UpdateGears(Gear requested_gear);
// Computes the next state of a shifter given the current state and the
// requested state.
Gear UpdateSingleGear(Gear requested_gear, Gear current_gear);
void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
#ifdef <API key>
void SetPosition(
const ::frc971::control_loops::DrivetrainQueue::Position *position);
#else //<API key>
void SetPosition(
const DrivetrainPosition *position);
#endif //<API key>
double FilterVelocity(double throttle);
double MaxVelocity();
void Update();
#ifdef <API key>
void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output);
#else //<API key>
void SendMotors(DrivetrainOutput *output);
#endif //<API key>
private:
StateFeedbackLoop<7, 2, 3> kf_;
const ::aos::controls::HPolytope<2> U_Poly_;
::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
const double ttrust_;
double wheel_;
double throttle_;
bool quickturn_;
int stale_count_;
double <API key>;
Gear left_gear_;
Gear right_gear_;
#ifdef <API key>
::frc971::control_loops::DrivetrainQueue::Position last_position_;
::frc971::control_loops::DrivetrainQueue::Position position_;
#else //<API key>
DrivetrainPosition last_position_;
DrivetrainPosition position_;
#endif //<API key>
int counter_;
DrivetrainConfig dt_config_;
};
} // namespace drivetrain
} // namespace control_loops
} // namespace frc971
#endif // <API key>
|
// modification, are permitted provided that the following conditions
// are met:
// the documentation and/or other materialsprovided with the
// distribution.
// "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
// 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 "minipy.h"
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
const char* prompt = ">>> ";
std::cout << "********** MiniPy 0.1 **********" << std::endl;
std::cout << prompt;
std::string command;
while (std::getline(std::cin, command)) {
if (command.empty())
;
else if (command == "exit")
break;
else
Py_Execute(command);
std::cout << prompt;
}
return 0;
}
|
class Xonsh < Formula
include Language::Python::Virtualenv
desc "Python-ish, <API key> shell language and command prompt"
homepage "https://xon.sh/"
url "https://github.com/xonsh/xonsh/archive/0.8.12.tar.gz"
sha256 "<SHA256-like>"
head "https://github.com/xonsh/xonsh.git"
bottle do
cellar :any_skip_relocation
sha256 "<SHA256-like>" => :mojave
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
end
depends_on "python"
# Resources based on `pip3 install xonsh[ptk,pygments,proctitle]`
resource "prompt_toolkit" do
url "https://files.pythonhosted.org/packages/d9/a5/<API key>/prompt_toolkit-2.0.7.tar.gz"
sha256 "<SHA256-like>"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/64/69/<API key>/Pygments-2.3.1.tar.gz"
sha256 "<SHA256-like>"
end
resource "setproctitle" do
url "https://files.pythonhosted.org/packages/5a/0d/<API key>/setproctitle-1.1.10.tar.gz"
sha256 "<SHA256-like>"
end
resource "six" do
url "https://files.pythonhosted.org/packages/dd/bf/<API key>/six-1.12.0.tar.gz"
sha256 "<SHA256-like>"
end
resource "wcwidth" do
url "https://files.pythonhosted.org/packages/55/11/<API key>/wcwidth-0.1.7.tar.gz"
sha256 "<SHA256-like>"
end
def install
<API key>
end
test do
assert_match "4", shell_output("#{bin}/xonsh -c 2+2")
end
end
|
#pragma once
#include <cstdio>
#include <stdint.h>
#define CUDA_CHECK_RETURN(value) { \
cudaError_t _m_cudaStat = value; \
if (_m_cudaStat != cudaSuccess) { \
fprintf(stderr, "Error %s at line %d in file %s\n", \
cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__); \
exit(1); \
} }
namespace cuda_common {
typedef struct {
uint32_t query_position;
uint32_t database_position;
} Coordinate;
enum Direction {
kFoward, kReverse,
};
static const size_t kMaxLoadLength = 4;
}
|
<?php
namespace Bacharu\Models;
use \Prajna\Objects\VIFMetrics as PrajnaVIFMetrics;
class VIFMetrics extends PrajnaVIFMetrics
{
public function __construct(){}
}
|
"""
sim_det_noise.py implements the noise simulation operator, OpSimNoise.
"""
import numpy as np
from ..op import Operator
from ..ctoast import <API key> as <API key>
from .. import timing as timing
class OpSimNoise(Operator):
"""
Operator which generates noise timestreams.
This passes through each observation and every process generates data
for its assigned samples. The dictionary for each observation should
include a unique 'ID' used in the random number generation. The
observation dictionary can optionally include a 'global_offset' member
that might be useful if you are splitting observations and want to
enforce reproducibility of a given sample, even when using
different-sized observations.
Args:
out (str): accumulate data to the cache with name <out>_<detector>.
If the named cache objects do not exist, then they are created.
realization (int): if simulating multiple realizations, the realization
index.
component (int): the component index to use for this noise simulation.
noise (str): PSD key in the observation dictionary.
"""
def __init__(self, out='noise', realization=0, component=0, noise='noise',
rate=None, altFFT=False):
# We call the parent class constructor, which currently does nothing
super().__init__()
self._out = out
self._oversample = 2
self._realization = realization
self._component = component
self._noisekey = noise
self._rate = rate
self._altfft = altFFT
def exec(self, data):
"""
Generate noise timestreams.
This iterates over all observations and detectors and generates
the noise timestreams based on the noise object for the current
observation.
Args:
data (toast.Data): The distributed data.
Raises:
KeyError: If an observation in data does not have noise
object defined under given key.
RuntimeError: If observations are not split into chunks.
"""
autotimer = timing.auto_timer(type(self).__name__)
for obs in data.obs:
obsindx = 0
if 'id' in obs:
obsindx = obs['id']
else:
print("Warning: observation ID is not set, using zero!")
telescope = 0
if 'telescope' in obs:
telescope = obs['telescope_id']
global_offset = 0
if 'global_offset' in obs:
global_offset = obs['global_offset']
tod = obs['tod']
if self._noisekey in obs:
nse = obs[self._noisekey]
else:
raise KeyError('Observation does not contain noise under '
'"{}"'.format(self._noisekey))
if tod.local_chunks is None:
raise RuntimeError('noise simulation for uniform distributed '
'samples not implemented')
# eventually we'll redistribute, to allow long correlations...
if self._rate is None:
times = tod.local_times()
else:
times = None
# Iterate over each chunk.
chunk_first = tod.local_samples[0]
for curchunk in range(tod.local_chunks[1]):
chunk_first += self.simulate_chunk(
tod=tod, nse=nse,
curchunk=curchunk, chunk_first=chunk_first,
obsindx=obsindx, times=times,
telescope=telescope, global_offset=global_offset)
return
def simulate_chunk(self, *, tod, nse, curchunk, chunk_first,
obsindx, times, telescope, global_offset):
"""
Simulate one chunk of noise for all detectors.
Args:
tod (toast.tod.TOD): TOD object for the observation.
nse (toast.tod.Noise): Noise object for the observation.
curchunk (int): The local index of the chunk to simulate.
chunk_first (int): First global sample index of the chunk.
obsindx (int): Observation index for random number stream.
times (int): Timestamps for effective sample rate.
telescope (int): Telescope index for random number stream.
global_offset (int): Global offset for random number stream.
Returns:
chunk_samp (int): Number of simulated samples
"""
autotimer = timing.auto_timer(type(self).__name__)
chunk_samp = tod.total_chunks[tod.local_chunks[0] + curchunk]
local_offset = chunk_first - tod.local_samples[0]
if self._rate is None:
# compute effective sample rate
rate = 1 / np.median(np.diff(
times[local_offset : local_offset+chunk_samp]))
else:
rate = self._rate
for key in nse.keys:
# Check if noise matching this PSD key is needed
weight = 0.
for det in tod.local_dets:
weight += np.abs(nse.weight(det, key))
if weight == 0:
continue
# Simulate the noise matching this key
#nsedata = <API key>(
# self._realization, telescope, self._component, obsindx,
# nse.index(key), rate, chunk_first+global_offset, chunk_samp,
# self._oversample, nse.freq(key), nse.psd(key),
# self._altfft)[0]
nsedata = <API key>(
self._realization, telescope, self._component, obsindx,
nse.index(key), rate, chunk_first+global_offset, chunk_samp,
self._oversample, nse.freq(key), nse.psd(key))
# Add the noise to all detectors that have nonzero weights
for det in tod.local_dets:
weight = nse.weight(det, key)
if weight == 0:
continue
cachename = '{}_{}'.format(self._out, det)
if tod.cache.exists(cachename):
ref = tod.cache.reference(cachename)
else:
ref = tod.cache.create(cachename, np.float64,
(tod.local_samples[1], ))
ref[local_offset : local_offset+chunk_samp] += weight*nsedata
del ref
return chunk_samp
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# modification, are permitted provided that the following conditions
# are met:
# the documentation and/or other materialsprovided with the
# distribution.
# "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
# 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 zmq
import time
if __name__ == '__main__':
ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://localhost:6666')
print 'all workers are ready ...'
while True:
try:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close()
|
class WireguardGo < Formula
desc "Userspace Go implementation of WireGuard"
homepage "https:
url "https://git.zx2c4.com/wireguard-go/snapshot/wireguard-go-0.0.20200320.tar.xz"
sha256 "<SHA256-like>"
license "MIT"
head "https://git.zx2c4.com/wireguard-go", using: :git
livecheck do
url :head
regex(/href=.*?wireguard-go[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
cellar :any_skip_relocation
sha256 "<SHA256-like>" => :catalina
sha256 "<SHA256-like>" => :mojave
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache"
system "make", "PREFIX=#{prefix}", "install"
end
test do
# ERROR: (notrealutun) Failed to create TUN device: no such file or directory
return if ENV["CI"]
assert_match "be utun", pipe_output("<API key>=1 #{bin}/wireguard-go notrealutun")
end
end
|
#include "pthread_impl.h"
int pthread_detach(pthread_t t)
{
/* Cannot detach a thread that's already exiting */
if (a_swap(t->exitlock, 1))
return pthread_join(t, 0);
t->detached = 2;
__unlock(t->exitlock);
return 0;
}
|
#!/bin/bash -e
# erik reed
# runs EM algorithm on hadoop streaming
if [ $# -ne 5 ]; then
echo Usage: $0 \"dir with net,tab,fg,em\" EM_FLAGS MAPPERS REDUCERS POP
echo "2 choices for EM_FLAGS: -u and -alem"
echo " -u corresponds to update; standard EM with fixed population size"
echo " e.g. a simple random restart with $POP BNs"
echo " -alem corresponds to Age-Layered EM with dynamic population size"
exit 1
fi
DAT_DIR=$1
EM_FLAGS=$2
MAPPERS=$3
REDUCERS=$4
# set to min_runs[0] if using ALEM
POP=$5
|
#ifndef <API key>
#define <API key>
#include <functional> // std::function
namespace sober {
namespace network {
namespace http {
using ExtraSuccessHandler = std::function<void()>;
} // namespace http
} // namespace network
} // namespace sober
#endif // <API key>
|
* DevOps
* DevOps
* DevOps
* DevOps
* Vagrant
* init
* box
* up
* ssh
* reload
* destroy
* port forward
* multi-machines
* DevOpsDevOps
* Vagrant
# DevOps
DevOps Developer + Operatior +
QA
DevOps
DevOps
DevQAOpsDev
BOSSjavaEEAPIjarwar
N
QAjava
DevOpscover
gradleapiCIjenkinsgo
artifactCD
PIPELINEQAjob
vagrantdockerjava
coverdevops
# DevOps
DevOps
LINUXBASHSHELL SCRIPT
CI
DevOps
# DevOps
DevOps
DevOps
DEVQAQA
QADev
CD
DevOps
# SESSION
5ITERATOR 0
PIPELINE
javajenkinsvagranttomcatgit
MACLINUX
|
package org.netmelody.neoclassycle.renderer;
import org.netmelody.neoclassycle.graph.StrongComponent;
/**
* Interface for rendering a {@link StrongComponent}.
*
* @author Franz-Josef Elmer
*/
public interface <API key> {
/** Renderes the specified {@link StrongComponent}. */
public String render(StrongComponent component);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ItzWarty.RAF
{
public class RAFFileListEntry
{
private byte[] <API key> = null;
private UInt32 offsetEntry = 0;
private RAF raf = null;
public RAFFileListEntry(RAF raf, byte[] <API key>, UInt32 offsetEntry)
{
this.raf = raf;
this.<API key> = <API key>;
this.offsetEntry = offsetEntry;
}
<summary>
Hash of the string name
</summary>
public UInt32 StringNameHash
{
get
{
return BitConverter.ToUInt32(<API key>, (int)offsetEntry);
}
}
<summary>
Offset to the start of the archived file in the data file
</summary>
public UInt32 FileOffset
{
get
{
return BitConverter.ToUInt32(<API key>, (int)offsetEntry+4);
}
}
<summary>
Size of this archived file
</summary>
public UInt32 FileSize
{
get
{
return BitConverter.ToUInt32(<API key>, (int)offsetEntry+8);
}
}
<summary>
Index of the name of the archvied file in the string table
</summary>
public UInt32 <API key>
{
get
{
return BitConverter.ToUInt32(<API key>, (int)offsetEntry+12);
}
}
public String GetFileName
{
get
{
return this.raf.GetDirectoryFile().GetStringTable()[this.<API key>];
}
}
}
}
|
// Intentionally left empty so that we can build a lib target for this library
#include "hashing/inc/hash.h"
|
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// Pinocchio is distributed in the hope that it will be
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Pinocchio If not, see
#ifndef __se3_se3_hpp__
#define __se3_se3_hpp__
#include <Eigen/Geometry>
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/skew.hpp"
namespace se3
{
/* Type returned by the "se3Action" and "se3ActionInverse" functions. */
namespace internal
{
template<typename D>
struct ActionReturn { typedef D Type; };
}
/** The rigid transform aMb can be seen in two ways:
*
* - given a point p expressed in frame B by its coordinate vector Bp, aMb
* computes its coordinates in frame A by Ap = aMb Bp.
* - aMb displaces a solid S centered at frame A into the solid centered in
* B. In particular, the origin of A is displaced at the origin of B: $^aM_b
* ^aA = ^aB$.
* The rigid displacement is stored as a rotation matrix and translation vector by:
* aMb (x) = aRb*x + aAB
* where aAB is the vector from origin A to origin B expressed in coordinates A.
*/
template< class Derived>
class SE3Base
{
protected:
typedef Derived Derived_t;
<API key>(Derived_t);
public:
Derived_t & derived() { return *static_cast<Derived_t*>(this); }
const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); }
const Angular_t & rotation() const { return derived().rotation_impl(); }
const Linear_t & translation() const { return derived().translation_impl(); }
Angular_t & rotation() { return derived().rotation_impl(); }
Linear_t & translation() { return derived().translation_impl(); }
void rotation(const Angular_t & R) { derived().rotation_impl(R); }
void translation(const Linear_t & R) { derived().translation_impl(R); }
Matrix4 toHomogeneousMatrix() const
{
return derived().<API key>();
}
operator Matrix4() const { return toHomogeneousMatrix(); }
Matrix6 toActionMatrix() const
{
return derived().toActionMatrix_impl();
}
operator Matrix6() const { return toActionMatrix(); }
void disp(std::ostream & os) const
{
static_cast<const Derived_t*>(this)->disp_impl(os);
}
Derived_t operator*(const Derived_t & m2) const { return derived().__mult__(m2); }
ay = aXb.act(by)
template<typename D>
typename internal::ActionReturn<D>::Type act (const D & d) const
{
return derived().act_impl(d);
}
by = aXb.actInv(ay)
template<typename D> typename internal::ActionReturn<D>::Type actInv(const D & d) const
{
return derived().actInv_impl(d);
}
Derived_t act (const Derived_t& m2) const { return derived().act_impl(m2); }
Derived_t actInv(const Derived_t& m2) const { return derived().actInv_impl(m2); }
bool operator == (const Derived_t & other) const
{
return derived().__equal__(other);
}
bool isApprox (const Derived_t & other) const
{
return derived().isApprox_impl(other);
}
friend std::ostream & operator << (std::ostream & os,const SE3Base<Derived> & X)
{
X.disp(os);
return os;
}
}; // class SE3Base
template<typename T, int U>
struct traits< SE3Tpl<T, U> >
{
typedef T Scalar_t;
typedef Eigen::Matrix<T,3,1,U> Vector3;
typedef Eigen::Matrix<T,4,1,U> Vector4;
typedef Eigen::Matrix<T,6,1,U> Vector6;
typedef Eigen::Matrix<T,3,3,U> Matrix3;
typedef Eigen::Matrix<T,4,4,U> Matrix4;
typedef Eigen::Matrix<T,6,6,U> Matrix6;
typedef Matrix3 Angular_t;
typedef Vector3 Linear_t;
typedef Matrix6 ActionMatrix_t;
typedef Eigen::Quaternion<T,U> Quaternion_t;
typedef SE3Tpl<T,U> SE3;
typedef ForceTpl<T,U> Force;
typedef MotionTpl<T,U> Motion;
typedef Symmetric3Tpl<T,U> Symmetric3;
enum {
LINEAR = 0,
ANGULAR = 3
};
}; // traits SE3Tpl
template<typename _Scalar, int _Options>
class SE3Tpl : public SE3Base< SE3Tpl< _Scalar, _Options > >
{
public:
friend class SE3Base< SE3Tpl< _Scalar, _Options > >;
<API key>(SE3Tpl);
SE3Tpl(): rot(), trans() {};
template<typename M3,typename v3>
SE3Tpl(const Eigen::MatrixBase<M3> & R, const Eigen::MatrixBase<v3> & p)
: rot(R), trans(p)
{
}
template<typename M4>
SE3Tpl(const Eigen::MatrixBase<M4> & m)
: rot(m.template block<3,3>(LINEAR,LINEAR)), trans(m.template block<3,1>(LINEAR,ANGULAR))
{
}
SE3Tpl(int) : rot(Matrix3::Identity()), trans(Vector3::Zero()) {}
template<typename S2, int O2>
SE3Tpl( const SE3Tpl<S2,O2> & clone )
: rot(clone.rotation()),trans(clone.translation()) {}
template<typename S2, int O2>
SE3Tpl & operator= (const SE3Tpl<S2,O2> & other)
{
rot = other.rotation ();
trans = other.translation ();
return *this;
}
static SE3Tpl Identity()
{
return SE3Tpl(1);
}
SE3Tpl & setIdentity () { rot.setIdentity (); trans.setZero (); return *this;}
aXb = bXa.inverse()
SE3Tpl inverse() const
{
return SE3Tpl(rot.transpose(), -rot.transpose()*trans);
}
static SE3Tpl Random()
{
Quaternion_t q(Vector4::Random());
q.normalize();
return SE3Tpl(q.matrix(),Vector3::Random());
}
SE3Tpl & setRandom ()
{
Quaternion_t q(Vector4::Random());
q.normalize ();
rot = q.matrix ();
trans.setRandom ();
return *this;
}
public:
Matrix4 <API key>() const
{
Matrix4 M;
M.template block<3,3>(LINEAR,LINEAR) = rot;
M.template block<3,1>(LINEAR,ANGULAR) = trans;
M.template block<1,3>(ANGULAR,LINEAR).setZero();
M(3,3) = 1;
return M;
}
Vb.toVector() = bXa.toMatrix() * Va.toVector()
Matrix6 toActionMatrix_impl() const
{
Matrix6 M;
M.template block<3,3>(ANGULAR,ANGULAR)
= M.template block<3,3>(LINEAR,LINEAR) = rot;
M.template block<3,3>(ANGULAR,LINEAR).setZero();
M.template block<3,3>(LINEAR,ANGULAR)
= skew(trans) * M.template block<3,3>(ANGULAR,ANGULAR);
return M;
}
void disp_impl(std::ostream & os) const
{
os << " R =\n" << rot << std::endl
<< " p = " << trans.transpose() << std::endl;
}
ay = aXb.act(by)
template<typename D>
typename internal::ActionReturn<D>::Type act_impl (const D & d) const
{
return d.se3Action(*this);
}
by = aXb.actInv(ay)
template<typename D> typename internal::ActionReturn<D>::Type actInv_impl(const D & d) const
{
return d.se3ActionInverse(*this);
}
Vector3 act_impl (const Vector3& p) const { return (rot*p+trans).eval(); }
Vector3 actInv_impl(const Vector3& p) const { return (rot.transpose()*(p-trans)).eval(); }
SE3Tpl act_impl (const SE3Tpl& m2) const { return SE3Tpl( rot*m2.rot,trans+rot*m2.trans);}
SE3Tpl actInv_impl (const SE3Tpl& m2) const { return SE3Tpl( rot.transpose()*m2.rot, rot.transpose()*(m2.trans-trans));}
SE3Tpl __mult__(const SE3Tpl & m2) const { return this->act(m2);}
bool __equal__( const SE3Tpl & m2 ) const
{
return (rotation_impl() == m2.rotation() && translation_impl() == m2.translation());
}
bool isApprox_impl( const SE3Tpl & m2 ) const
{
Matrix4 diff( <API key>() -
m2.<API key>());
return (diff.isMuchSmallerThan(<API key>(), 1e-14)
&& diff.isMuchSmallerThan(m2.<API key>(), 1e-14) );
}
public:
const Angular_t & rotation_impl() const { return rot; }
Angular_t & rotation_impl() { return rot; }
void rotation_impl(const Angular_t & R) { rot = R; }
const Linear_t & translation_impl() const { return trans;}
Linear_t & translation_impl() { return trans;}
void translation_impl(const Linear_t & p) { trans=p; }
protected:
Angular_t rot;
Linear_t trans;
}; // class SE3Tpl
typedef SE3Tpl<double,0> SE3;
} // namespace se3
#endif // ifndef __se3_se3_hpp__
|
/**
* @file urosNode.c
* @author Andrea Zoppi <texzk@email.it>
*
* @brief Node features of the middleware.
*/
/* HEADER FILES */
#include "../include/urosBase.h"
#include "../include/urosUser.h"
#include "../include/urosNode.h"
#include "../include/urosRpcCall.h"
#include "../include/urosRpcParser.h"
#include <string.h>
#define DEBUG 0
/* LOCAL TYPES & MACROS */
#if <API key> == UROS_FALSE && !defined(__DOXYGEN__)
#undef urosAssert
#define urosAssert(expr)
#endif
#if <API key> == UROS_FALSE && !defined(__DOXYGEN__)
#undef urosError
#define urosError(when, action, msgargs) { if (when) { action; } }
#endif
/* LOCAL VARIABLES */
/** @brief Node thread stack.*/
static UROS_STACK(urosNodeThreadStack, <API key>);
/** @brief XMLRPC Listener thread stack.*/
static UROS_STACK(xmlrpcListenerStack, <API key>);
/** @brief TCPROS Listener thread stack.*/
static UROS_STACK(tcprosListenerStack, <API key>);
/** @brief XMLRPC Slave server worker thread stacks.*/
static UROS_STACKPOOL(slaveMemPoolChunk, <API key>,
<API key>);
/** @brief TCPROS Client worker thread stacks.*/
static UROS_STACKPOOL(tcpcliMemPoolChunk, <API key>,
<API key>);
/** @brief TCPROS Server worker thread stacks.*/
static UROS_STACKPOOL(tcpsvrMemPoolChunk, <API key>,
<API key>);
/* GLOBAL VARIABLES */
/**
* @brief Node singleton.
*/
UrosNode urosNode;
/* LOCAL FUNCTIONS */
void <API key>(void) {
static UrosNodeStatus *const stp = &urosNode.status;
uros_err_t err;
(void)err;
urosAssert(stp->xmlrpcListenerId == UROS_NULL_THREADID);
urosAssert(stp->tcprosListenerId == UROS_NULL_THREADID);
/* Fill the worker thread pools.*/
#if DEBUG
sleep(1);
printf("%s\n", stp->tcpcliThdPool.namep);
#endif
/* Subscribe thread */
printf("Subscribe Thread ID\n");
err = <API key>(&stp->tcpcliThdPool);
urosAssert(err == UROS_OK);
/* Publish thread */
printf("Publish Thread ID\n");
err = <API key>(&stp->tcpsvrThdPool);
urosAssert(err == UROS_OK);
printf("Servece? Thread ID\n");
err = <API key>(&stp->slaveThdPool);
urosAssert(err == UROS_OK);
/* Spawn the XMLRPC Slave listener threads.*/
err = <API key>(&stp->xmlrpcListenerId,
"RpcSlaveLis",
<API key>,
(uros_proc_f)<API key>, NULL,
xmlrpcListenerStack,
<API key>);
urosAssert(err == UROS_OK);
/* Spawn the TCPROS listener thread.*/
err = <API key>(&stp->tcprosListenerId,
"TcpRosLis",
<API key>,
(uros_proc_f)<API key>, NULL,
tcprosListenerStack,
<API key>);
urosAssert(err == UROS_OK);
}
void <API key>(void) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
static UrosNodeStatus *const stp = &urosNode.status;
UrosConn conn;
uros_err_t err;
(void)err;
urosAssert(stp->xmlrpcListenerId != UROS_NULL_THREADID);
urosAssert(stp->tcprosListenerId != UROS_NULL_THREADID);
/* Join the XMLRPC Slave listener threads.*/
urosConnObjectInit(&conn);
urosConnCreate(&conn, UROS_PROTO_TCP);
urosConnConnect(&conn, &cfgp->xmlrpcAddr);
urosConnClose(&conn);
err = urosThreadJoin(stp->xmlrpcListenerId);
urosAssert(err == UROS_OK);
stp->xmlrpcListenerId = UROS_NULL_THREADID;
/* Join the TCPROS listener thread.*/
urosConnObjectInit(&conn);
urosConnCreate(&conn, UROS_PROTO_TCP);
urosConnConnect(&conn, &cfgp->tcprosAddr);
urosConnClose(&conn);
err = urosThreadJoin(stp->tcprosListenerId);
urosAssert(err == UROS_OK);
stp->tcprosListenerId = UROS_NULL_THREADID;
/* Join the worker thread pools.*/
err = <API key>(&stp->tcpcliThdPool);
urosAssert(err == UROS_OK);
err = <API key>(&stp->tcpsvrThdPool);
urosAssert(err == UROS_OK);
err = <API key>(&stp->slaveThdPool);
urosAssert(err == UROS_OK);
}
uros_err_t <API key>(void) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
UrosRpcResponse res;
uros_err_t err;
/* Check if the Master can reply to a getPid() request.*/
<API key>(&res);
err = urosRpcCallGetPid(
&cfgp->masterAddr,
&cfgp->xmlrpcUri,
&res
);
<API key>(&res);
return err;
}
void <API key>(void) {
/* Register topics.*/
<API key>();
<API key>();
/* Register services.*/
<API key>();
/* Register parameters.*/
<API key>();
}
void <API key>(void) {
static UrosNodeStatus *const stp = &urosNode.status;
UrosListNode *np;
UrosString exitMsg;
/* Get the exit message.*/
urosMutexLock(&stp->stateLock);
exitMsg = stp->exitMsg;
stp->exitMsg = urosStringAssignZ(NULL);
urosMutexUnlock(&stp->stateLock);
/* Exit from all the registered TCPROS worker threads.*/
urosMutexLock(&stp->pubTcpListLock);
for (np = stp->pubTcpList.headp; np != NULL; np = np->nextp) {
<API key>((UrosTcpRosStatus*)np->datap);
}
urosMutexUnlock(&stp->pubTcpListLock);
urosMutexLock(&stp->subTcpListLock);
for (np = stp->subTcpList.headp; np != NULL; np = np->nextp) {
<API key>((UrosTcpRosStatus*)np->datap);
}
urosMutexUnlock(&stp->subTcpListLock);
/* Call the shutdown function provided by the user.*/
urosUserShutdown(&exitMsg);
urosStringClean(&exitMsg);
/* Unregister topics.*/
<API key>();
<API key>();
/* Unregister services.*/
<API key>();
/* Unregister parameters.*/
<API key>();
}
/* GLOBAL FUNCTIONS */
/** @addtogroup node_funcs */
/**
* @brief Initializes a node object.
* @details This procedure:
* - loads a nullified configuration
* - initializes the status lists
* - initializes the status locks
* - initializes and allocates memory pools
* - initializes thread pools
*
* @pre The node has not been initialized yet.
*
* @param[in,out] np
* Pointer to the @p UrosNode to be initialized.
*/
void urosNodeObjectInit(UrosNode *np) {
UrosNodeStatus *stp;
urosAssert(np != NULL);
/* Invalidate configuration variables.*/
memset((void*)&np->config, 0, sizeof(UrosNodeConfig));
/* Initialize status variables.*/
stp = &np->status;
stp->state = UROS_NODE_UNINIT;
stp->xmlrpcPid = ~0;
urosListObjectInit(&stp->subTopicList);
urosListObjectInit(&stp->pubTopicList);
urosListObjectInit(&stp->pubServiceList);
urosListObjectInit(&stp->subParamList);
urosListObjectInit(&stp->subTcpList);
urosListObjectInit(&stp->pubTcpList);
stp->xmlrpcListenerId = UROS_NULL_THREADID;
stp->tcprosListenerId = UROS_NULL_THREADID;
urosMutexObjectInit(&stp->stateLock);
urosMutexObjectInit(&stp->xmlrpcPidLock);
urosMutexObjectInit(&stp->subTopicListLock);
urosMutexObjectInit(&stp->pubTopicListLock);
urosMutexObjectInit(&stp->pubServiceListLock);
urosMutexObjectInit(&stp->subParamListLock);
urosMutexObjectInit(&stp->subTcpListLock);
urosMutexObjectInit(&stp->pubTcpListLock);
stp->exitFlag = UROS_FALSE;
/* Initialize mempools with their description.*/
<API key>(&stp->slaveMemPool,
<API key>(<API key>),
NULL);
<API key>(&stp->tcpcliMemPool,
<API key>(<API key>),
NULL);
<API key>(&stp->tcpsvrMemPool,
<API key>(<API key>),
NULL);
/* Load the actual memory chunks for worker thread stacks.*/
<API key>(&stp->slaveMemPool, slaveMemPoolChunk,
<API key>);
<API key>(&stp->tcpcliMemPool, tcpcliMemPoolChunk,
<API key>);
<API key>(&stp->tcpsvrMemPool, tcpsvrMemPoolChunk,
<API key>);
/* Initialize thread pools.*/
<API key>(&stp->tcpcliThdPool, &stp->tcpcliMemPool,
(uros_proc_f)<API key>,
"TcpRosCli",
<API key>);
<API key>(&stp->tcpsvrThdPool, &stp->tcpsvrMemPool,
(uros_proc_f)<API key>,
"TcpRosSvr",
<API key>);
<API key>(&stp->slaveThdPool, &stp->slaveMemPool,
(uros_proc_f)<API key>,
"RpcSlaveSvr",
<API key>);
/* The node is initialized and stopped.*/
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_IDLE;
urosMutexUnlock(&stp->stateLock);
}
/**
* @brief Creates the main Node thread.
* @note Should be called at system startup, after @p urosInit().
*
* @return
* Error code.
*/
uros_err_t <API key>(void) {
urosAssert(urosNode.status.exitFlag == UROS_FALSE);
urosNode.status.exitFlag = UROS_FALSE;
return <API key>(
&urosNode.status.nodeThreadId, "urosNode",
<API key>,
(uros_proc_f)urosNodeThread, NULL,
urosNodeThreadStack, <API key>
);
}
/**
* @brief Node thread.
* @details This thread handles the whole life of the local node, including
* (un)registration (from)to the Master, thread pool magnagement,
* node shutdown, and so on.
*
* @param[in] argp
* Ignored.
* @return
* Error code.
*/
uros_err_t urosNodeThread(void *argp) {
static UrosNodeStatus *const stp = &urosNode.status;
uros_bool_t exitFlag;
(void)argp;
#if <API key>
urosMutexLock(&stp->stateLock);
urosAssert(stp->state == UROS_NODE_IDLE);
urosMutexUnlock(&stp->stateLock);
#endif
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_STARTUP;
urosMutexUnlock(&stp->stateLock);
/* Create the listener and pool threads.*/
<API key>();
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
while (!exitFlag) {
/* Check if the Master is alive.*/
if (<API key>() != UROS_OK) {
/* Add a delay not to flood in case of short timeouts.*/
urosThreadSleepSec(3);
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
continue;
}
/* Register to the Master.*/
<API key>();
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_RUNNING;
urosMutexUnlock(&stp->stateLock);
/* Check if the Master is alive every 3 seconds.*/
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
while (!exitFlag) {
#if <API key>
urosError(<API key>() != UROS_OK, break,
("Master node "UROS_IPFMT" lost\n",
UROS_IPARG(&urosNode.config.masterAddr.ip)));
#endif
urosThreadSleepMsec(<API key>);
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
}
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_SHUTDOWN;
urosMutexUnlock(&stp->stateLock);
/* Unregister from the Master*/
<API key>();
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
if (!exitFlag) {
/* The node has simply lost sight of the Master, restart.*/
stp->state = UROS_NODE_STARTUP;
}
urosMutexUnlock(&stp->stateLock);
}
/* Join listener and pool threads.*/
<API key>();
/* The node has shut down.*/
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_IDLE;
urosMutexUnlock(&stp->stateLock);
return UROS_OK;
}
/**
* @brief Loads the default node configuration.
* @details Any previously allocated data is freed, then the default node
* configuration is loaded.
*
* @pre The related @p UrosNode is initialized.
*
* @param[in,out] cfgp
* Pointer to the target configuration descriptor.
*/
void <API key>(UrosNodeConfig *cfgp) {
urosAssert(cfgp != NULL);
urosAssert(<API key> != <API key>);
/* Deallocate any previously allocated data.*/
urosStringClean(&cfgp->nodeName);
urosStringClean(&cfgp->xmlrpcUri);
urosStringClean(&cfgp->tcprosUri);
urosStringClean(&cfgp->masterUri);
/* Load default values.*/
cfgp->nodeName = urosStringCloneZ(UROS_NODE_NAME);
cfgp->xmlrpcAddr.ip.dword = <API key>;
cfgp->xmlrpcAddr.port = <API key>;
cfgp->xmlrpcUri = urosStringCloneZ(
"http://"<API key>
":"UROS_STRINGIFY2(<API key>));
cfgp->tcprosAddr.ip.dword = <API key>;
cfgp->tcprosAddr.port = <API key>;
cfgp->tcprosUri = urosStringCloneZ(
"rosrpc://"<API key>
":"UROS_STRINGIFY2(<API key>));
cfgp->masterAddr.ip.dword = <API key>;
cfgp->masterAddr.port = <API key>;
cfgp->masterUri = urosStringCloneZ(
"http://"<API key>
":"UROS_STRINGIFY2(<API key>));
}
/**
* @brief Publishes a topic.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see <API key>()
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[in] typep
* Pointer to the topic message type name string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *topicp;
const UrosMsgType *statictypep;
UrosListNode *topicnodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(!flags.service);
/* Get the registered message type.*/
statictypep = <API key>(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the topic already exists.*/
urosMutexLock(&np->status.pubTopicListLock);
topicnodep = <API key>(&np->status.pubTopicList, namep);
urosMutexUnlock(&np->status.pubTopicListLock);
urosError(topicnodep != NULL, return UROS_ERR_BADPARAM,
("Topic [%.*s] already published\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
topicp = urosNew(NULL, UrosTopic);
if (topicp == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(topicp);
topicp->name = urosStringClone(namep);
topicp->typep = statictypep;
topicp->procf = procf;
topicp->flags = flags;
/* Publish the topic.*/
err = <API key>(topicp);
if (err != UROS_OK) { urosTopicDelete(topicp); }
return err;
}
/**
* @brief Publishes a topic.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see <API key>()
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The TPCROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name null-terminated string.
* @param[in] typep
* Pointer to the topic message type name null-terminated string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
urosAssert(!flags.service);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return <API key>(&namestr, &typestr, procf, flags);
}
/**
* @brief Publishes a topic by its descriptor.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The topic descriptor must have the @p service flag set to @p 0.
* @post The topic descriptor is used the following way:
* - If successful, the topic descriptor is referenced by the topic
* registry, and is no longer modifiable by the caller function.
* - If unsuccessful, the topic descriptor can be deallocated by the
* caller function.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] topicp
* Pointer to the topic descriptor to be published and registered.
* @return
* Error code.
*/
uros_err_t <API key>(UrosTopic *topicp) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(topicp != NULL);
urosAssert(urosStringNotEmpty(&topicp->name));
urosAssert(topicp->typep != NULL);
urosAssert(urosStringNotEmpty(&topicp->typep->name));
urosAssert(topicp->procf != NULL);
urosAssert(!topicp->flags.service);
urosAssert(topicp->refcnt == 0);
urosAssert(topicp->refcnt == 0);
<API key>(&res);
urosMutexLock(&np->status.pubTopicListLock);
/* Master XMLRPC registerPublisher() */
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
&topicp->name,
&topicp->typep->name,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while registering as publisher of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the published topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
<API key>(nodep);
nodep->datap = (void*)topicp;
urosListAdd(&np->status.pubTopicList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.pubTopicListLock);
<API key>(&res);
return err;
}
/**
* @brief Unpublishes a topic.
* @details Issues an @p unpublishTopic() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a string which names the topic.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *topicnodep;
UrosTopic *topicp;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the topic descriptor.*/
urosMutexLock(&np->status.pubTopicListLock);
topicnodep = <API key>(&np->status.pubTopicList, namep);
if (topicnodep == NULL) {
urosError(topicnodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Topic [%.*s] not published\n", UROS_STRARG(namep)));
}
topicp = (UrosTopic*)topicnodep->datap;
/* Unregister the topic on the Master node.*/
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, UROS_NOP,
("Error %s while unregistering as publisher of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the topic locally.*/
topicp->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.pubTopicList, topicnodep);
urosAssert(tcprosnodep == topicnodep);
if (topicp->refcnt > 0) {
/* Tell each publishing TCPROS thread to exit.*/
urosMutexLock(&np->status.pubTcpListLock);
for (tcprosnodep = np->status.pubTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.pubTcpListLock);
/* NOTE: The last exiting thread freeds the topic descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.pubTopicListLock);
return err;
}
/**
* @brief Unpublishes a topic.
* @details Issues an @p unpublishTopic() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a null-terminated string which names the topic.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return <API key>(&namestr);
}
/**
* @brief Subscribes to a topic.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @see <API key>()
* @see <API key>()
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[in] typep
* Pointer to the topic message type name string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *topicp;
const UrosMsgType *statictypep;
UrosListNode *topicnodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(!flags.service);
/* Get the registered message type.*/
statictypep = <API key>(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the topic already exists.*/
urosMutexLock(&np->status.subTopicListLock);
topicnodep = <API key>(&np->status.subTopicList, namep);
urosMutexUnlock(&np->status.subTopicListLock);
urosError(topicnodep != NULL, return UROS_ERR_BADPARAM,
("Topic [%.*s] already subscribed\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
topicp = urosNew(NULL, UrosTopic);
if (topicp == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(topicp);
topicp->name = urosStringClone(namep);
topicp->typep = statictypep;
topicp->procf = procf;
topicp->flags = flags;
/* Subscribe to the topic.*/
err = <API key>(topicp);
if (err != UROS_OK) { urosTopicDelete(topicp); }
return err;
}
/**
* @brief Subscribes to a topic.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @see <API key>()
* @see <API key>()
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name null-terminated string.
* @param[in] typep
* Pointer to the topic message type name null-terminated string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
urosAssert(!flags.service);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return <API key>(&namestr, &typestr, procf, flags);
}
/**
* @brief Subscribes to a topic by its descriptor.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @see <API key>()
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @pre The topic descriptor must have the @p service flag set to @p 0.
* @post The topic descriptor is used the following way:
* - If successful, the topic descriptor is referenced by the topic
* registry, and is no longer modifiable by the caller function.
* - If unsuccessful, the topic descriptor can be deallocated by the
* caller function.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] topicp
* Pointer to the topic descriptor to be subscribed to and registered.
* @return
* Error code.
*/
uros_err_t <API key>(UrosTopic *topicp) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosList newpubs;
UrosListNode *nodep;
urosAssert(topicp != NULL);
urosAssert(urosStringNotEmpty(&topicp->name));
urosAssert(topicp->typep != NULL);
urosAssert(urosStringNotEmpty(&topicp->typep->name));
urosAssert(topicp->procf != NULL);
urosAssert(!topicp->flags.service);
urosAssert(topicp->refcnt == 0);
<API key>(&res);
urosListObjectInit(&newpubs);
urosMutexLock(&np->status.subTopicListLock);
/* Master XMLRPC registerSubscriber() */
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
&topicp->name,
&topicp->typep->name,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot register as subscriber of topic [%.*s]\n",
UROS_STRARG(&topicp->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Connect to registered publishers.*/
err = <API key>(&topicp->name, res.valuep, &newpubs);
urosError(err != UROS_OK, goto _finally,
("Error %s while finding new publishers of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
<API key>(&res);
err = <API key>(&topicp->name, &newpubs);
urosError(err != UROS_OK, goto _finally,
("Error %s while connecting to new publishers of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
/* Add to the subscribed topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
<API key>(nodep);
nodep->datap = (void*)topicp;
urosListAdd(&np->status.subTopicList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subTopicListLock);
urosListClean(&newpubs, (uros_delete_f)urosFree);
<API key>(&res);
return err;
}
/**
* @brief Unsubscribes to a topic.
* @details Issues an @p <API key>() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no subscribing TCPROS threads, or
* - by the last subscribing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a string which names the topic.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *topicnodep;
UrosTopic *topicp;
UrosTcpRosStatus *tcpstp;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the topic descriptor.*/
urosMutexLock(&np->status.subTopicListLock);
topicnodep = <API key>(&np->status.subTopicList, namep);
if (topicnodep == NULL) {
urosError(topicnodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Topic [%.*s] not subscribed\n", UROS_STRARG(namep)));
}
topicp = (UrosTopic*)topicnodep->datap;
/* Unregister the topic on the Master node.*/
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, UROS_NOP,
("Error %s while unregistering as subscriber of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the topic locally.*/
topicp->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.subTopicList, topicnodep);
urosAssert(tcprosnodep == topicnodep);
if (topicp->refcnt > 0) {
/* Tell each subscribing TCPROS thread to exit.*/
urosMutexLock(&np->status.subTcpListLock);
for (tcprosnodep = np->status.subTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.subTcpListLock);
/* NOTE: The last exiting thread freeds the topic descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.subTopicListLock);
return err;
}
/**
* @brief Unsubscribes to a topic.
* @details Issues an @p <API key>() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no subscribing TCPROS threads, or
* - by the last subscribing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a null-terminated string which names the topic.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return <API key>(&namestr);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] namep
* Pointer to the service name string.
* @param[in] typep
* Pointer to the service type name string.
* @param[in] callf
* Service call handler.
* @param[in] flags
* TCPROS flags. The @p service flag must be set, and @p persistent
* must be clear.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t urosNodeCallService(const UrosString *namep,
const UrosString *typep,
uros_tcpsrvcall_t callf,
uros_topicflags_t flags,
void *resobjp) {
UrosTopic service;
UrosAddr pubaddr;
const UrosMsgType *statictypep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(callf != NULL);
urosAssert(flags.service);
urosAssert(!flags.persistent);
urosAssert(resobjp != NULL);
/* Get the registered message type.*/
statictypep = <API key>(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown service type [%.*s]\n", UROS_STRARG(typep)));
/* Resolve the service provider.*/
err = <API key>(namep, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
urosTopicObjectInit(&service);
service.name = *namep;
service.typep = statictypep;
service.procf = (uros_proc_f)callf;
service.flags = flags;
return <API key>(&pubaddr, &service, resobjp);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] namep
* Pointer to the service name null-terminated string.
* @param[in] typep
* Pointer to the service type name null-terminated string.
* @param[in] callf
* Service call handler.
* @param[in] flags
* TCPROS flags. The @p service flag must be set, and @p persistent
* must be clear.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep,
const char *typep,
uros_tcpsrvcall_t callf,
uros_topicflags_t flags,
void *resobjp) {
UrosTopic service;
UrosAddr pubaddr;
const UrosMsgType *statictypep;
uros_err_t err;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(callf != NULL);
urosAssert(flags.service);
urosAssert(!flags.persistent);
urosAssert(resobjp != NULL);
/* Get the registered message type.*/
statictypep = <API key>(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown service type [%s]\n", typep));
/* Resolve the service provider.*/
urosTopicObjectInit(&service);
service.name = urosStringAssignZ(namep);
err = <API key>(&service.name, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
service.typep = statictypep;
service.procf = (uros_proc_f)callf;
service.flags = flags;
return <API key>(&pubaddr, &service, resobjp);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre @p servicep->procf must address a @p uros_tcpsrvcall_t function.
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] servicep
* Pointer to the service descriptor.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosTopic *servicep,
void *resobjp) {
UrosAddr pubaddr;
uros_err_t err;
urosAssert(servicep != NULL);
urosAssert(urosStringNotEmpty(&servicep->name));
urosAssert(servicep->typep != NULL);
urosAssert(urosStringNotEmpty(&servicep->typep->name));
urosAssert(servicep->procf != NULL);
urosAssert(servicep->flags.service);
urosAssert(!servicep->flags.persistent);
urosAssert(resobjp != NULL);
/* Resolve the service provider.*/
err = <API key>(&servicep->name, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
return <API key>(&pubaddr, servicep, resobjp);
}
/**
* @brief Publishes a service.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see <API key>()
* @see <API key>()
*
* @pre The service is not published.
* @pre The TCPROS @p service flag must be set.
*
* @param[in] namep
* Pointer to the service name string.
* @param[in] typep
* Pointer to the service type name string.
* @param[in] procf
* Service handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *servicep;
const UrosMsgType *statictypep;
UrosListNode *servicenodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(flags.service);
/* Get the registered service type.*/
statictypep = <API key>(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the service already exists.*/
urosMutexLock(&np->status.pubServiceListLock);
servicenodep = <API key>(&np->status.pubServiceList,
namep);
urosMutexUnlock(&np->status.pubServiceListLock);
urosError(servicenodep != NULL, return UROS_ERR_BADPARAM,
("Service [%.*s] already published\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
servicep = urosNew(NULL, UrosTopic);
if (servicep == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(servicep);
servicep->name = urosStringClone(namep);
servicep->typep = statictypep;
servicep->procf = procf;
servicep->flags = flags;
/* Try to register the topic.*/
err = <API key>(servicep);
if (err != UROS_OK) { urosTopicDelete(servicep); }
return err;
}
/**
* @brief Publishes a service.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see <API key>()
* @see <API key>()
*
* @pre The service is not published.
* @pre The TCPROS @p service flag must be set.
*
* @param[in] namep
* Pointer to the service name null-terminated string.
* @param[in] typep
* Pointer to the service type name null-terminated string.
* @param[in] procf
* Service handler function.
* @param[in] flags
* Service flags.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return <API key>(&namestr, &typestr, procf, flags);
}
/**
* @brief Publishes a service by its descriptor.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see <API key>()
*
* @pre The TCPROS @p service flag must be set.
*
* @pre The service is not published.
* @pre The service descriptor must have the @p service flag set to @p 1.
* @post - If successful, the service descriptor is referenced by the
* service registry, and is no longer modifiable by the caller
* function.
* - If unsuccessful, the service descriptor can be deallocated by the
* caller function.
*
* @param[in] servicep
* Pointer to the service descriptor to be published and registered.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosTopic *servicep) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(servicep != NULL);
urosAssert(urosStringNotEmpty(&servicep->name));
urosAssert(servicep->typep != NULL);
urosAssert(urosStringNotEmpty(&servicep->typep->name));
urosAssert(servicep->procf != NULL);
urosAssert(servicep->flags.service);
<API key>(&res);
urosMutexLock(&np->status.pubServiceListLock);
/* Master XMLRPC registerPublisher() */
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
&servicep->name,
&np->config.tcprosUri,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot register service [%.*s]\n",
UROS_STRARG(&servicep->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the published topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
<API key>(nodep);
nodep->datap = (void*)servicep;
urosListAdd(&np->status.pubServiceList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.pubServiceListLock);
<API key>(&res);
return err;
}
/**
* @brief Unpublishes a service.
* @details Issues an @p unregisterService() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
*
* @pre The service is published.
* @post If successful, the service descriptor is dereferenced by the
* service registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the
* service.
*
* @param[in] namep
* Pointer to a string which names the service.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *servicenodep;
UrosTopic *servicep;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the service descriptor.*/
urosMutexLock(&np->status.pubServiceListLock);
servicenodep = <API key>(&np->status.pubServiceList,
namep);
urosError(servicenodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Service [%.*s] not published\n", UROS_STRARG(namep)));
servicep = (UrosTopic*)servicenodep->datap;
/* Unregister the service on the Master node.*/
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.tcprosUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while unregistering as publisher of service [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the service locally.*/
servicep->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.pubServiceList, servicenodep);
urosAssert(tcprosnodep == servicenodep);
if (np->status.pubTcpList.length > 0) {
/* Tell each publishing TCPROS thread to exit.*/
urosMutexLock(&np->status.pubTcpListLock);
for (tcprosnodep = np->status.pubTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == servicep && tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.pubTcpListLock);
/* NOTE: The last exiting thread freeds the service descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(servicenodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.pubServiceListLock);
return err;
}
/**
* @brief Unpublishes a service.
* @details Issues an @p unregisterService() call to the XMLRPC Master.
* @see <API key>()
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
*
* @pre The service is published.
* @post If successful, the service descriptor is dereferenced by the
* service registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the
* service.
*
* @param[in] namep
* Pointer to a null-terminated string which names the service.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return <API key>(&namestr);
}
/**
* @brief Subscribes to a parameter by its descriptor.
* @details Issues a @p subscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @see <API key>()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has not been registered yet.
*
* @param[in] namep
* Pointer to the parameter name string.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosString *clonednamep;
UrosListNode *paramnodep;
UrosRpcResponse res;
UrosListNode *nodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
/* Check if the parameter already exists.*/
urosMutexLock(&np->status.subParamListLock);
paramnodep = <API key>(&np->status.subParamList, namep);
urosMutexUnlock(&np->status.subParamListLock);
urosError(paramnodep != NULL, return UROS_ERR_BADPARAM,
("Parameter [%.*s] already subscribed\n", UROS_STRARG(namep)));
/* Create the storage data in advance.*/
clonednamep = urosNew(NULL, UrosString);
if (clonednamep == NULL) { return UROS_ERR_NOMEM; }
*clonednamep = urosStringClone(namep);
nodep = urosNew(NULL, UrosListNode);
if (clonednamep->datap == NULL || nodep == NULL) {
urosStringDelete(clonednamep); urosFree(nodep);
return UROS_ERR_NOMEM;
}
/* Subscribe to the topic.*/
<API key>(&res);
urosMutexLock(&np->status.subParamListLock);
/* Master XMLRPC registerSubscriber() */
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
&np->config.xmlrpcUri,
namep,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while subscribing to parameter [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the subscribed parameter list.*/
<API key>(nodep);
nodep->datap = (void*)clonednamep;
urosListAdd(&np->status.subParamList, nodep);
/* Update to the current value.*/
urosUserParamUpdate(namep, res.valuep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subParamListLock);
<API key>(&res);
return err;
}
/**
* @brief Subscribes to a parameter.
* @details Issues a @p subscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @see <API key>()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has not been registered yet.
*
* @param[in] namep
* Pointer to the parameter name null-terminated string.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return <API key>(&namestr);
}
/**
* @brief Subscribes to a parameter.
* @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has been registered.
* @post If successful, the parameter descriptor is unreferenced and deleted
* by the parameter registry.
*
* @param[in] namep
* Pointer to a string which names the parameter to be unregistered.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(urosStringNotEmpty(namep));
<API key>(&res);
urosMutexLock(&np->status.subParamListLock);
/* Check if the parameter was actually subscribed.*/
nodep = <API key>(&np->status.subParamList, namep);
urosError(nodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; },
("Parameter [%.*s] not found\n", UROS_STRARG(namep)));
/* Master XMLRPC registerSubscriber() */
err = <API key>(
&np->config.masterAddr,
&np->config.nodeName,
&np->config.xmlrpcUri,
namep,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot unsubscribe from param [%.*s]\n",
UROS_STRARG(namep)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %ld, expected %d\n",
(long int)res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %ld, expected 200\n",
(long int)res.httpcode));
/* Remove from the subscribed parameter list and delete.*/
nodep = urosListRemove(&np->status.subParamList, nodep);
urosAssert(nodep != NULL);
urosListNodeDelete(nodep, (uros_delete_f)urosStringDelete);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subParamListLock);
<API key>(&res);
return err;
}
/**
* @brief Subscribes to a parameter.
* @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see <API key>()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has been registered.
* @post If successful, the parameter descriptor is unreferenced and deleted
* by the parameter registry.
*
* @param[in] namep
* Pointer to a null-terminated string which names the parameter to be
* unregistered.
* @return
* Error code.
*/
uros_err_t <API key>(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return <API key>(&namestr);
}
/**
* @brief Find new publishers for a given topic.
* @details Scans through the provided publishers list to look for any new
* publishers.
*
* @param[in] namep
* Pointer to a non-empty string which names the targeted topic.
* @param[in] publishersp
* Pointer to an @p UrosRpcParam with @p UROS_RPCP_ARRAY pclass.
* It contains the list of current publishers, received for example
* through a XMLRPC call to @p subscribeTopic(). Each publisher is
* addressed by its URI.
* @param[out] newpubsp
* Pointer to an empty list which will be populated by the newly
* discovered publishers, if any.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep,
const UrosRpcParam *publishersp,
UrosList *newpubsp) {
static UrosNode *const np = &urosNode;
uros_err_t err;
const UrosListNode *tcpnodep;
const UrosRpcParamNode *paramnodep;
const UrosTcpRosStatus *tcpstp, *tcpfoundp;
const UrosString *urip;
UrosAddr pubaddr;
(void)err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(publishersp != NULL);
urosAssert(publishersp->pclass == UROS_RPCP_ARRAY);
urosAssert(publishersp->value.listp != NULL);
urosAssert(urosListIsValid(newpubsp));
urosAssert(newpubsp->length == 0);
/* Build a list of newly discovered publishers.*/
urosMutexLock(&np->status.subTcpListLock);
for (paramnodep = publishersp->value.listp->headp;
paramnodep != NULL;
paramnodep = paramnodep->nextp) {
urip = ¶mnodep->param.value.string;
err = urosUriToAddr(urip, &pubaddr);
urosAssert(err == UROS_OK);
tcpfoundp = NULL;
for (tcpnodep = np->status.subTcpList.headp;
tcpnodep != NULL;
tcpnodep = tcpnodep->nextp) {
tcpstp = (const UrosTcpRosStatus *)tcpnodep->datap;
if (tcpstp->topicp->flags.service == UROS_FALSE) {
urosAssert(tcpstp->topicp != NULL);
if (0 == urosStringCmp(&tcpstp->topicp->name, namep)) {
urosAssert(tcpstp->csp != NULL);
if (tcpstp->csp->remaddr.ip.dword == pubaddr.ip.dword &&
tcpstp->csp->remaddr.port == pubaddr.port) {
tcpfoundp = tcpstp;
}
}
}
}
if (tcpfoundp == NULL) {
UrosAddr *addrp;
UrosListNode *nodep;
/* New publisher.*/
addrp = urosNew(NULL, UrosAddr);
if (addrp == NULL) {
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_ERR_NOMEM;
}
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) {
urosFree(addrp);
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_ERR_NOMEM;
}
*addrp = pubaddr;
nodep->datap = addrp;
nodep->nextp = NULL;
urosListAdd(newpubsp, nodep);
}
}
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_OK;
}
/**
* @brief Gets the TCPROS URI of a topic publisher.
* @details Requests the TCPROS URI of a topic published by a node.
*
* @param[in] apiaddrp
* XMLRPC API address of the target node.
* @param[in] namep
* Pointer to the topic name string.
* @param[out] tcprosaddrp
* Pointer to an allocated @p UrosAddr descriptor, which will hold the
* TCPROS API address of the requested topic provider.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosAddr *apiaddrp,
const UrosString *namep,
UrosAddr *tcprosaddrp) {
static const UrosRpcParamNode tcprosnode = {
{ UROS_RPCP_STRING, {{ 6, "TCPROS" }} }, NULL
};
static const UrosRpcParamList tcproslist = {
(UrosRpcParamNode*)&tcprosnode, (UrosRpcParamNode*)&tcprosnode, 1
};
static const UrosRpcParamNode protonode = {
{ UROS_RPCP_ARRAY, {{ (size_t)&tcproslist, NULL }} }, NULL
};
static const UrosRpcParamList protolist = {
(UrosRpcParamNode*)&protonode, (UrosRpcParamNode*)&protonode, 1
};
uros_err_t err;
UrosRpcParamNode *nodep;
UrosRpcParam *paramp;
UrosRpcResponse res;
urosAssert(apiaddrp != NULL);
urosAssert(urosStringNotEmpty(namep));
urosAssert(tcprosaddrp != NULL);
#define _ERR { err = UROS_ERR_BADPARAM; goto _finally; }
/* Request the topic to the publisher.*/
<API key>(&res);
err = <API key>(
apiaddrp,
&urosNode.config.nodeName,
namep,
&protolist,
&res
);
/* Check for valid values.*/
if (err != UROS_OK) { goto _finally; }
urosError(res.httpcode != 200, _ERR,
("The HTTP response code is %lu, expected 200\n",
(long unsigned int)res.httpcode));
if (res.code != UROS_RPCC_SUCCESS) { _ERR }
urosError(res.valuep->pclass != UROS_RPCP_ARRAY, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_ARRAY)\n",
(int)res.valuep->pclass, (int)UROS_RPCP_ARRAY));
urosAssert(res.valuep->value.listp != NULL);
urosError(res.valuep->value.listp->length != 3, _ERR,
("Response value array length %lu, expected 3",
(long unsigned int)res.valuep->value.listp->length));
nodep = res.valuep->value.listp->headp;
/* Check the protocol string.*/
paramp = &nodep->param; nodep = nodep->nextp;
urosError(paramp->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)paramp->pclass, (int)UROS_RPCP_STRING));
urosError(0 != urosStringCmp(&tcprosnode.param.value.string,
¶mp->value.string), _ERR,
("Response protocol is [%.*s], expected [TCPROS]\n",
UROS_STRARG(&tcprosnode.param.value.string)));
/* Check the node hostname string.*/
paramp = &nodep->param; nodep = nodep->nextp;
urosError(paramp->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)paramp->pclass, (int)UROS_RPCP_STRING));
err = urosHostnameToIp(¶mp->value.string, &tcprosaddrp->ip);
urosError(err != UROS_OK, goto _finally,
("Cannot resolve hostname [%.*s]",
UROS_STRARG(¶mp->value.string)));
/* Check the node port number.*/
paramp = &nodep->param;
urosError(paramp->pclass != UROS_RPCP_INT, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_INT)\n",
(int)paramp->pclass, (int)UROS_RPCP_INT));
urosError(paramp->value.int32 < 0 || paramp->value.int32 > 65535, _ERR,
("Port number %ld outside range\n",
(long int)paramp->value.int32));
tcprosaddrp->port = (uint16_t)paramp->value.int32;
err = UROS_OK;
_finally:
<API key>(&res);
return err;
#undef _ERR
}
/**
* @brief Gets the TCPROS URI of a service publisher.
* @details Requests the TCPROS URI of a service published by a node.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[out] pubaddrp
* Pointer to an allocated @p UrosAddr descriptor, which will hold the
* TCPROS API address of the requested service provider.
* @return
* Error code.
*/
uros_err_t <API key>(const UrosString *namep,
UrosAddr *pubaddrp) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
uros_err_t err;
UrosRpcResponse res;
UrosString *uristrp;
urosAssert(urosStringNotEmpty(namep));
urosAssert(pubaddrp != NULL);
#define _ERR { err = UROS_ERR_BADPARAM; goto _finally; }
/* Lookup the service URI.*/
<API key>(&res);
err = <API key>(
&cfgp->masterAddr,
&cfgp->nodeName,
namep,
&res
);
/* Check for valid values.*/
if (err != UROS_OK) { goto _finally; }
urosError(res.httpcode != 200, _ERR,
("The HTTP response code is %lu, expected 200\n",
(long unsigned int)res.httpcode));
urosError(res.code != UROS_RPCC_SUCCESS, _ERR,
("Cannot find a provider for service [%.*s]\n",
UROS_STRARG(namep)));
urosError(res.valuep->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)res.valuep->pclass, (int)UROS_RPCP_STRING));
uristrp = &res.valuep->value.string;
res.valuep->value.string = urosStringAssignZ(NULL);
<API key>(&res);
urosAssert(urosStringIsValid(uristrp));
urosError(uristrp->length == 0, _ERR, ("Service URI string is empty\n"));
/* Resolve the service address.*/
err = urosUriToAddr(uristrp, pubaddrp);
_finally:
<API key>(&res);
return err;
#undef _ERR
}
|
package org.mastodon.tracking.mamut.trackmate.wizard;
import org.mastodon.mamut.model.Link;
import org.mastodon.mamut.model.Model;
import org.mastodon.mamut.model.Spot;
import org.mastodon.model.<API key>;
public class <API key>
{
private static final int N_STARTING_CELLS = 6;
private static final int N_DIVISIONS = 17;
private static final int <API key> = 5;
private static final double VELOCITY = 5;
private static final double RADIUS = 3;
private final Model model;
public <API key>()
{
this.model = new Model();
}
public Model run()
{
return run( N_STARTING_CELLS, N_DIVISIONS, <API key> );
}
public Model run( final int nStartingCells, final int nDivisions, final int nFramesPerDivision )
{
new <API key>< Model >( model ){{ startImport(); }};
final Spot tmp = model.getGraph().vertexRef();
for ( int ic = 0; ic < nStartingCells; ic++ )
{
final double angle = 2d * ic * Math.PI / N_STARTING_CELLS;
final double vx = VELOCITY * Math.cos( angle );
final double vy = VELOCITY * Math.sin( angle );
// final int nframes = N_DIVISIONS * <API key>;
final double x = 0.; // nframes * VELOCITY + vx;
final double y = 0.; // nframes * VELOCITY + vy;
final double z = N_DIVISIONS * VELOCITY;
final double[] pos = new double[] { x, y, z };
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
final Spot mother = model.getGraph().addVertex( tmp ).init( 0, pos, cov );
addBranch( mother, vx, vy, 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( tmp );
new <API key>< Model >( model ){{ finishImport(); }};
return model;
}
private void addBranch( final Spot start, final double vx, final double vy, final int iteration, final int nDivisions, final int nFramesPerDivision )
{
if ( iteration >= nDivisions ) { return; }
final Spot previousSpot = model.getGraph().vertexRef();
final Spot spot = model.getGraph().vertexRef();
final Spot daughter = model.getGraph().vertexRef();
final Link link = model.getGraph().edgeRef();
final double[] pos = new double[ 3 ];
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
// Extend
previousSpot.refTo( start );
for ( int it = 0; it < nFramesPerDivision; it++ )
{
pos[ 0 ] = previousSpot.getDoublePosition( 0 ) + vx;
pos[ 1 ] = previousSpot.getDoublePosition( 1 ) + vy;
pos[ 2 ] = previousSpot.getDoublePosition( 2 );
final int frame = previousSpot.getTimepoint() + 1;
model.getGraph().addVertex( spot ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, spot, link ).init();
previousSpot.refTo( spot );
}
// Divide
for ( int id = 0; id < 2; id++ )
{
final double sign = id == 0 ? 1 : -1;
final double x;
final double y;
final double z;
if ( iteration % 2 == 0 )
{
x = previousSpot.getDoublePosition( 0 );
y = previousSpot.getDoublePosition( 1 );
z = previousSpot.getDoublePosition( 2 ) + sign * VELOCITY * ( 1 - 0.5d * iteration / nDivisions ) * 2;
}
else
{
x = previousSpot.getDoublePosition( 0 ) - sign * vy * ( 1 - 0.5d * iteration / nDivisions ) * 2;
y = previousSpot.getDoublePosition( 1 ) + sign * vx * ( 1 - 0.5d * iteration / nDivisions ) * 2;
z = previousSpot.getDoublePosition( 2 );
}
final int frame = previousSpot.getTimepoint() + 1;
pos[ 0 ] = x;
pos[ 1 ] = y;
pos[ 2 ] = z;
model.getGraph().addVertex( daughter ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, daughter, link ).init();
addBranch( daughter, vx, vy, iteration + 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( previousSpot );
model.getGraph().releaseRef( spot );
model.getGraph().releaseRef( daughter );
model.getGraph().releaseRef( link );
}
public static void main( final String[] args )
{
final <API key> clme = new <API key>();
final long start = System.currentTimeMillis();
final Model model = clme.run();
final long end = System.currentTimeMillis();
System.out.println( "Model created in " + ( end - start ) + " ms." );
System.out.println( "Total number of spots: " + model.getGraph().vertices().size() );
System.out.println( String.format( "Total memory used by the model: %.1f MB", ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / 1e6d ) );
}
}
|
#ifndef IMAGE_H_
#define IMAGE_H_
#include <cstdlib>
#include <vector>
#include <fstream>
#include <iostream>
#include "bfutils.h"
#include "cmd.h"
#include <string.h>
class Section{
public:
Section(std::vector<Cmd> &SectionCmd, uint16_t MemoryBase, uint16_t MemorySize);
Section(std::vector<uint16_t> &SectionData,
uint16_t MemoryBase, uint16_t MemorySize);
Section(std::fstream &File);
~Section();
uint8_t GetType(){return Hdr.type;};
uint16_t GetFileBase(){return Hdr.FileBase;};
uint16_t GetMemoryBase(){return Hdr.MemoryBase;};
uint16_t GetFileSize(){return Hdr.FileSize;};
uint16_t GetMemorySize(){return Hdr.MemorySize;};
void WriteHeader(std::fstream &File);
void WriteData(std::fstream &File);
uint16_t *GetData(){return Data;};
bool Error(){return err;};
private:
bool err;
BfSection_t Hdr;
uint16_t *Data;
};
class Image{
public:
Image(std::fstream &File, bool hex);
Image(uint8_t _machine);
~Image();
void AddSection(Section §ion);
uint8_t GetSectionNum(void){return Hdr.SectionNum;};
Section &GetSection(uint8_t section){return Sections[section];};
void SetIpEntry(ADDRESS_TYPE Ptr){Hdr.IpEntry = Ptr;};
void SetApEntry(ADDRESS_TYPE Ptr){Hdr.ApEntry = Ptr;};
ADDRESS_TYPE GetIpEntry(){return Hdr.IpEntry;};
ADDRESS_TYPE GetApEntry(){return Hdr.ApEntry;};
bool ReadHex(std::fstream &File);
void Write(std::fstream &File);
bool Error(){return err;};
private:
bool m_hex;
bool err;
BfHeader_t Hdr;
std::vector<Section> Sections;
};
#endif //IMAGE_H_
|
#{extends 'main.html' /} #{set title:'FAQ' /}
#{set faq:'active'/}
#{set title:'FAQ'/}
<div class="page-header">
<h1>Frequently Asked Questions
<a class="btn btn-primary login pull-right" href="@{Login.auth()}">Login with Dropbox</a>
<a class="btn btn-primary login pull-right" href="@{Login.boxAuth()}">Login with Box</a>
</h1>
</div>
<div class="well faq">
<h3>What is SortMyBox?</h3>
<p>SortMyBox is a magic folder inside your cloud storage folder.
Save new files there and we will move them based on rules you create.
Like e-mail filters, for your Dropbox.</p>
<h3>How does SortMyBox work?</h3>
<p>We check the contents of your SortMyBox folder every 15 minutes. If there are any files that match any of your
rules, we will move them to their correct location. We also log all file moves so you never lose a file.</p>
<h3>Is SortMyBox for me?</h3>
<p>Yes! Whether you're keeping your photos and videos organized or sharing documents with other people, SortMyBox will keep your files organized.</p>
<h3>How do I begin?</h3>
<p>Login using your <a href="@{Login.login()}">Dropbox</a> or <a href="@{Login.boxAuth()}">Box</a> account and
we will create a SortMyBox folder and some sample rules for you.
Save your files in this folder and you're good to go.</p>
<h3>Why do I have to provide access for my Dropbox/Box account?</h3>
<p>SortMyBox needs permission to move files around and put them in the appropriate folders. SortMyBox will never use your access for any other purposes.</p>
<h3>What sorting options do I have?</h3>
<p>We have 3 kinds of rules: </p>
<dl class="dl-horizontal">
<dt>Name Contains:</dt>
<dd>Move similarly named files to an appropriate folder.</dd>
<dd>A rule with the pattern <code>venice 2011</code> matches files named
<code>jen birthday venice 2011.jpg</code> or
<code>gondola venice 2011.jpg</code>.</dd>
<dt>Extension equals:</dt>
<dd>Files with a matching extension will be moved to an appropriate folder.</dd>
<dd>A rule with the extension <code>doc</code> matches files named
<code>science report final.doc</code> or
<code>resume.doc</code>, <strong>but not</strong>
<code>doc brown with marty.jpg</code>.</dd>
<dt>Name Pattern:</dt>
<dd>Use wildcards like <code>?</code> and <code>*</code> to move files to an appropriate folder. <code>?</code> matches a single letter/number/symbol/character whereas <code>*</code> can match any number of them.</dd>
<dd>The pattern <code>Prince*.mp3</code> matches <code>Prince - Purple rain.mp3</code> or <code>Prince.mp3</code>,
<strong>but not</strong> <code>Prince.doc</code> or <code>Best of Prince.mp3</code>.</dd>
<dd>The pattern <code>error?.txt</code> matches <code>error.txt</code> or <code>errors.txt</code>,
<strong>but not</strong> <code>errorss.txt</code> or <code>new error.txt</code>.</dd>
</dl>
<h3>Is SortMyBox free?</h3>
<p>Yes.</p>
<h3>Open source?</h3>
<p>SortMyBox is open source and BSD licensed, you can find it on <a href ="https://github.com/mustpax/sortmybox"> GitHub.</a></p>
<p>You can even run it on your own Google AppEngine instance. Instructions forthcoming!</p>
<h3>How do I contact you?</h3>
<p>You can <a href = "mailto: ${play.configuration.getProperty("sortbox.email")}" >email us</a>
or find us on <a href = "http://twitter.com/sortmybox">Twitter</a>.</p>
<h3>Anything else?</h3>
<p>Yes, please help us spread the word and share SortMyBox with other Dropbox & Box users! </p>
</div>
|
// the following conditions are met:
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file spline.h
*
* \brief Contains definition and partial implementaiton of sirius::Spline class.
*/
#ifndef __SPLINE_H__
#define __SPLINE_H__
// TODO: add back() method like in std::vector
// TODO: [?] store radial grid, not the pointer to the grid.
namespace sirius {
Cubic spline with a not-a-knot boundary conditions.
/** The following convention for spline coefficients is used: between points
* \f$ x_i \f$ and \f$ x_{i+1} \f$ the value of the spline is equal to
* \f$ a_i + b_i(x_{i+1} - x_i) + c_i(x_{i+1}-x_i)^2 + d_i(x_{i+1}-x_i)^3 \f$.
*/
template <typename T, typename U = double>
class Spline
{
private:
Radial grid.
Radial_grid<U> const* radial_grid_{nullptr};
mdarray<T, 2> coeffs_;
/* forbid copy constructor */
Spline(Spline<T, U> const& src__) = delete;
/* forbid assigment operator */
Spline<T, U>& operator=(Spline<T, U> const& src__) = delete;
Solver tridiagonal system of linear equaitons.
int solve(T* dl, T* d, T* du, T* b, int n)
{
for (int i = 0; i < n - 1; i++) {
if (std::abs(dl[i]) == 0) {
if (std::abs(d[i]) == 0) {
return i + 1;
}
} else if (std::abs(d[i]) >= std::abs(dl[i])) {
T mult = dl[i] / d[i];
d[i + 1] -= mult * du[i];
b[i + 1] -= mult * b[i];
if (i < n - 2) {
dl[i] = 0;
}
} else {
T mult = d[i] / dl[i];
d[i] = dl[i];
T tmp = d[i + 1];
d[i + 1] = du[i] - mult * tmp;
if (i < n - 2) {
dl[i] = du[i + 1];
du[i + 1] = -mult * dl[i];
}
du[i] = tmp;
tmp = b[i];
b[i] = b[i + 1];
b[i + 1] = tmp - mult * b[i + 1];
}
}
if (std::abs(d[n - 1]) == 0) {
return n;
}
b[n - 1] /= d[n - 1];
if (n > 1) {
b[n - 2] = (b[n - 2] - du[n - 2] * b[n - 1]) / d[n - 2];
}
for (int i = n - 3; i >= 0; i
b[i] = (b[i] - du[i] * b[i + 1] - dl[i] * b[i + 2]) / d[i];
}
return 0;
}
public:
Default constructor.
Spline()
{
}
Constructor of a new empty spline.
Spline(Radial_grid<U> const& radial_grid__) : radial_grid_(&radial_grid__)
{
coeffs_ = mdarray<T, 2>(num_points(), 4);
coeffs_.zero();
}
Constructor of a spline from a function.
Spline(Radial_grid<U> const& radial_grid__, std::function<T(U)> f__) : radial_grid_(&radial_grid__)
{
coeffs_ = mdarray<T, 2>(num_points(), 4);
for (int i = 0; i < num_points(); i++) {
U x = (*radial_grid_)[i];
coeffs_(i, 0) = f__(x);
}
interpolate();
}
Constructor of a spline from a list of values.
Spline(Radial_grid<U> const& radial_grid__, std::vector<T> const& y__) : radial_grid_(&radial_grid__)
{
assert(radial_grid_->num_points() == (int)y__.size());
coeffs_ = mdarray<T, 2>(num_points(), 4);
for (int i = 0; i < num_points(); i++) {
coeffs_(i, 0) = y__[i];
}
interpolate();
}
Move constructor.
Spline(Spline<T, U>&& src__)
{
radial_grid_ = src__.radial_grid_;
coeffs_ = std::move(src__.coeffs_);
}
Move assigment operator.
Spline<T, U>& operator=(Spline<T, U>&& src__)
{
if (this != &src__) {
radial_grid_ = src__.radial_grid_;
coeffs_ = std::move(src__.coeffs_);
}
return *this;
}
Spline<T, U>& operator=(std::function<T(U)> f__)
{
for (int ir = 0; ir < radial_grid_->num_points(); ir++) {
U x = (*radial_grid_)[ir];
coeffs_(ir, 0) = f__(x);
}
return this->interpolate();
}
Integrate with r^m weight.
T integrate(int m__) const
{
std::vector<T> g(num_points());
return integrate(g, m__);
}
inline std::vector<T> values() const
{
std::vector<T> a(num_points());
for (int i = 0; i < num_points(); i++) {
a[i] = coeffs_(i, 0);
}
return std::move(a);
}
Return number of spline points.
inline int num_points() const
{
return radial_grid_->num_points();
}
inline std::array<T, 4> coeffs(int i__) const
{
return {coeffs_(i__, 0), coeffs_(i__, 1), coeffs_(i__, 2), coeffs_(i__, 3)};
}
inline mdarray<T, 2> const& coeffs() const
{
return coeffs_;
}
inline double x(int i__) const
{
return (*radial_grid_)[i__];
}
inline double dx(int i__) const
{
return radial_grid_->dx(i__);
}
inline T operator()(U x) const
{
int j = radial_grid_->index_of(x);
if (j == -1) {
TERMINATE("point not found");
}
U dx = x - (*radial_grid_)[j];
return (*this)(j, dx);
}
Return value at \f$ x_i \f$.
inline T& operator[](const int i)
{
return coeffs_(i, 0);
}
inline T operator[](const int i) const
{
return coeffs_(i, 0);
}
inline T operator()(const int i, U dx) const
{
assert(i >= 0);
assert(i < num_points() - 1);
assert(dx >= 0);
return coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3)));
}
inline T deriv(const int dm, const int i, const U dx) const
{
assert(i >= 0);
assert(i < num_points() - 1);
assert(dx >= 0);
T result = 0;
switch (dm) {
case 0: {
result = coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3)));
break;
}
case 1: {
result = coeffs_(i, 1) + (coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 3.0) * dx;
break;
}
case 2: {
result = coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 6.0;
break;
}
case 3: {
result = coeffs_(i, 3) * 6.0;
break;
}
default: {
TERMINATE("wrong order of derivative");
break;
}
}
return result;
}
inline T deriv(int dm, int i) const
{
assert(i >= 0);
assert(i < num_points());
assert(radial_grid_ != nullptr);
if (i == num_points() - 1) {
return deriv(dm, i - 1, radial_grid_->dx(i - 1));
} else {
return deriv(dm, i, 0);
}
}
inline Radial_grid<U> const& radial_grid() const
{
return *radial_grid_;
}
Spline<T, U>& interpolate()
{
int np = num_points();
/* lower diagonal */
std::vector<T> dl(np - 1);
/* main diagonal */
std::vector<T> d(np);
/* upper diagonal */
std::vector<T> du(np - 1);
std::vector<T> x(np);
std::vector<T> dy(np - 1);
/* derivative of y */
for (int i = 0; i < np - 1; i++) {
dy[i] = (coeffs_(i + 1, 0) - coeffs_(i, 0)) / radial_grid_->dx(i);
}
/* setup "B" vector of AX=B equation */
for (int i = 0; i < np - 2; i++) {
x[i + 1] = (dy[i + 1] - dy[i]) * 6.0;
}
x[0] = -x[1];
x[np - 1] = -x[np - 2];
/* main diagonal of "A" matrix */
for (int i = 0; i < np - 2; i++) {
d[i + 1] = static_cast<T>(2) * (static_cast<T>(radial_grid_->dx(i)) + static_cast<T>(radial_grid_->dx(i + 1)));
}
U h0 = radial_grid_->dx(0);
U h1 = radial_grid_->dx(1);
U h2 = radial_grid_->dx(np - 2);
U h3 = radial_grid_->dx(np - 3);
d[0] = (h1 / h0) * h1 - h0;
d[np - 1] = (h3 / h2) * h3 - h2;
/* subdiagonals of "A" matrix */
for (int i = 0; i < np - 1; i++) {
du[i] = static_cast<T>(radial_grid_->dx(i));
dl[i] = static_cast<T>(radial_grid_->dx(i));
}
du[0] = -(h1 * (1.0 + h1 / h0) + d[1]);
dl[np - 2] = -(h3 * (1.0 + h3 / h2) + d[np - 2]);
/* solve tridiagonal system */
//solve(a.data(), b.data(), c.data(), d.data(), np);
//auto& x = d;
//int info = linalg<CPU>::gtsv(np, 1, &a[0], &b[0], &c[0], &d[0], np);
int info = solve(&dl[0], &d[0], &du[0], &x[0], np);
if (info) {
std::stringstream s;
s << "error in tridiagonal solver: " << info;
TERMINATE(s);
}
for (int i = 0; i < np - 1; i++) {
coeffs_(i, 2) = x[i] / 2.0;
T t = (x[i + 1] - x[i]) / 6.0;
coeffs_(i, 1) = dy[i] - (coeffs_(i, 2) + t) * radial_grid_->dx(i);
coeffs_(i, 3) = t / radial_grid_->dx(i);
}
coeffs_(np - 1, 1) = 0;
coeffs_(np - 1, 2) = 0;
coeffs_(np - 1, 3) = 0;
return *this;
}
inline void scale(double a__)
{
for (int i = 0; i < num_points(); i++) {
coeffs_(i, 0) *= a__;
coeffs_(i, 1) *= a__;
coeffs_(i, 2) *= a__;
coeffs_(i, 3) *= a__;
}
}
T integrate_simpson() const
{
std::vector<U> w(num_points(), 0);
for (int i = 0; i < num_points() - 2; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U x2 = (*radial_grid_)[i + 2];
w[i] += (2 * x0 + x1 - 3 * x2) * (x1 - x0) / (x0 - x2) / 6;
w[i + 1] += (x0 - x1) * (x0 + 2 * x1 - 3 * x2) / 6 / (x2 - x1);
w[i + 2] += std::pow(x0 - x1, 3) / 6 / (x2 - x0) / (x2 - x1);
}
//for (int i = 1; i < num_points() - 1; i++) {
// w[i] *= 0.5;
T res{0};
for (int i = 0; i < num_points(); i++) {
res += w[i] * coeffs_(i, 0);
}
return res;
}
T integrate_simple() const
{
T res{0};
for (int i = 0; i < num_points() - 1; i++) {
U dx = radial_grid_->dx(i);
res += 0.5 * (coeffs_(i, 0) + coeffs_(i + 1, 0)) * dx;
}
return res;
}
T integrate(std::vector<T>& g__, int m__) const
{
g__ = std::vector<T>(num_points());
g__[0] = 0.0;
switch (m__) {
case 0: {
T t = 1.0 / 3.0;
for (int i = 0; i < num_points() - 1; i++) {
U dx = radial_grid_->dx(i);
g__[i + 1] = g__[i] + (((coeffs_(i, 3) * dx * 0.25 + coeffs_(i, 2) * t) * dx + coeffs_(i, 1) * 0.5) * dx + coeffs_(i, 0)) * dx;
}
break;
}
case 2: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
U x0_2 = x0 * x0;
U x0_3 = x0_2 * x0;
U x1_2 = x1 * x1;
U x1_3 = x1_2 * x1;
g__[i + 1] = g__[i] + (20.0 * a0 * (x1_3 - x0_3) + 5.0 * a1 * (x0 * x0_3 + x1_3 * (3.0 * dx - x0)) -
dx * dx * dx * (-2.0 * a2 * (x0_2 + 3.0 * x0 * x1 + 6.0 * x1_2) -
a3 * dx * (x0_2 + 4.0 * x0 * x1 + 10.0 * x1_2))) / 60.0;
}
break;
}
case -1: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-1)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
g__[i + 1] = g__[i] + (dx / 6.0) * (6.0 * a1 + x0 * (-9.0 * a2 + 11.0 * a3 * x0) + x1 * (3.0 * a2 - 7.0 * a3 * x0 + 2.0 * a3 * x1)) +
(-a0 + x0 * (a1 + x0 * (-a2 + a3 * x0))) * std::log(x0 / x1);
}
break;
}
case -2: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-2)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + (((x0 - x1) * (-2.0 * a0 + x0 * (2.0 * a1 - 2.0 * a2 * (x0 + x1) +
// a3 * (2.0 * std::pow(x0, 2) + 5.0 * x0 * x1 - std::pow(x1, 2)))) +
// 2.0 * x0 * (a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1 * std::log(x1 / x0)) /
// (2.0 * x0 * x1));
g__[i + 1] = g__[i] + (a2 * dx - 5.0 * a3 * x0 * dx / 2.0 - a1 * (dx / x1) + a0 * (dx / x0 / x1) +
(x0 / x1) * dx * (a2 - a3 * x0) + a3 * x1 * dx / 2.0) +
(a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * std::log(x1 / x0);
}
break;
}
case -3: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-3)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + (-((x0 - x1) * (a0 * (x0 + x1) + x0 * (a1 * (-x0 + x1) +
// x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 +
// 2.0 * a3 * std::pow(x1, 2)))) + 2.0 * std::pow(x0, 2) * (a2 - 3.0 * a3 * x0) * std::pow(x1, 2) *
// std::log(x0 / x1)) / (2.0 * std::pow(x0, 2) * std::pow(x1, 2)));
g__[i + 1] = g__[i] + dx * (a0 * (x0 + x1) + x0 * (a1 * dx +
x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 +
2.0 * a3 * std::pow(x1, 2)))) / std::pow(x0 * x1, 2) / 2.0 +
(-a2 + 3.0 * a3 * x0) * std::log(x0 / x1);
}
break;
}
case -4: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-4)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + ((2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) +
// x0 * (x0 - x1) * (a1 * (x0 - x1) * (2.0 * x0 + x1) +
// x0 * (-2.0 * a2 * std::pow(x0 - x1, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 +
// 11.0 * std::pow(x1, 2)))) + 6.0 * a3 * std::pow(x0 * x1, 3) * std::log(x1 / x0)) /
// (6.0 * std::pow(x0 * x1, 3)));
g__[i + 1] = g__[i] + (2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) -
x0 * dx * (-a1 * dx * (2.0 * x0 + x1) +
x0 * (-2.0 * a2 * std::pow(dx, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 +
11.0 * std::pow(x1, 2))))) / std::pow(x0 * x1, 3) / 6.0 +
a3 * std::log(x1 / x0);
}
break;
}
default: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(m)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
g__[i + 1] = g__[i] + (std::pow(x0, 1 + m__) * (-(a0 * double((2 + m__) * (3 + m__) * (4 + m__))) +
x0 * (a1 * double((3 + m__) * (4 + m__)) - 2.0 * a2 * double(4 + m__) * x0 +
6.0 * a3 * std::pow(x0, 2)))) / double((1 + m__) * (2 + m__) * (3 + m__) * (4 + m__)) +
std::pow(x1, 1 + m__) * ((a0 - x0 * (a1 + x0 * (-a2 + a3 * x0))) / double(1 + m__) +
((a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1) / double(2 + m__) +
((a2 - 3.0 * a3 * x0) * std::pow(x1, 2)) / double(3 + m__) +
(a3 * std::pow(x1, 3)) / double(4 + m__));
}
break;
}
}
return g__[num_points() - 1];
}
uint64_t hash() const
{
return coeffs_.hash();
}
#ifdef __GPU
void copy_to_device()
{
coeffs_.allocate_on_device();
coeffs_.copy_to_device();
}
void <API key>(int thread_id__)
{
coeffs_.allocate_on_device();
coeffs_.<API key>(thread_id__);
}
#endif
};
template <typename T>
inline Spline<T> operator*(Spline<T> const& a__, Spline<T> const& b__)
{
//assert(a__.radial_grid().hash() == b__.radial_grid().hash());
Spline<double> s12(a__.radial_grid());
auto& coeffs_a = a__.coeffs();
auto& coeffs_b = b__.coeffs();
auto& coeffs = const_cast<mdarray<double, 2>&>(s12.coeffs());
for (int ir = 0; ir < a__.radial_grid().num_points(); ir++) {
coeffs(ir, 0) = coeffs_a(ir, 0) * coeffs_b(ir, 0);
coeffs(ir, 1) = coeffs_a(ir, 1) * coeffs_b(ir, 0) + coeffs_a(ir, 0) * coeffs_b(ir, 1);
coeffs(ir, 2) = coeffs_a(ir, 2) * coeffs_b(ir, 0) + coeffs_a(ir, 1) * coeffs_b(ir, 1) + coeffs_a(ir, 0) * coeffs_b(ir, 2);
coeffs(ir, 3) = coeffs_a(ir, 3) * coeffs_b(ir, 0) + coeffs_a(ir, 2) * coeffs_b(ir, 1) + coeffs_a(ir, 1) * coeffs_b(ir, 2) + coeffs_a(ir, 0) * coeffs_b(ir, 3);
}
return std::move(s12);
}
#ifdef __GPU
extern "C" double <API key>(int size__,
double const* x__,
double const* dx__,
double const* f__,
double const* g__,
double* d_buf__,
double* h_buf__,
int stream_id__);
extern "C" void <API key>(int const* idx_ri__,
int num_ri__,
int num_points__,
double const* x__,
double const* dx__,
double const* f__,
double const* g__,
double* result__);
#endif
template<typename T>
T inner(Spline<T> const& f__, Spline<T> const& g__, int m__, int num_points__)
{
//assert(f__.radial_grid().hash() == g__.radial_grid().hash());
T result = 0;
switch (m__)
{
case 0:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T faga = f[0] * g[0];
T fdgd = f[3] * g[3];
T k1 = f[0] * g[1] + f[1] * g[0];
T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0];
T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1];
T k5 = f[2] * g[3] + f[3] * g[2];
result += dx * (faga +
dx * (k1 / 2.0 +
dx * (k2 / 3.0 +
dx * (k3 / 4.0 +
dx * (k4 / 5.0 +
dx * (k5 / 6.0 +
dx * fdgd / 7.0))))));
}
break;
}
case 1:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T faga = f[0] * g[0];
T fdgd = f[3] * g[3];
T k1 = f[0] * g[1] + f[1] * g[0];
T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0];
T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1];
T k5 = f[2] * g[3] + f[3] * g[2];
result += dx * ((faga * x0) +
dx * ((faga + k1 * x0) / 2.0 +
dx * ((k1 + k2 * x0) / 3.0 +
dx * ((k2 + k3 * x0) / 4.0 +
dx * ((k3 + k4 * x0) / 5.0 +
dx * ((k4 + k5 * x0) / 6.0 +
dx * ((k5 + fdgd * x0) / 7.0 +
dx * fdgd / 8.0)))))));
}
break;
}
case 2:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T k0 = f[0] * g[0];
T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3];
T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3];
T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k4 = f[3] * g[2] + f[2] * g[3];
T k5 = f[1] * g[0] + f[0] * g[1];
T k6 = f[3] * g[3]; // 25 OPS
T r1 = k4 * 0.125 + k6 * x0 * 0.25;
T r2 = (k1 + x0 * (2.0 * k4 + k6 * x0)) * 0.<API key>;
T r3 = (k2 + x0 * (2.0 * k1 + k4 * x0)) * 0.<API key>;
T r4 = (k3 + x0 * (2.0 * k2 + k1 * x0)) * 0.2;
T r5 = (k5 + x0 * (2.0 * k3 + k2 * x0)) * 0.25;
T r6 = (k0 + x0 * (2.0 * k5 + k3 * x0)) * 0.<API key>;
T r7 = (x0 * (2.0 * k0 + x0 * k5)) * 0.5;
T v = dx * k6 * 0.<API key>;
v = dx * (r1 + v);
v = dx * (r2 + v);
v = dx * (r3 + v);
v = dx * (r4 + v);
v = dx * (r5 + v);
v = dx * (r6 + v);
v = dx * (r7 + v);
result += dx * (k0 * x0 * x0 + v);
}
break;
}
/* canonical formula derived with Mathematica */
/*case 2:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coefs(i);
auto g = g__.coefs(i);
T k0 = f[0] * g[0];
T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3];
T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3];
T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k4 = f[3] * g[2] + f[2] * g[3];
T k5 = f[1] * g[0] + f[0] * g[1];
T k6 = f[3] * g[3]; // 25 OPS
result += dx * (k0 * x0 * x0 +
dx * ((x0 * (2.0 * k0 + x0 * k5)) / 2.0 +
dx * ((k0 + x0 * (2.0 * k5 + k3 * x0)) / 3.0 +
dx * ((k5 + x0 * (2.0 * k3 + k2 * x0)) / 4.0 +
dx * ((k3 + x0 * (2.0 * k2 + k1 * x0)) / 5.0 +
dx * ((k2 + x0 * (2.0 * k1 + k4 * x0)) / 6.0 +
dx * ((k1 + x0 * (2.0 * k4 + k6 * x0)) / 7.0 +
dx * ((k4 + 2.0 * k6 * x0) / 8.0 +
dx * k6 / 9.0))))))));
}
break;
}*/
default:
{
TERMINATE("wrong r^m prefactor");
}
}
return result;
}
template<typename T>
T inner(Spline<T> const& f__, Spline<T> const& g__, int m__)
{
return inner(f__, g__, m__, f__.num_points());
}
};
#endif // __SPLINE_H__
|
// Set color based on frequency and brightness
void setColor(int peak_index, int brightness) {
if (peak_index == 0) {
// signal was weak, turn lights off
red = 0;
green = 0;
blue = 0;
} else if (peak_index > 30) {
red = current_palette[29].red;
green = current_palette[29].green;
blue = current_palette[29].blue;
} else {
red = current_palette[peak_index - 1].red;
green = current_palette[peak_index - 1].green;
blue = current_palette[peak_index - 1].blue;
}
strip_color = strip.Color(
round((red / 100.0) * brightness),
round((green / 100.0) * brightness),
round((blue / 100.0) * brightness)
);
if (DEBUG) {
Serial.print((red / 100.0) * brightness);
Serial.print("\t");
Serial.print((green / 100.0) * brightness);
Serial.print("\t");
Serial.println((blue / 100.0) * brightness);
}
for (int i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip_color);
}
strip.show();
}
void changeColorPalette() {
// re-populate colors for color_palette from new palette choice
if (palette_choice != new_palette_choice - 1) {
palette_choice = new_palette_choice - 1;
for (int i = 0; i < 30; i++) {
current_palette[i].red = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].red)
);
current_palette[i].green = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].green)
);
current_palette[i].blue = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].blue)
);
}
}
}
|
#ifndef TYPES_H
#define TYPES_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
typedef unsigned char u_int8;
typedef unsigned short u_int16;
typedef unsigned long u_int32;
typedef unsigned int context;
/**
** Declaration for unix
**/
#ifdef UNIX
#ifndef _WIN32
typedef int SOCKET;
#endif
typedef struct sockaddr SOCKADDR;
typedef struct sockaddr_in SOCKADDR_IN;
#endif /* UNIX */
#endif /* TYPES_H */
|
package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene;
/**
* <API key> bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class <API key>
implements org.apache.axis2.databinding.ADBBean{
/**
* field for <API key>
*/
protected java.lang.String <API key> ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String <API key>(){
return <API key>;
}
/**
* Auto generated setter method
* @param param <API key>
*/
public void <API key>(java.lang.String param){
this.<API key>=param;
}
/**
* field for <API key>
*/
protected java.lang.String <API key> ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String <API key>(){
return <API key>;
}
/**
* Auto generated setter method
* @param param <API key>
*/
public void <API key>(java.lang.String param){
this.<API key>=param;
}
/**
* field for PatentPriority_date
*/
protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.<API key> <API key> ;
public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.<API key> <API key>(){
return <API key>;
}
/**
* Auto generated setter method
* @param param PatentPriority_date
*/
public void <API key>(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.<API key> param){
this.<API key>=param;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName);
return factory.createOMElement(dataSource,parentQName);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http:
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http:
namespacePrefix+":<API key>",
xmlWriter);
} else {
writeAttribute("xsi","http:
"<API key>",
xmlWriter);
}
}
namespace = "http:
writeStartElement(null, namespace, "<API key>", xmlWriter);
if (<API key>==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}else{
xmlWriter.writeCharacters(<API key>);
}
xmlWriter.writeEndElement();
namespace = "http:
writeStartElement(null, namespace, "<API key>", xmlWriter);
if (<API key>==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}else{
xmlWriter.writeCharacters(<API key>);
}
xmlWriter.writeEndElement();
if (<API key>==null){
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}
<API key>.serialize(new javax.xml.namespace.QName("http:
xmlWriter);
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http:
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http:
"<API key>"));
if (<API key> != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(<API key>));
} else {
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http:
"<API key>"));
if (<API key> != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(<API key>));
} else {
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http:
"<API key>"));
if (<API key>==null){
throw new org.apache.axis2.databinding.ADBException("<API key> cannot be null!!");
}
elementList.add(<API key>);
return new org.apache.axis2.databinding.utils.reader.<API key>(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static <API key> parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
<API key> object =
new <API key>();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http:
java.lang.String fullTypeName = reader.getAttributeValue("http:
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"<API key>".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (<API key>)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http:
nillableValue = reader.getAttributeValue("http:
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
throw new org.apache.axis2.databinding.ADBException("The element: "+"<API key>" +" cannot be null");
}
java.lang.String content = reader.getElementText();
object.<API key>(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http:
nillableValue = reader.getAttributeValue("http:
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
throw new org.apache.axis2.databinding.ADBException("The element: "+"<API key>" +" cannot be null");
}
java.lang.String content = reader.getElementText();
object.<API key>(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http:
object.<API key>(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.<API key>.Factory.parse(reader));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
|
#include "check/twinshadow.h"
#include "twinshadow/string.h"
char *buf_strstrip;
START_TEST(<API key>)
{
ts_strstrip(buf_strstrip);
ck_assert_str_eq(buf_strstrip, "one two three");
}
END_TEST
void
setup_strstrip_test(void) {
buf_strstrip = strdup(" one two three ");
}
void
<API key>(void) {
free(buf_strstrip);
}
TCase *
tcase_strstrip(void) {
TCase *tc = tcase_create("strstrip");
<API key>(tc, setup_strstrip_test, <API key>);
tcase_add_test(tc, <API key>);
return tc;
}
<API key>(strstrip);
|
// ooSocket.c WJ112
#include "oo/Sock.h"
#include "oo/print.h"
#include <cerrno>
#include <cstring>
#include <netdb.h>
#include <sys/types.h>
namespace oo {
int Sock::getprotobyname(const char *name) {
if (name == nullptr) {
name = "tcp";
}
struct protoent *proto = ::getprotobyname(name);
if (proto == nullptr) {
return -1;
}
return proto->p_proto;
}
int Sock::getservbyname(const char *name, const char *proto) {
if (name == nullptr) {
throw ReferenceError();
}
if (proto == nullptr) {
proto = "tcp";
}
struct servent *serv = ::getservbyname(name, proto);
if (!serv) {
// maybe it's just a numeric string
int port;
try {
port = convert<int>(name);
} catch(ValueError err) {
return -1;
}
if (port <= 0) { // invalid port number
return -1; // should we throw ValueError instead?
}
return port;
}
return ntohs(serv->s_port);
}
String Sock::getservbyport(int port, const char *proto) {
if (proto == nullptr) {
proto = "tcp";
}
struct servent *serv = ::getservbyport(htons(port), proto);
if (!serv) {
return String("");
}
return String(serv->s_proto);
}
bool Sock::listen(const char *serv) {
int sock = ::socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
throw IOError("failed to create socket");
}
// set option reuse bind address
int on = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#ifdef SO_REUSEPORT
int on2 = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#endif
struct sockaddr_in sa;
std::memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
int port = this->getservbyname(serv);
if (port == -1) {
::close(sock);
throw IOError("failed to listen, service unknown");
}
sa.sin_port = htons(port);
socklen_t sa_len = sizeof(struct sockaddr_in);
if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) {
::close(sock);
throw IOError("failed to bind socket");
}
if (::listen(sock, SOMAXCONN) == -1) {
::close(sock);
throw IOError("failed to listen on socket");
}
if (!f_.open(sock, "rw")) {
::close(sock);
throw IOError("failed to tie socket to a stream");
}
return true;
}
bool Sock::listen6(const char *serv) {
int sock = ::socket(AF_INET6, SOCK_STREAM, 0);
if (sock == -1) {
throw IOError("failed to create socket");
}
// set option reuse bind address
int on = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#ifdef SO_REUSEPORT
int on2 = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#endif
struct sockaddr_in6 sa;
std::memset(&sa, 0, sizeof(struct sockaddr_in6));
sa.sin6_family = AF_INET6;
sa.sin6_addr = in6addr_any;
int port = this->getservbyname(serv);
if (port == -1) {
::close(sock);
throw IOError("failed to listen, service unknown");
}
sa.sin6_port = htons(port);
socklen_t sa_len = sizeof(struct sockaddr_in6);
if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) {
::close(sock);
throw IOError("failed to bind socket");
}
if (::listen(sock, SOMAXCONN) == -1) {
::close(sock);
throw IOError("failed to listen on socket");
}
if (!f_.open(sock, "rw")) {
::close(sock);
throw IOError("failed to tie socket to a stream");
}
return true;
}
bool Sock::connect(const char *ipaddr, const char *serv) {
if (ipaddr == nullptr) {
throw ReferenceError();
}
if (serv == nullptr) {
throw ReferenceError();
}
if (!this->isclosed()) {
throw IOError("socket is already in use");
}
struct addrinfo hints, *res;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC; // IPv4, IPv6, or any other protocol
hints.ai_socktype = SOCK_STREAM;
if (::getaddrinfo(ipaddr, serv, &hints, &res) != 0) {
throw IOError("failed to get address info");
}
int sock = -1;
// try connecting, try out all protocols
for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) {
if ((sock = ::socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1) {
continue;
}
if (::connect(sock, r->ai_addr, r->ai_addrlen) == -1) {
::close(sock);
sock = -1;
continue;
}
break; // successful connect
}
freeaddrinfo(res);
if (sock == -1) {
throw IOError("failed to connect to remote host");
}
// tie it to a stream
if (!f_.open(sock, "w+")) {
::close(sock);
sock = -1;
throw IOError("failed to open socket as a stream");
}
return true;
}
Sock Sock::accept(void) const {
if (this->isclosed()) {
throw IOError("accept() called on a non-listening socket");
}
Sock sock;
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(struct sockaddr_storage);
int sockfd;
for(;;) {
sockfd = ::accept(f_.fileno(), (struct sockaddr *)&addr, &addr_len);
if (sockfd == -1) {
if (errno == EINTR) {
continue;
}
return Sock();
}
break;
}
if (!sock.f_.open(sockfd, "w+")) {
return Sock();
}
return sock;
}
String Sock::remoteaddr(void) const {
if (this->isclosed()) {
throw IOError("can not get remote address of an unconnected socket");
}
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(struct sockaddr_storage);
if (::getpeername(f_.fileno(), (struct sockaddr *)&addr, &addr_len) == -1) {
throw IOError("failed to get remote address of socket");
}
char host[NI_MAXHOST];
if (::getnameinfo((struct sockaddr *)&addr, addr_len, host, sizeof(host),
nullptr, 0, NI_NUMERICHOST|NI_NUMERICSERV) == -1) {
throw IOError("failed to get numeric address of remote host");
}
return String(host);
}
Sock listen(const char *serv) {
Sock sock;
if (!sock.listen(serv)) {
return Sock();
}
return sock;
}
Sock listen6(const char *serv) {
Sock sock;
if (!sock.listen6(serv)) {
return Sock();
}
return sock;
}
Sock connect(const char *ipaddr, const char *serv) {
Sock sock;
if (!sock.connect(ipaddr, serv)) {
return Sock();
}
return sock;
}
String resolv(const String& ipaddr) {
if (ipaddr.empty()) {
throw ValueError();
}
struct addrinfo *res;
if (::getaddrinfo(ipaddr.c_str(), nullptr, nullptr, &res) != 0) {
// probably invalid IP address
return ipaddr;
}
char host[NI_MAXHOST];
for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) {
if (::getnameinfo(r->ai_addr, r->ai_addrlen, host, sizeof(host), nullptr, 0, 0) == 0) {
freeaddrinfo(res);
return String(host);
}
}
// some kind of error
// print("TD error: %s", ::gai_strerror(err));
freeaddrinfo(res);
return ipaddr;
}
void fprint(Sock& sock, const char *fmt, ...) {
if (fmt == nullptr) {
throw ReferenceError();
}
if (!*fmt) {
return;
}
std::va_list ap;
va_start(ap, fmt);
vfprint(sock, fmt, ap);
va_end(ap);
}
void vfprint(Sock& sock, const char *fmt, std::va_list ap) {
if (fmt == nullptr) {
throw ReferenceError();
}
std::stringstream ss;
vssprint(ss, fmt, ap);
sock.write(ss.str());
}
} // namespace
// EOB
|
#include <algorithm>
#include <cmath>
#include <cfloat>
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/io.hpp"
#define C_ 1
using std::max;
namespace caffe {
const float kLOG_THRESHOLD = 1e-20;
template <typename Dtype>
void <API key><Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
}
template <typename Dtype>
Dtype <API key><Dtype>::Backward_cpu(
const vector<Blob<Dtype>*>& top, const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
const Dtype* bottom_data = (*bottom)[0]->cpu_data();
const Dtype* bottom_label = (*bottom)[1]->cpu_data();
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
int num = (*bottom)[0]->num();
int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count());
Dtype loss = 0;
for (int i = 0; i < num; ++i) {
int label = static_cast<int>(bottom_label[i]);
Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD));
loss -= log(prob);
bottom_diff[i * dim + label] = - 1. / prob / num;
}
return loss / num;
}
// TODO: implement the GPU version for multinomial loss
template <typename Dtype>
void InfogainLossLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
BlobProto blob_proto;
<API key>(this->layer_param_.source(), &blob_proto);
infogain_.FromProto(blob_proto);
CHECK_EQ(infogain_.num(), 1);
CHECK_EQ(infogain_.channels(), 1);
CHECK_EQ(infogain_.height(), infogain_.width());
}
template <typename Dtype>
Dtype InfogainLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
const Dtype* bottom_data = (*bottom)[0]->cpu_data();
const Dtype* bottom_label = (*bottom)[1]->cpu_data();
const Dtype* infogain_mat = infogain_.cpu_data();
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
int num = (*bottom)[0]->num();
int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
CHECK_EQ(infogain_.height(), dim);
Dtype loss = 0;
for (int i = 0; i < num; ++i) {
int label = static_cast<int>(bottom_label[i]);
for (int j = 0; j < dim; ++j) {
Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD));
loss -= infogain_mat[label * dim + j] * log(prob);
bottom_diff[i * dim + j] = - infogain_mat[label * dim + j] / prob / num;
}
}
return loss / num;
}
template <typename Dtype>
void EuclideanLossLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[0]->channels(), bottom[1]->channels());
CHECK_EQ(bottom[0]->height(), bottom[1]->height());
CHECK_EQ(bottom[0]->width(), bottom[1]->width());
difference_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
}
template <typename Dtype>
Dtype EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
int count = (*bottom)[0]->count();
int num = (*bottom)[0]->num();
caffe_sub(count, (*bottom)[0]->cpu_data(), (*bottom)[1]->cpu_data(),
difference_.mutable_cpu_data());
Dtype loss = caffe_cpu_dot(
count, difference_.cpu_data(), difference_.cpu_data()) / num / Dtype(2);
// Compute the gradient
caffe_axpby(count, Dtype(1) / num, difference_.cpu_data(), Dtype(0),
(*bottom)[0]->mutable_cpu_diff());
return loss;
}
template <typename Dtype>
void AccuracyLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Accuracy Layer takes two blobs as input.";
CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
(*top)[0]->Reshape(1, 2, 1, 1);
}
template <typename Dtype>
void AccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
Dtype accuracy = 0;
Dtype logprob = 0;
const Dtype* bottom_data = bottom[0]->cpu_data();
const Dtype* bottom_label = bottom[1]->cpu_data();
int num = bottom[0]->num();
int dim = bottom[0]->count() / bottom[0]->num();
for (int i = 0; i < num; ++i) {
// Accuracy
Dtype maxval = -FLT_MAX;
int max_id = 0;
for (int j = 0; j < dim; ++j) {
if (bottom_data[i * dim + j] > maxval) {
maxval = bottom_data[i * dim + j];
max_id = j;
}
}
//LOG(INFO) << " max_id: " << max_id << " label: " << static_cast<int>(bottom_label[i]);
if (max_id == static_cast<int>(bottom_label[i])) {
++accuracy;
}
Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])],
Dtype(kLOG_THRESHOLD));
logprob -= log(prob);
}
// LOG(INFO) << "classes: " << num;
(*top)[0]->mutable_cpu_data()[0] = accuracy / num;
(*top)[0]->mutable_cpu_data()[1] = logprob / num;
}
template <typename Dtype>
void HingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Hinge Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Hinge Loss Layer takes no output.";
}
template <typename Dtype>
void HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const Dtype* label = bottom[1]->cpu_data();
int num = bottom[0]->num();
int count = bottom[0]->count();
int dim = count / num;
caffe_copy(count, bottom_data, bottom_diff);
if(0) {
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
LOG(INFO) << bottom_data[i * dim + j];
LOG(INFO) << "*************ONE PASS*****************";
}
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
//LOG(INFO) << bottom_diff[i * dim + static_cast<int>(label[i])];
}
for (int i = 0; i < num; ++i) {
for (int j = 0; j < dim; ++j) {
//LOG(INFO) << bottom_diff[i * dim + j];
bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]);
//if(bottom_diff[i*dim+j] != 1)
//LOG(INFO) << bottom_diff[i*dim+j];
}
}
}
template <typename Dtype>
Dtype HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
const Dtype* label = (*bottom)[1]->cpu_data();
int num = (*bottom)[0]->num();
int count = (*bottom)[0]->count();
int dim = count / num;
Dtype loss = caffe_cpu_asum(count, bottom_diff) / num;
caffe_cpu_sign(count, bottom_diff, bottom_diff);
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
}
caffe_scal(count, Dtype(1. / num), bottom_diff);
//LOG(INFO) << "loss" << loss;
return loss;
}
|
#ifndef _CONVOUTPUT_SPH_H_
#define _CONVOUTPUT_SPH_H_
/**
* @file convOutput_SPH.h
* @brief convOutput_SPH Class Header
* @author aics
* @date 2013/11/7
*/
#include "convOutput.h"
class convOutput_SPH : public convOutput {
public:
convOutput_SPH();
~convOutput_SPH();
public:
/**
* @brief
* @param [in] prefix
* @param [in] step
* @param [in] id
* @param [in] mio true = local / false = gather(default)
*/
cdm_FILE* OutputFile_Open(
const std::string prefix,
const unsigned step,
const int id,
const bool mio);
/**
* @brief sphheader
* @param[in] step
* @param[in] dim
* @param[in] d_type
* @param[in] imax x
* @param[in] jmax y
* @param[in] kmax z
* @param[in] time
* @param[in] org
* @param[in] pit
* @param[in] prefix
* @param[in] pFile
*/
bool
WriteHeaderRecord(int step,
int dim,
CDM::E_CDM_DTYPE d_type,
int imax,
int jmax,
int kmax,
double time,
double* org,
double* pit,
const std::string prefix,
cdm_FILE *pFile);
/**
* @brief
* @param[in] dmy
* @param[in] pFile
* @param[in] out plot3d
*/
bool
WriteDataMarker(int dmy, cdm_FILE* pFile, bool out);
protected:
};
#endif // _CONVOUTPUT_SPH_H_
|
#ifndef CRYPTOPP_CONFIG_H
#define CRYPTOPP_CONFIG_H
#ifdef __GNUC__
#define VC_INLINE static inline __attribute__((always_inline))
#elif defined (_MSC_VER)
#define VC_INLINE __forceinline
#else
#define VC_INLINE static inline
#endif
#ifdef __GNUC__
#define <API key> (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
// Apple and LLVM's Clang. Apple Clang version 7.0 roughly equals LLVM Clang version 3.7
#if defined(__clang__ ) && !defined(<API key>)
#define <API key> (__clang_major__ * 10000 + __clang_minor__ * 100 + <API key>)
#elif defined(__clang__ ) && defined(<API key>)
#define <API key> (__clang_major__ * 10000 + __clang_minor__ * 100 + <API key>)
#endif
// TODO: supply the upper version when LLVM fixes it. We set it to 20.0 for compilation purposes.
#if (defined(<API key>) && <API key> <= 200000) || (defined(<API key>) && <API key> <= 200000)
#define <API key> 1
#endif
#ifndef <API key>
// This should be a lower bound on the L1 cache line size. It's used for defense against timing attacks.
#if defined(_M_X64) || defined(__x86_64__) || (__ILP32__ >= 1)
#define <API key> 64
#else
// L1 cache line size is 32 on Pentium III and earlier
#define <API key> 32
#endif
#endif
#if defined(_MSC_VER) && (_MSC_VER > 1200)
#define <API key>
#endif
#ifndef CRYPTOPP_ALIGN_DATA
#if defined(_MSC_VER)
#define CRYPTOPP_ALIGN_DATA(x) __declspec(align(x))
#elif defined(__GNUC__)
#define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x)))
#else
#define CRYPTOPP_ALIGN_DATA(x)
#endif
#endif
#ifndef <API key>
#if defined(__GNUC__) && !defined(__APPLE__)
// the alignment attribute doesn't seem to work without this section attribute when -fdata-sections is turned on
#define <API key> __attribute__((section ("CryptoPP_Align16")))
#else
#define <API key>
#endif
#endif
#if defined(_MSC_VER) || defined(__fastcall)
#define CRYPTOPP_FASTCALL __fastcall
#else
#define CRYPTOPP_FASTCALL
#endif
#ifdef <API key> // for backwards compatibility: this macro had both meanings
#define <API key>
#define <API key>
#endif
// Apple's Clang prior to 5.0 cannot handle SSE2 (and Apple does not use LLVM Clang numbering...)
#if defined(<API key>) && (<API key> < 50000)
# define <API key>
#endif
#if !defined(<API key>) && ((defined(_MSC_VER) && defined(_M_IX86)) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))))
// C++Builder 2010 does not allow "call label" where label is defined within inline assembly
#define <API key>
#if !defined(<API key>) && (defined(<API key>) || <API key> >= 30300 || defined(__SSE2__))
#define <API key> 1
#else
#define <API key> 0
#endif
// SSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed.
// GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version. Also see the output of
// `gcc -dM -E -march=native - < /dev/null | grep -i SSE` for preprocessor defines available.
#if !defined(<API key>) && (_MSC_VER >= 1400 || <API key> >= 40102 || defined(__SSSE3__) || defined(__SSE3__))
#define <API key> 1
#else
#define <API key> 0
#endif
#endif
#if !defined(<API key>) && defined(_MSC_VER) && defined(_M_X64)
#define <API key>
#endif
#if !defined(<API key>) && defined(__GNUC__) && defined(__x86_64__)
#define <API key>
#endif
#if !defined(<API key>) && (defined(<API key>) || defined(__SSE2__)) && !defined(_M_ARM)
#define <API key> 1
#else
#define <API key> 0
#endif
#if !defined(<API key>) && !defined(<API key>) && <API key> && (<API key> >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110 || defined(__AES__))
#define <API key> 1
#else
#define <API key> 0
#endif
#if <API key> || <API key> || defined(<API key>)
#define <API key> 1
#else
#define <API key> 0
#endif
#if <API key> && (defined(__SSE4_1__) || defined(__INTEL_COMPILER) || defined(_MSC_VER))
#define <API key> 1
#else
#define <API key> 0
#endif
// how to allocate 16-byte aligned memory (for SSE2)
#if defined(_MSC_VER)
#define <API key>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define <API key>
#elif defined(__linux__) || defined(__sun__) || defined(__CYGWIN__)
#define <API key>
#else
#define <API key>
#endif
// how to declare class constants
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__INTEL_COMPILER)
# define CRYPTOPP_CONSTANT(x) enum {x};
#else
# define CRYPTOPP_CONSTANT(x) static const int x;
#endif
// Linux provides X32, which is 32-bit integers, longs and pointers on x86_64 using the full x86_64 register set.
// the System V ABI specs calls out, like on just about any 32-bit system with Clang.
#if ((__ILP32__ >= 1) || (_ILP32 >= 1)) && defined(__x86_64__)
#define CRYPTOPP_BOOL_X32 1
#else
#define CRYPTOPP_BOOL_X32 0
#endif
#if (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X86 1
#else
#define CRYPTOPP_BOOL_X86 0
#endif
#if (defined(_M_X64) || defined(__x86_64__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X64 1
#else
#define CRYPTOPP_BOOL_X64 0
#endif
// Undo the ASM and Intrinsic related defines due to X32.
#if CRYPTOPP_BOOL_X32
# undef CRYPTOPP_BOOL_X64
# undef <API key>
# undef <API key>
#endif
#if !defined(<API key>) && !defined(<API key>)
#if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || defined(__powerpc__) || (<API key> >= 1))
#define <API key>
#endif
#endif
// this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
#define GETBYTE(x, y) (unsigned int)((unsigned char)((x)>>(8*(y))))
// these may be faster on other CPUs/compilers
// #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
// #define GETBYTE(x, y) (((byte *)&(x))[y])
#define <API key>(x, y) ((byte)((x)>>(8*(y))))
#endif
|
#.Synopsis
# Creates and deletes sinkhole domains in Windows DNS servers.
#.Description
# Script takes fully-qualified domain names (FQDNs) and/or simple domain
# names, then uses them to create primary zones (not Active Directory
# integrated) in a Windows DNS server, setting all zones to resolve to a
# single chosen IP address. The IP address might be "0.0.0.0" or the IP
# of an internal server configured for logging. The intention is to
# prevent clients from resolving the correct IP address of unwanted FQDNs
# and domain names, such as for malware and phishing sites. Such names
# are said to be "sinkholed" or "blackholed" since they often resolve
# to 0.0.0.0, which is an inaccessible IP address.
#.Parameter InputFile
# Path to a file which contains the FQDNs and domain names to sinkhole.
# File can have blank lines, comment lines (# or ;), multiple FQDNs or
# domains per line (space- or comma-delimited), and can be a hosts file
# with IP addresses too (addresses and localhost entires will be ignored).
# You can also include wildcards to input multiple files, e.g.,
# "*bad*.txt", or pass in an array of file objects instead of a string.
#.Parameter Domain
# One or more FQDNs or domains to sinkhole, separated by spaces or commas.
#.Parameter SinkHoleIP
# The IP address to which all sinkholed names will resolve. The
# default is "0.0.0.0", but perhaps is better set to an internal server.
# Remember, there is only one IP for ALL the sinkholed domains.
#.Parameter DnsServerName
# FQDN of the Windows DNS server. Defaults to localhost. If specified,
# please always use a fully-qualified domain name (FQDN), especially if
# the DNS server is a stand-alone or in a different domain.
#.Parameter IncludeWildCard
# Will add a wildcard host record (*) to every sinkhole domain, which
# will match all possible hostnames within that domain. Keep in mind
# name, so a wildcard is not needed to match it; but sinkholing just
# the wildcard. If you only want to sinkhole the exact FQDN or domain
# name supplied to the script, then don't include a wildcard record.
# If you are certain that you do not want to resolve anything whatsoever
# under the sinkholed domains, then include the wildcard DNS record.
#.Parameter <API key>
# Will cause every sinkholed domain in your DNS server to re-read the
# one shared zone file they all use. This is the zone file for the
# <API key>.local domain. Keep in mind that the DNS
# graphical management tool shows you what is cached in memory, not
# what is in the zone file. Reload the sinkhole domains if you,
# for example, change the sinkhole IP address. Using this switch
# causes any other parameters to be ignored.
#.Parameter <API key>
# Will delete all sinkhole domains, but will not delete any regular
# non-sinkhole domains. Strictly speaking, this deletes any domain
# which uses a zone file named "<API key>.local.dns".
# The zone file itself is not deleted, but it only 1KB in size.
# Using this switch causes any other parameters to be ignored.
#.Parameter RemoveLeadingWWW
# Some lists of sinkhole names are simple domain names, while other
# name to be sinkholed, then consider using -IncludeWildCard too.
# but only for a single digit after the "www" part (1-9 only).
#.Parameter Credential
# An "authority\username" string to explicitly authenticate to the
# DNS server instead of using single sign-on with the current
# identity. The authority is either a server name or a domain name.
# You will be prompted for the passphrase. You can also pass in
# a variable with a credential object from Get-Credential.
#.Example
# which will resolve to "0.0.0.0". DNS server is local.
#.Example
# which will resolve to "10.1.1.1". DNS server is local.
#.Example
# .\Sinkhole-DNS.ps1 -InputFile file.txt -IncludeWildCard
# This will create DNS domains out of all the FQDNs and domain
# names listed in file.txt, plus add a wildcard (*) record.
#.Example
# .\Sinkhole-DNS.ps1 -<API key>
# Perhaps after changing the sinkhole IP address, this will cause
# all sinkholed domains to re-read their shared zone file.
#.Example
# .\Sinkhole-DNS.ps1 -<API key>
# This will delete all sinkholed domains, but will not delete
# any other domains. This does not delete the sinkhole zone file.
#.Example
# .\Sinkhole-DNS.ps1 -InputFile file.txt -DnsServerName `
# "server7.sans.org" -Credential "server7\administrator"
# This will create sinkholed domains from file.txt on a remote
# DNS server named "server7.sans.org" with explicit credentials.
# You will be prompted for the passphrase.
#.Example
# $Cred = Get-Credential -Credential "server7\administrator"
# .\Sinkhole-DNS.ps1 -InputFile *evil*.txt `
# -DnsServerName "server7.sans.org" -Credential $Cred
# This will create sinkholed domains from *evil*.txt on a remote
# DNS server named "server7.sans.org" with explicit credentials
# supplied in a credential object ($Cred) which can be reused again.
# Multiple input files may match "*evil*.txt".
Param ($InputFile, [String] $Domain, [String] $SinkHoleIP = "0.0.0.0", [String] $DnsServerName = ".", [Switch] $IncludeWildCard,
[Switch] $<API key>, [Switch] $<API key>, [Switch] $RemoveLeadingWWW, $Credential)
# Check for common help switches.
if (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String") -and ($InputFile -match "/\?|-help|--h|--help"))
{
If ($Host.Version.Major -ge 2) { get-help -full .\sinkhole-dns.ps1 }
Else {"`nPlease read this script's header in Notepad for the help information."}
Exit
}
# Confirm PowerShell 2.0 or later.
If ($Host.Version.Major -lt 2) { "This script requires PowerShell 2.0 or later.`nDownload the latest version from http:
# If necessary, prompt user for domain\username and a passphrase.
If ($Credential) { $Cred = Get-Credential -Credential $Credential }
Function Main
{
# Test access to WMI at target server ($ZoneClass is used later too).
$ZoneClass = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_Zone'"
If (-not $? -or $ZoneClass.Name -ne "MicrosoftDNS_Zone") { Throw("Failed to connect to WMI service or the WMI DNS_Zone namespace!") ; Exit }
## Parse input domains, but exclude the following: localhost, any IP addresses, blank lines.
#Process any -Domain args.
[Object[]] $Domains = @($Domain -Split "[\s\;\,]")
#Process any -InputFile arguments and expand any wildcards.
If (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String")) { $InputFile = dir $InputFile }
If ($InputFile -ne $Null) { $InputFile | ForEach { $Domains += Get-Content $_ | Where { $_ -notmatch "^[\#\;\<]" } | ForEach { $_ -Split "[\s\;\,]" } } }
If ($RemoveLeadingWWW) { 0..$([Int] $Domains.Count - 1) | ForEach { $Domains[$_] = $Domains[$_] -Replace "^www[1-9]{0,1}\.","" } }
#Convert to lowercase, remove redundants, exclude blank lines, exclude IPs, exclude anything with a colon in it, e.g., IPv6.
$Domains = $Domains | ForEach { $_.Trim().ToLower() } | Sort -Unique | Where { $_.Length -ne 0 -and $_ -notmatch "^localhost$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\:" }
If ($Domains.Count -le 0) { "No domains specified!" ; exit } Else { "`n" + [String] $Domains.Count + " domain(s) to sinkhole to $SinkHoleIP." }
## Get or create the master sinkhole zone: <API key>.local.
$WmiPath = "Root\MicrosoftDNS:MicrosoftDNS_Zone.ContainerName='<API key>.local',DnsServerName='" + $DnsServerName + "',Name='<API key>.local'"
If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName <API key>) #Zone exists.
{
"`nThe <API key>.local zone already exists, deleting its existing DNS records."
$ExistingRecords = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_AType WHERE ContainerName = '<API key>.local'")
If (-not $?) { Throw("Failed to query the A records of the <API key>.local domain!") ; exit }
If ($ExistingRecords.Count -gt 0) { $ExistingRecords | ForEach { $_.Delete() } }
}
Else #Zone does not exist.
{
"`nCreating the <API key>.local zone and its zone file."
$RR = $ZoneClass.CreateZone("<API key>.local",0,$false,$null,$null,"only-edit.<API key>.local.")
If (-not $? -or $RR.__CLASS -ne "__PARAMETERS")
{
If ($Credential -And ($DnsServerName.Length -ne 0) -And ($DnsServerName -NotLike "*.*")) { "Did you forget to use a FQDN for the DNS server name?" }
Throw("Failed to create the <API key>.local domain!")
Exit
}
}
## Create DNS records in master sinkhole zone.
# Create the default A record with the sinkhole IP address.
$RecordClass = $Null # Defaults to "IN" class of record.
$TTL = 120 # Seconds. Defaults to zone default if you set this to $null.
$ATypeRecords = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_AType'"
If (-not $? -or $ATypeRecords.Name -ne "MicrosoftDNS_AType") { "`nFailed to query A type records, but continuing..." }
$ARecord = $ATypeRecords.<API key>($DnsServerName,"<API key>.local","<API key>.local",$RecordClass,$TTL,$SinkHoleIP)
If ($?) { "Created default DNS record for the <API key>.local zone ($SinkHoleIP)." }
Else { "Failed to create default A record for the <API key>.local zone, but continuing..." }
# Create the wildcard A record if the -IncludeWildCard switch was used.
If ($IncludeWildCard)
{
$ARecord = $ATypeRecords.<API key>($DnsServerName,"<API key>.local","*.<API key>.local",$RecordClass,$TTL,$SinkHoleIP)
If ($?) { "Created the wildcard (*) record for the <API key>.local zone ($SinkHoleIP)." }
Else { "Failed to create the wildcard (*) record for the <API key>.local zone, but continuing..." }
}
# Update zone data file on disk after adding the A record(s).
If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone)
{ "Updated the zone file for <API key>.local." }
Else
{
Start-Sleep -Seconds 2 #Just seems to help...
$ItWorked = InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone
If ($ItWorked) { "Updated the zone file for <API key>.local." }
Else {"`nFailed to update the server data file for the <API key>.local zone, but continuing..." }
}
## Create the sinkholed domains using the <API key>.local.dns zone file.
$Created = $NotCreated = 0
$<API key> = $<API key>
$<API key> = "SilentlyContinue"
$Domains | ForEach `
{
$ZoneClass.CreateZone($_,0,$false,"<API key>.local.dns",$null,"only-edit.<API key>.local.") | Out-Null
If ($?) { $Created++ } Else { $NotCreated++ }
}
$<API key> = $<API key>
"`nSinkhole domains created at the DNS server: $Created"
"`nDomains NOT created (maybe already existed): $NotCreated`n"
} #End of Main
Function GetWMI ([String] $Query)
{
# This is a helper function for the sake of -Credential.
If ($Credential) { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName -Credential $Cred }
Else { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName }
}
Function InvokeWmiMethod ([String] $ObjectPath, [String] $MethodName)
{
# This is a helper function for the sake of -Credential.
$<API key> = "SilentlyContinue"
If ($Credential) { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName -Credential $Cred }
Else { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName }
$? #Returns
}
Function <API key>
{
# Function causes sinkholed domains to be reloaded from the shared master zone file, perhaps after a -SinkHoleIP change.
# You may get errors if zone is temporarily locked for updates, but the DNS server's default lock is only two minutes.
"`nReloading sinkholed domains from the <API key>.local.dns zone file, `nwhich may take a few minutes if you have 10K+ domains..."
$BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '<API key>.local.dns'")
If (-not $?) { Throw("Failed to connect to WMI service!") ; exit }
"`nSinkholed domains to be reloaded from the zone file: " + [String] $BHDomains.Count
$Locked = @() #Index numbers of zones which are temporarily locked and cannot be reloaded yet.
$i = 0
$<API key> = "SilentlyContinue"
If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.ReloadZone() ; If (-not $?) { $Locked += $i } ; $i++ } }
If ($Locked.Count -gt 0)
{
"`n" + [String] $Locked.Count + " zone(s) are still temporarily locked, will try those again in two minutes.`nPlease wait two minutes or hit Ctrl-C to cancel..."
Start-Sleep -Seconds 60
"Just one more minute... Thank you for holding, your function call is appreciated."
Start-Sleep -Seconds 30
"Just 30 more seconds... Your patience is admirable, and you're good looking too!"
Start-Sleep -Seconds 35
$Locked | ForEach { $BHDomains[$_].ReloadZone() ; if (-not $?) { "`n" + [String] $BHDomains[$_].ContainerName + " is still locked and has not reloaded yet." } }
}
"`nThe other sinkholed domains were successfully reloaded.`n"
} #End
Function <API key>
{
# Delete all sinkholed zones, including <API key>.local, but
# note that this does not delete the (tiny) zone file on the drive.
"`nDeleting all sinkholed domains, which may take a few minutes if you have 10K+ domains..."
$BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '<API key>.local.dns'")
If (-not $?) { Throw("Failed to connect to WMI service!") ; exit }
"`nSinkhole domains to be deleted: " + [String] $BHDomains.Count
$i = 0
If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.Delete() ; If ($?){$i++} } }
"Sinkhole domains deleted count: $i`n"
} #End
# MAIN #
If ($<API key>) { <API key> ; Exit }
If ($<API key>) { <API key> ; Exit }
Main
|
var searchData=
[
['lettersonly',['lettersOnly',['../<API key>.html#<API key>',1,'<API key>']]],
['list_5fdelimiter',['LIST_DELIMITER',['../<API key>.html#<API key>',1,'<API key>']]],
['load',['load',['../<API key>.html#<API key>',1,'<API key>']]],
['loadclass',['loadClass',['../<API key>.html#<API key>',1,'<API key>']]],
['loadmore',['loadMore',['../<API key>.html#<API key>',1,'<API key>']]],
['<API key>',['<API key>',['../<API key>.html#<API key>',1,'AblePolecat_Dom']]],
['loadtoken',['loadToken',['../<API key><API key>.html#<API key>',1,'<API key><API key>\loadToken()'],['../<API key><API key>.html#<API key>',1,'<API key><API key>\loadToken()']]],
['log_2ephp',['Log.php',['../_command_2_log_8php.html',1,'']]],
['<API key>',['LOG_NAME_BOOTSEQ',['../<API key>.html#<API key>',1,'<API key>']]],
['logbootmessage',['logBootMessage',['../<API key>.html#<API key>',1,'<API key>']]],
['logerrorinfo',['logErrorInfo',['../<API key>.html#<API key>',1,'<API key>']]],
['logerrormessage',['logErrorMessage',['../<API key>.html#<API key>',1,'<API key>']]],
['logstatusmessage',['logStatusMessage',['../<API key>.html#<API key>',1,'<API key>']]],
['logwarningmessage',['logWarningMessage',['../<API key>.html#<API key>',1,'<API key>']]],
['lookupconstraint',['lookupConstraint',['../<API key>.html#<API key>',1,'<API key>']]],
['lvalue',['lvalue',['../<API key>.html#<API key>',1,'<API key>\lvalue()'],['../<API key>.html#<API key>',1,'<API key>\lvalue()']]]
];
|
#ifndef <API key>
#define <API key>
#include <vector>
#include "base/basictypes.h"
#include "ui/gfx/gfx_export.h"
namespace gfx {
class Image;
}
namespace gfx {
// Creates an image from the given JPEG-encoded input. If there was an error
// creating the image, returns an IsEmpty() Image.
UI_EXPORT Image <API key>(const unsigned char* input,
size_t input_size);
// Fills the |dst| vector with JPEG-encoded bytes of the 1x representation of
// the given image.
// Returns true if the image has a 1x representation and the 1x representation
// was encoded successfully.
// |quality| determines the compression level, 0 == lowest, 100 == highest.
// Returns true if the Image was encoded successfully.
UI_EXPORT bool <API key>(const Image& image,
int quality,
std::vector<unsigned char>* dst);
} // namespace gfx
#endif // <API key>
|
#include "chrome/browser/profiles/profile.h"
#include <string>
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/<API key>.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/<API key>.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/<API key>.h"
#include "chrome/browser/extensions/<API key>.h"
#include "chrome/browser/extensions/<API key>.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/<API key>.h"
#include "chrome/browser/net/<API key>.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/<API key>.h"
#include "chrome/browser/profiles/<API key>.h"
#include "chrome/browser/ssl/ssl_host_state.h"
#include "chrome/browser/sync/<API key>.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/<API key>.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/find_bar/find_bar_state.h"
#include "chrome/browser/ui/webui/<API key>.h"
#include "chrome/browser/ui/webui/<API key>.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "content/browser/appcache/<API key>.h"
#include "content/browser/browser_thread.h"
#include "content/browser/<API key>.h"
#include "content/browser/file_system/<API key>.h"
#include "content/browser/host_zoom_map.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/common/<API key>.h"
#include "grit/locale_settings.h"
#include "net/base/<API key>.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/database/database_tracker.h"
#include "webkit/quota/quota_manager.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/password_manager/password_store_win.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/keychain_mac.h"
#include "chrome/browser/password_manager/password_store_mac.h"
#elif defined(OS_POSIX) && !defined(OS_CHROMEOS)
#include "chrome/browser/password_manager/<API key>.h"
#include "chrome/browser/password_manager/<API key>.h"
#include "chrome/browser/password_manager/password_store_x.h"
#elif defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/preferences.h"
#endif
using base::Time;
using base::TimeDelta;
// A pointer to the request context for the default profile. See comments on
// Profile::<API key>.
net::<API key>* Profile::<API key>;
namespace {
} // namespace
Profile::Profile()
: <API key>(false),
<API key>(0) {
}
// static
const char* Profile::kProfileKey = "__PROFILE__";
// static
const ProfileId Profile::kInvalidProfileId = static_cast<ProfileId>(0);
// static
void Profile::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::<API key>, true);
prefs->RegisterBooleanPref(prefs::<API key>, true);
prefs->RegisterBooleanPref(prefs::<API key>, true);
prefs->RegisterBooleanPref(prefs::<API key>, false);
// TODO(estade): <API key> should be an ASCII string.
prefs-><API key>(prefs::<API key>,
<API key>);
prefs->RegisterBooleanPref(prefs::kEnableSpellCheck, true);
prefs->RegisterBooleanPref(prefs::<API key>, true);
#if defined(TOOLKIT_USES_GTK)
prefs->RegisterBooleanPref(prefs::kUsesSystemTheme,
GtkThemeService::<API key>());
#endif
prefs-><API key>(prefs::<API key>, FilePath());
prefs->RegisterStringPref(prefs::kCurrentThemeID,
ThemeService::kDefaultThemeID);
prefs-><API key>(prefs::kCurrentThemeImages);
prefs-><API key>(prefs::kCurrentThemeColors);
prefs-><API key>(prefs::kCurrentThemeTints);
prefs-><API key>(prefs::<API key>);
prefs->RegisterBooleanPref(prefs::kDisableExtensions, false);
prefs->RegisterStringPref(prefs::<API key>, "");
#if defined(OS_CHROMEOS)
// TODO(dilmah): For OS_CHROMEOS we maintain kApplicationLocale in both
// local state and user's profile. For other platforms we maintain
// kApplicationLocale only in local state.
// In the future we may want to maintain kApplicationLocale
// in user's profile for other platforms as well.
prefs->RegisterStringPref(prefs::kApplicationLocale, "");
prefs->RegisterStringPref(prefs::<API key>, "");
prefs->RegisterStringPref(prefs::<API key>, "");
#endif
}
// static
net::<API key>* Profile::<API key>() {
return <API key>;
}
bool Profile::IsGuestSession() {
#if defined(OS_CHROMEOS)
static bool is_guest_session =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession);
return is_guest_session;
#else
return false;
#endif
}
bool Profile::IsSyncAccessible() {
ProfileSyncService* syncService = <API key>();
return syncService && !syncService->IsManaged();
}
// <API key> is a profile subclass that wraps an existing profile
// to make it suitable for the incognito mode.
class <API key> : public Profile,
public BrowserList::Observer {
public:
explicit <API key>(Profile* real_profile)
: profile_(real_profile),
prefs_(real_profile-><API key>()),
<API key>(io_data_(this)),
start_time_(Time::Now()) {
<API key>.reset(<API key>::Create(this));
BrowserList::AddObserver(this);
<API key>::GetForProfile(this);
DCHECK(real_profile->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled));
// TODO(oshima): Remove the need to eagerly initialize the request context
// Profile member from a thread other than the UI thread, so we need to
// prevent a race.
#if defined(OS_CHROMEOS)
GetRequestContext();
#endif // defined(OS_CHROMEOS)
// Make the chrome//extension-icon/ resource available.
ExtensionIconSource* icon_source = new ExtensionIconSource(real_profile);
<API key>()->AddDataSource(icon_source);
}
virtual ~<API key>() {
NotificationService::current()->Notify(NotificationType::PROFILE_DESTROYED,
Source<Profile>(this),
NotificationService::NoDetails());
<API key>::GetInstance()-><API key>(this);
// Clean up all DB files/directories
if (db_tracker_)
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(
db_tracker_.get(),
&webkit_database::DatabaseTracker::<API key>));
BrowserList::RemoveObserver(this);
if (<API key>)
<API key>-><API key>();
}
virtual ProfileId GetRuntimeId() {
return reinterpret_cast<ProfileId>(this);
}
virtual std::string GetProfileName() {
// Incognito profile should not return the profile name.
return std::string();
}
virtual FilePath GetPath() { return profile_->GetPath(); }
virtual bool IsOffTheRecord() {
return true;
}
virtual Profile* <API key>() {
return this;
}
virtual void <API key>() {
// Suicide is bad!
NOTREACHED();
}
virtual bool <API key>() {
return true;
}
virtual Profile* GetOriginalProfile() {
return profile_;
}
virtual <API key>* GetAppCacheService() {
if (!appcache_service_) {
appcache_service_ = new <API key>;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
appcache_service_.get(),
&<API key>::<API key>,
IsOffTheRecord()
? FilePath() : GetPath().Append(chrome::kAppCacheDirname),
make_scoped_refptr(<API key>()),
make_scoped_refptr(<API key>()),
false));
}
return appcache_service_;
}
virtual webkit_database::DatabaseTracker* GetDatabaseTracker() {
if (!db_tracker_.get()) {
db_tracker_ = new webkit_database::DatabaseTracker(
GetPath(), IsOffTheRecord(), <API key>());
}
return db_tracker_;
}
virtual VisitedLinkMaster* <API key>() {
// We don't provide access to the VisitedLinkMaster when we're OffTheRecord
// because we don't want to leak the sites that the user has visited before.
return NULL;
}
virtual ExtensionService* GetExtensionService() {
return GetOriginalProfile()->GetExtensionService();
}
virtual StatusTray* GetStatusTray() {
return GetOriginalProfile()->GetStatusTray();
}
virtual UserScriptMaster* GetUserScriptMaster() {
return GetOriginalProfile()->GetUserScriptMaster();
}
virtual <API key>* <API key>() {
// TODO(mpcomplete): figure out whether we should return the original
// profile's version.
return NULL;
}
virtual <API key>* <API key>() {
return <API key>.get();
}
virtual <API key>* <API key>() {
return GetOriginalProfile()-><API key>();
}
virtual <API key>* <API key>() {
return GetOriginalProfile()-><API key>();
}
virtual <API key>* <API key>() {
return GetOriginalProfile()-><API key>();
}
virtual SSLHostState* GetSSLHostState() {
if (!ssl_host_state_.get())
ssl_host_state_.reset(new SSLHostState());
DCHECK(ssl_host_state_->CalledOnValidThread());
return ssl_host_state_.get();
}
virtual net::<API key>* <API key>() {
if (!<API key>.get()) {
<API key> = new net::<API key>(
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kHstsHosts));
<API key> =
new <API key>(true /* readonly */);
<API key>->Initialize(<API key>.get(),
GetOriginalProfile()->GetPath());
}
return <API key>.get();
}
virtual HistoryService* GetHistoryService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetHistoryService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual HistoryService* <API key>() {
return profile_-><API key>();
}
virtual FaviconService* GetFaviconService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetFaviconService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual <API key>* <API key>() {
return profile_-><API key>();
}
virtual WebDataService* GetWebDataService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetWebDataService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual WebDataService* <API key>() {
return profile_-><API key>();
}
virtual PasswordStore* GetPasswordStore(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetPasswordStore(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual PrefService* GetPrefs() {
return prefs_;
}
virtual PrefService* <API key>() {
return prefs_;
}
virtual TemplateURLModel* GetTemplateURLModel() {
return profile_->GetTemplateURLModel();
}
virtual TemplateURLFetcher* <API key>() {
return profile_-><API key>();
}
virtual DownloadManager* GetDownloadManager() {
if (!download_manager_.get()) {
scoped_refptr<DownloadManager> dlm(
new DownloadManager(g_browser_process-><API key>()));
dlm->Init(this);
download_manager_.swap(dlm);
}
return download_manager_.get();
}
virtual bool <API key>() const {
return (download_manager_.get() != NULL);
}
virtual PersonalDataManager* <API key>() {
return NULL;
}
virtual fileapi::FileSystemContext* <API key>() {
if (!<API key>)
<API key> = <API key>(
GetPath(), IsOffTheRecord(), <API key>());
DCHECK(<API key>.get());
return <API key>.get();
}
virtual net::<API key>* GetRequestContext() {
return io_data_.<API key>();
}
virtual quota::QuotaManager* GetQuotaManager() {
if (!quota_manager_.get()) {
quota_manager_ = new quota::QuotaManager(
IsOffTheRecord(),
GetPath(),
BrowserThread::<API key>(BrowserThread::IO),
BrowserThread::<API key>(BrowserThread::DB));
}
return quota_manager_.get();
}
virtual net::<API key>* <API key>(
int renderer_child_id) {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::<API key>)) {
const Extension* installed_app = GetExtensionService()->
<API key>(renderer_child_id);
if (installed_app != NULL && installed_app->is_storage_isolated())
return <API key>(installed_app->id());
}
return GetRequestContext();
}
virtual net::<API key>* <API key>() {
// In OTR mode, media request context is the same as the original one.
return io_data_.<API key>();
}
virtual net::<API key>* <API key>() {
return io_data_.<API key>();
}
virtual net::<API key>* <API key>(
const std::string& app_id) {
return io_data_.<API key>(app_id);
}
virtual const content::ResourceContext& GetResourceContext() {
return io_data_.GetResourceContext();
}
virtual net::SSLConfigService* GetSSLConfigService() {
return profile_->GetSSLConfigService();
}
virtual <API key>* <API key>() {
// Retrieve the host content settings map of the parent profile in order to
// ensure the preferences have been migrated.
profile_-><API key>();
if (!<API key>.get())
<API key> = new <API key>(this);
return <API key>.get();
}
virtual HostZoomMap* GetHostZoomMap() {
if (!host_zoom_map_)
host_zoom_map_ = new HostZoomMap(this);
return host_zoom_map_.get();
}
virtual <API key>* <API key>() {
return profile_-><API key>();
}
virtual <API key>* <API key>() {
return profile_-><API key>();
}
virtual <API key>* <API key>() {
return profile_-><API key>();
}
virtual FindBarState* GetFindBarState() {
if (!find_bar_state_.get())
find_bar_state_.reset(new FindBarState());
return find_bar_state_.get();
}
virtual bool <API key>() const {
// We never have a profile sync service.
return false;
}
virtual bool <API key>() {
return profile_-><API key>();
}
virtual BookmarkModel* GetBookmarkModel() {
return profile_->GetBookmarkModel();
}
virtual <API key>* <API key>() {
return profile_-><API key>();
}
virtual TokenService* GetTokenService() {
return NULL;
}
virtual ProfileSyncService* <API key>() {
return NULL;
}
virtual ProfileSyncService* <API key>(
const std::string& cros_user) {
return NULL;
}
virtual BrowserSignin* GetBrowserSignin() {
return profile_->GetBrowserSignin();
}
virtual <API key>* <API key>() {
return NULL;
}
virtual bool IsSameProfile(Profile* profile) {
return (profile == this) || (profile == profile_);
}
virtual Time GetStartTime() const {
return start_time_;
}
virtual SpellCheckHost* GetSpellCheckHost() {
return profile_->GetSpellCheckHost();
}
virtual void <API key>(bool force) {
profile_-><API key>(force);
}
virtual WebKitContext* GetWebKitContext() {
if (!webkit_context_.get()) {
webkit_context_ = new WebKitContext(
IsOffTheRecord(), GetPath(), <API key>(),
false);
}
return webkit_context_.get();
}
virtual history::TopSites* <API key>() {
return NULL;
}
virtual history::TopSites* GetTopSites() {
return NULL;
}
virtual void MarkAsCleanShutdown() {
}
virtual void InitExtensions(bool extensions_enabled) {
NOTREACHED();
}
virtual void InitPromoResources() {
NOTREACHED();
}
virtual void <API key>() {
NOTREACHED();
}
virtual NTPResourceCache* GetNTPResourceCache() {
// Just return the real profile resource cache.
return profile_->GetNTPResourceCache();
}
virtual FilePath <API key>() {
const FilePath& directory = <API key>;
if (directory.empty()) {
return profile_-><API key>();
}
return directory;
}
virtual void <API key>(const FilePath& path) {
<API key> = path;
}
#if defined(OS_CHROMEOS)
virtual void <API key>() {
profile_-><API key>();
}
virtual void <API key>() {
// The incognito profile shouldn't have Chrome OS's preferences.
// The preferences are associated with the regular user profile.
}
#endif // defined(OS_CHROMEOS)
virtual void <API key>() {
// DownloadManager is lazily created, so check before accessing it.
if (download_manager_.get()) {
// Drop our download manager so we forget about all the downloads made
// in incognito mode.
download_manager_->Shutdown();
download_manager_ = NULL;
}
}
virtual void OnBrowserAdded(const Browser* browser) {
}
virtual void OnBrowserRemoved(const Browser* browser) {
if (BrowserList::GetBrowserCount(this) == 0)
<API key>();
}
virtual <API key>* <API key>() {
if (!<API key>) {
<API key> = new <API key>();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
<API key>.get(),
&<API key>::<API key>));
}
return <API key>;
}
virtual ExtensionInfoMap* GetExtensionInfoMap() {
return profile_->GetExtensionInfoMap();
}
virtual <API key>* <API key>() {
if (!<API key>.get())
<API key>.reset(new <API key>(this));
return <API key>.get();
}
virtual PromoCounter* <API key>() {
return NULL;
}
#if defined(OS_CHROMEOS)
virtual void ChangeAppLocale(const std::string& locale, AppLocaleChangedVia) {
}
virtual void OnLogin() {
}
#endif // defined(OS_CHROMEOS)
virtual <API key>* <API key>() {
if (!<API key>)
<API key> = new <API key>(GetPrefs());
return <API key>;
}
virtual prerender::PrerenderManager* GetPrerenderManager() {
// We do not allow prerendering in OTR profiles at this point.
// TODO(tburkard): Figure out if we want to support this, and how, at some
// point in the future.
return NULL;
}
private:
<API key> registrar_;
// The real underlying profile.
Profile* profile_;
// Weak pointer owned by |profile_|.
PrefService* prefs_;
scoped_ptr<<API key>> <API key>;
<API key>::Handle io_data_;
// The download manager that only stores downloaded items in memory.
scoped_refptr<DownloadManager> download_manager_;
// We use a non-writable content settings map for OTR.
scoped_refptr<<API key>> <API key>;
// Use a separate zoom map for OTR.
scoped_refptr<HostZoomMap> host_zoom_map_;
// Use a special WebKit context for OTR browsing.
scoped_refptr<WebKitContext> webkit_context_;
// We don't want SSLHostState from the OTR profile to leak back to the main
// profile because then the main profile would learn some of the host names
// the user visited while OTR.
scoped_ptr<SSLHostState> ssl_host_state_;
// Use a separate FindBarState so search terms do not leak back to the main
// profile.
scoped_ptr<FindBarState> find_bar_state_;
// The <API key> that only stores enabled sites in memory.
scoped_refptr<net::<API key>>
<API key>;
// Time we were started.
Time start_time_;
scoped_refptr<<API key>> appcache_service_;
// The main database tracker for this profile.
// Should be used only on the file thread.
scoped_refptr<webkit_database::DatabaseTracker> db_tracker_;
FilePath <API key>;
scoped_refptr<<API key>> <API key>;
// The file_system context for this profile.
scoped_refptr<fileapi::FileSystemContext> <API key>;
scoped_refptr<<API key>> <API key>;
scoped_ptr<<API key>> <API key>;
scoped_refptr<quota::QuotaManager> quota_manager_;
// Used read-only.
scoped_refptr<<API key>> <API key>;
<API key>(<API key>);
};
#if defined(OS_CHROMEOS)
// Special case of the <API key> which is used while Guest
// session in CrOS.
class GuestSessionProfile : public <API key> {
public:
explicit GuestSessionProfile(Profile* real_profile)
: <API key>(real_profile) {
}
virtual PersonalDataManager* <API key>() {
return GetOriginalProfile()-><API key>();
}
virtual void <API key>() {
<API key>.reset(new chromeos::Preferences());
<API key>->Init(GetPrefs());
}
private:
// The guest user should be able to customize Chrome OS preferences.
scoped_ptr<chromeos::Preferences> <API key>;
};
#endif
Profile* Profile::<API key>() {
#if defined(OS_CHROMEOS)
if (Profile::IsGuestSession())
return new GuestSessionProfile(this);
#endif
return new <API key>(this);
}
|
/*
* wrapper pow(x,y) return x**y
*/
#include "fdlibm.h"
#ifdef __STDC__
double pow(double x, double y) /* wrapper pow */
#else
double pow(x,y) /* wrapper pow */
double x,y;
#endif
{
#ifdef _IEEE_LIBM
return __ieee754_pow(x,y);
#else
double z;
z=__ieee754_pow(x,y);
if(_LIB_VERSION == _IEEE_|| isnan(y)) return z;
if(isnan(x)) {
if(y==0.0)
return __kernel_standard(x,y,42); /* pow(NaN,0.0) */
else
return z;
}
if(x==0.0){
if(y==0.0)
return __kernel_standard(x,y,20); /* pow(0.0,0.0) */
if(finite(y)&&y<0.0)
return __kernel_standard(x,y,23); /* pow(0.0,negative) */
return z;
}
if(!finite(z)) {
if(finite(x)&&finite(y)) {
if(isnan(z))
return __kernel_standard(x,y,24); /* pow neg**non-int */
else
return __kernel_standard(x,y,21); /* pow overflow */
}
}
if(z==0.0&&finite(x)&&finite(y))
return __kernel_standard(x,y,22); /* pow underflow */
return z;
#endif
}
|
{% from 'macros/misc.html' import render_tag %}
{% macro render_flag_hidden(hidden_by) -%}
{{ render_tag(_('hidden'), class='user-comment-hidden', icon='hidden', title='%s (%s %s)'|format(_('hidden'), _('by'), hidden_by.screen_name)) }}
{%- endmacro %}
{% macro render_flag_new() -%}
{{ render_tag(_('new')) }}
{%- endmacro %}
|
#ifndef <API key>
#define <API key>
#include <string>
#include "base/basictypes.h"
#include "net/base/io_buffer.h"
#include "net/base/load_log.h"
#include "net/base/upload_data_stream.h"
#include "net/http/<API key>.h"
#include "net/http/http_response_info.h"
#include "net/socket/<API key>.h"
namespace net {
class ClientSocketHandle;
class HttpRequestInfo;
class HttpStreamParser {
public:
// Any data in |read_buffer| will be used before reading from the socket
// and any data left over after parsing the stream will be put into
// |read_buffer|. The left over data will start at offset 0 and the
// buffer's offset will be set to the first free byte. |read_buffer| may
// have its capacity changed.
HttpStreamParser(ClientSocketHandle* connection,
GrowableIOBuffer* read_buffer,
LoadLog* load_log);
~HttpStreamParser() {}
// These functions implement the interface described in HttpStream with
// some additional functionality
int SendRequest(const HttpRequestInfo* request, const std::string& headers,
UploadDataStream* request_body, HttpResponseInfo* response,
CompletionCallback* callback);
int ReadResponseHeaders(CompletionCallback* callback);
int ReadResponseBody(IOBuffer* buf, int buf_len,
CompletionCallback* callback);
uint64 GetUploadProgress() const;
HttpResponseInfo* GetResponseInfo();
bool <API key>() const;
bool <API key>() const;
bool IsMoreDataBuffered() const;
private:
// FOO_COMPLETE states implement the second half of potentially asynchronous
// operations and don't necessarily mean that FOO is complete.
enum State {
STATE_NONE,
<API key>,
STATE_SENDING_BODY,
STATE_REQUEST_SENT,
STATE_READ_HEADERS,
<API key>,
STATE_BODY_PENDING,
STATE_READ_BODY,
<API key>,
STATE_DONE
};
// The number of bytes by which the header buffer is grown when it reaches
// capacity.
enum { <API key> = 4096 };
// |kMaxHeaderBufSize| is the number of bytes that the response headers can
// grow to. If the body start is not found within this range of the
// response, the transaction will fail with <API key>.
// Note: |kMaxHeaderBufSize| should be a multiple of |<API key>|.
enum { kMaxHeaderBufSize = 256 * 1024 }; // 256 kilobytes.
// The maximum sane buffer size.
enum { kMaxBufSize = 2 * 1024 * 1024 }; // 2 megabytes.
// Handle callbacks.
void OnIOComplete(int result);
// Try to make progress sending/receiving the request/response.
int DoLoop(int result);
// The implementations of each state of the state machine.
int DoSendHeaders(int result);
int DoSendBody(int result);
int DoReadHeaders();
int <API key>(int result);
int DoReadBody();
int DoReadBodyComplete(int result);
// Examines |read_buf_| to find the start and end of the headers. Return
// the offset for the end of the headers, or -1 if the complete headers
// were not found. If they are are found, parse them with
// <API key>().
int <API key>();
// Parse the headers into response_.
void <API key>(int <API key>);
// Examine the parsed headers to try to determine the response body size.
void <API key>();
// Current state of the request.
State io_state_;
// The request to send.
const HttpRequestInfo* request_;
// The request header data.
scoped_refptr<DrainableIOBuffer> request_headers_;
// The request body data.
scoped_ptr<UploadDataStream> request_body_;
// Temporary buffer for reading.
scoped_refptr<GrowableIOBuffer> read_buf_;
// Offset of the first unused byte in |read_buf_|. May be nonzero due to
// a 1xx header, or body data in the same packet as header data.
int <API key>;
// The amount beyond |<API key>| where the status line starts;
// -1 if not found yet.
int <API key>;
// The parsed response headers. Owned by the caller.
HttpResponseInfo* response_;
// Indicates the content length. If this value is less than zero
// (and chunked_decoder_ is null), then we must read until the server
// closes the connection.
int64 <API key>;
// Keep track of the number of response body bytes read so far.
int64 response_body_read_;
// Helper if the data is chunked.
scoped_ptr<HttpChunkedDecoder> chunked_decoder_;
// Where the caller wants the body data.
scoped_refptr<IOBuffer> user_read_buf_;
int user_read_buf_len_;
// The callback to notify a user that their request or response is
// complete or there was an error
CompletionCallback* user_callback_;
// In the client callback, the client can do anything, including
// destroying this class, so any pending callback must be issued
// after everything else is done. When it is time to issue the client
// callback, move it from |user_callback_| to |scheduled_callback_|.
CompletionCallback* scheduled_callback_;
// The underlying socket.
ClientSocketHandle* const connection_;
scoped_refptr<LoadLog> load_log_;
// Callback to be used when doing IO.
<API key><HttpStreamParser> io_callback_;
<API key>(HttpStreamParser);
};
} // namespace net
#endif // <API key>
|
# Goga – examples
## Summary
0. Simple functions
1. Constrained one-objective problems
2. Unconstrained two-objective problems
3. Constrained two-objective problems
4. Constrained and unconstrained three-objective problems
5. Unconstrained many-objectives problems
6. Truss shape and topology optimisation
7. Economic emission load dispatch
# 0 Simple functions
Goga can use two types of objective functions:
(A) the higher-level one: MinProb\_t which takes the vector of random variables x and returns
the objectives values in f. It may also return the inequality constraints in g and the
equality constraints in h. It also accepts integer random variables in y
(B) the lower-level one: ObjFunc\_t which takes the pointer to a candidate solution object
(Solution) and fills the Ova array in this object with the objective values. In this method
the vector of random variables x is stored as Flt
Both functions take the cpu number as input if that's necessary (rarely)
The functions definitions of each case are shown below
ObjFunc\_t defines the objective fuction
`type ObjFunc_t func(sol *Solution, cpu int)`
MinProb\_t defines objective functon for specialised minimisation problem
`type MinProb_t func(f, g, h, x []float64, y []int, cpu int)`
## Curve 1
go
func fcnA(f, g, h, x []float64, y []int, cpu int) {
f[0] = 2.0 + (1.0+x[0])*(1.0+x[0])
}
// case B: finding the minimum of
func fcnB(sol *goga.Solution, cpu int) {
x := sol.Flt
sol.Ova[0] = 2.0 + (1.0+x[0])*(1.0+x[0])
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{-2} // must set minimum
opt.FltMax = []float64{2} // must set maximum
// initialise the solver
useMethodA := false
if useMethodA {
opt.Init(goga.GenTrialSolutions, nil, fcnA, nf, ng, nh)
} else {
opt.Init(goga.GenTrialSolutions, fcnB, nil, nf, ng, nh)
}
// solve problem
opt.Solve()
// print results
xBest := opt.Solutions[0].Flt[0]
fBest := 2.0 + (1.0+xBest)*(1.0+xBest)
io.Pf("xBest = %v\n", xBest)
io.Pf("f(xBest) = %v\n", fBest)
// plotting
fvec := []float64{0} // temporary vector to use with fcnA
xvec := []float64{0} // temporary vector to use with fcnA
X := utl.LinSpace(-2, 2, 101)
F := utl.GetMapped(X, func(x float64) float64 {
xvec[0] = x
fcnA(fvec, nil, nil, xvec, nil, 0)
return fvec[0]
})
plt.Reset(true, nil)
plt.PlotOne(xBest, fBest, &plt.A{C: "r", M: "o", Ms: 20, NoClip: true})
plt.Plot(X, F, nil)
plt.Gll("$x$", "$f$", nil)
plt.Save("/tmp/goga", "simple01")
}
Source code: <a href="simple/simple01.go">simple/simple01.go</a>
<div id="container">
<p><img src="simple/figs/simple01.png" width="450"></p>
Output of simple01.go
</div>
## Curve 2
go
// objective function
func fcn(f, g, h, x []float64, y []int, cpu int) {
f[0] = Cos(8*x[0]*Pi) * Exp(Cos(x[0]*Pi)-1)
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{0} // must set minimum
opt.FltMax = []float64{2} // must set maximum
// initialise the solver
opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh)
// solve problem
opt.Solve()
// auxiliary
fvec := []float64{0} // temporary vector to use with fcn
xvec := []float64{0} // temporary vector to use with fcn
// print results
xBest := opt.Solutions[0].Flt[0]
xvec[0] = xBest
fcn(fvec, nil, nil, xvec, nil, 0)
fBest := fvec[0]
io.Pf("xBest = %v\n", xBest)
io.Pf("f(xBest) = %v\n", fBest)
// generate f(x) curve
X := utl.LinSpace(opt.FltMin[0], opt.FltMax[0], 1001)
F := utl.GetMapped(X, func(x float64) float64 {
xvec[0] = x
fcn(fvec, nil, nil, xvec, nil, 0)
return fvec[0]
})
// plotting
plt.Reset(true, nil)
plt.PlotOne(xBest, fBest, &plt.A{L: "best", C: "#bf2e64", M: ".", Ms: 15, NoClip: true})
opt.PlotAddFltOva(0, 0, opt.Solutions, 1, &plt.A{L: "all", C: "g", Ls: "none", M: ".", NoClip: true})
plt.Plot(X, F, &plt.A{L: "f(x)", C: "#0077d2"})
plt.Gll("$x$", "$f$", nil)
plt.Save("/tmp/goga", "simple02")
}
Source code: <a href="simple/simple02.go">simple/simple02.go</a>
<div id="container">
<p><img src="simple/figs/simple02.png" width="450"></p>
Output of simple02.go
</div>
## Cross-in-tray function
See [cross-in-tray function on wikipedia](https://en.wikipedia.org/wiki/<API key>)
go
// objective function
func fcn(f, g, h, x []float64, y []int, cpu int) {
f[0] = -0.0001 * Pow(Abs(Sin(x[0])*Sin(x[1])*Exp(Abs(100-Sqrt(Pow(x[0], 2)+Pow(x[1], 2))/Pi)))+1, 0.1)
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{-10, -10} // must set minimum
opt.FltMax = []float64{+10, +10} // must set maximum
opt.Nsol = 80
// initialise the solver
opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh)
// solve problem
tstart := time.Now()
opt.Solve()
cputime := time.Now().Sub(tstart)
// print results
fvec := []float64{0} // temporary vector to use with fcn
xbest := opt.Solutions[0].Flt
fcn(fvec, nil, nil, xbest, nil, 0)
io.Pf("xBest = %v\n", xbest)
io.Pf("f(xBest) = %v\n", fvec)
// plotting
pp := goga.NewPlotParams(false)
pp.Npts = 101
pp.ArgsF.NoLines = true
pp.ArgsF.CmapIdx = 4
plt.Reset(true, nil)
plt.Title(io.Sf("Nsol(pop.size)=%d Tmax(generations)=%d CpuTime=%v", opt.Nsol, opt.Tmax, io.RoundDuration(cputime, 1e3)), &plt.A{Fsz: 8})
opt.PlotContour(0, 1, 0, pp)
plt.PlotOne(xbest[0], xbest[1], &plt.A{C: "r", Mec: "r", M: "*"})
plt.Gll("$x_0$", "$x_1$", nil)
plt.Save("/tmp/goga", "cross-in-tray")
}
Source code: <a href="simple/cross-in-tray.go">simple/cross-in-tray.go</a>
<div id="container">
<p><img src="simple/figs/cross-in-tray.png" width="450"></p>
Output of cross-in-tray.go
</div>
To check the **repeatability** of the code, the optimisation loop can be called several times. This
can be done with the `RunMany` function. For example, replace `opt.Solve()` with
go
// solve problem
opt.RunMany("", "", false)
// stat
opt.PrintStatF(0)
Which will produce something similar to:
fmin = -2.0626118708227428
fave = -2.062611870822731
fmax = -2.0626118708217605
fdev = 9.817431965542015e-14
[-2.11,-2.10) | 0
[-2.10,-2.08) | 0
[-2.08,-2.07) | 0
[-2.07,-2.06) | 100
[-2.06,-2.04) | 0
[-2.04,-2.03) | 0
[-2.03,-2.01) | 0
count = 100
Source code: <a href="simple/cross-in-tray-stat.go">simple/cross-in-tray-stat.go</a>
# 1 Constrained one-objective problems
Source code: <a href="01-one-obj/one-obj.go">one-obj.go</a>
# 2 Unconstrained two-objective problems
Source code: <a href="02-two-obj/two-obj.go">two-obj.go</a>
# 3 Constrained two-objective problems
Source code: <a href="03-two-obj-ct/two-obj-ct.go">two-obj-ct.go</a>
# 4 Constrained and unconstrained three-objective problems
Source code: <a href="04-three-obj/three-obj.go">three-obj.go</a>
# 5 Unconstrained many-objectives problems
Source code: <a href="05-many-obj/many-obj.go">many-obj.go</a>
# 6 Truss shape and topology optimisation
Source code: <a href="06-truss/topology.go">topology.go</a>
and <a href="06-truss/femsim.go">femsim.go</a>
# 7 Economic emission load dispatch
Source code: <a href="07-eed/ecoemission.go">ecoemission.go</a>
and <a href="07-eed/generators.go">generators.go</a>
|
/**
* Layout Select UI
*
* @package zork
* @subpackage form
* @author Kristof Matos <kristof.matos@megaweb.hu>
*/
( function ( global, $, js )
{
"use strict";
if ( typeof js.layoutSelect !== "undefined" )
{
return;
}
js.require( "jQuery.fn.vslider");
/**
* Generates layout select user interface from radio inputs
*
* @memberOf Zork.Form.Element
*/
global.Zork.prototype.layoutSelect = function ( element )
{
js.style('/styles/scripts/layoutselect.css');
element = $( element );
var defaultKey = element.data( "<API key>")
|| "paragraph.form.content.layout.default",
<API key> = element.data( "<API key>")
|| "paragraph.form.content.layout.default-description",
imageSrcPattern = element.data( "<API key>") || "",
selectType = element.data( "jsLayoutselectType") || "locale",
itemsPerRow = parseInt(element.data("<API key>"))>0
? parseInt(element.data("<API key>"))
: ( selectType == "local" ? 6 : 3 );
element.addClass( "layout-select "+selectType);
element.find( "label" ).each( function(idx,eleRadioItem) {
var input = $(eleRadioItem).find( ":radio" ),
inner = $('<div class="inner"/>').append(input),
title = $('<div class="title"/>').html( $(eleRadioItem).html() || js.core.translate(defaultKey) ),
overlay = $('<div class="overlay"/>'),
innerButtons = $('<div class="buttons"/>').appendTo(inner),
innerDescription = $('<p class="description"/>').appendTo(inner),
innerButtonsSelect = $('<span class="select"/>')
.html(
js.core.translate("default.select"
,js.core.userLocale)
)
.appendTo(innerButtons),
dateCreated = input.data("created") || '-',
dateModified = input.data("lastModified") || '-';
$(eleRadioItem).html('')
.append(inner)
.append(title)
.append(overlay);
if( selectType == 'import' )
{
innerDescription.html(
js.core.translate(
<API key>.replace("[value]",
input.attr( "value"))
,js.core.userLocale));
var imageSrc = imageSrcPattern
.replace("[value]",input.attr( "value"));
inner.prepend( $( "<img alt='icon' />" ).attr( "src", imageSrc ));
}
else//selectType == 'locale'
{
if( input.attr( "value") )
{
innerDescription
.append(
$('<div/>')
.append( $('<span/>').html(
js.core.translate("default.lastmodified",
js.core.userLocale)
+': ') )
.append( $('<span/>').html(dateModified) )
)
.append(
$('<div/>')
.append( $('<span/>').html(
js.core.translate("default.created",
js.core.userLocale)
+': ') )
.append( $('<span/>').html(dateCreated) )
);
js.core.translate("default.created",js.core.userLocale)
innerButtons.prepend(
$('<a class="preview"/>')
.html(
js.core.translate("default.preview"
,js.core.userLocale)
)
.attr('href','/app/'+js.core.userLocale
+'/paragraph/render/'+input.attr( "value"))
.attr('target','_blank')
);
}
}
innerButtonsSelect.on( "click", function(evt) {
element.find( "label" ).removeClass("selected");
$(evt.target.parentNode.parentNode.parentNode).addClass("selected");
} );
} );
var eleRow,
eleRowsContainer = $('<div/>').appendTo(element);
element.find( "label" ).each( function(idxItem,eleItem) {
if( idxItem%itemsPerRow==0 )
{
eleRow = $('<div />').appendTo(eleRowsContainer);
}
eleRow.append(eleItem);
} );
$(eleRowsContainer).vslider({"items":"div", "itemheight":( selectType == 'local' ? 300 : 255 )});
{
setTimeout( function(){ $('.ui-vslider').vslider('refresh') },100 );
}
};
global.Zork.prototype.layoutSelect.<API key> = true;
} ( window, jQuery, zork ) );
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Bill
*/
public class BackRightAutonomous extends CommandBase {
public BackRightAutonomous() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
/**
* Dialog to add a new visualization from any of your
* existing tables.
*
*/
cdb.admin.<API key> = cdb.core.View.extend({
events: {
"click .remove" : "_onRemove"
},
tagName: "li",
className: "table",
initialize: function() {
_.bindAll(this, "_onRemove");
this.template = this.getTemplate('dashboard/views/<API key>');
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this.$el;
},
show: function() {
this.$el.show();
},
_onRemove: function(e) {
this.killEvent(e);
this.clear();
this.trigger("remove", this);
},
clear: function() {
this.$el.hide();
}
});
cdb.admin.<API key> = cdb.admin.BaseDialog.extend({
_MAX_LAYERS: 3,
_TEXTS: {
title: _t('Create visualization'),
loading_data: _t('Loading data…'),
description: _t('Select the layers you will use on this visualization (you will be able to add more later)'),
new_vis_title: _t("Give a name to your visualization"),
no_tables: _t("Looks like you don’t have any imported data in your account. To create your first \
visualization you will need to import at least a dataset.")
},
events: cdb.core.View.extendEvents({ // do not remove
"click .add" : "_onAddTableItem",
}),
initialize: function() {
if (!this.options.user) {
new Throw("No user specified when it is needed")
}
this.user = this.options.user;
// Dialog options
_.extend(this.options, {
title: this._TEXTS.title,
template_name: 'common/views/dialog_base',
clean_on_hide: true,
ok_button_classes: "button green hidden",
ok_title: this._TEXTS.title,
modal_type: "creation",
modal_class: '<API key>',
width: this.user.isInsideOrg() ? 502 : 464
});
// Set max layers if user has this parameter
var max_user_layers = this.options.user.get('max_layers');
if (!isNaN(max_user_layers) && this._MAX_LAYERS != max_user_layers) {
this._MAX_LAYERS = max_user_layers;
}
this.ok = this.options.ok;
this.model = new cdb.core.Model();
this.model.bind("change:disabled", this._onToggleDisabled, this);
// Collection to manage the tables
this.table_items = new Backbone.Collection();
this.table_items.bind("add", this._addTableItem, this);
this.table_items.bind("remove", this._onRemove, this);
this.constructor.__super__.initialize.apply(this);
this.setWizard(this.options.wizard_option);
this.visualizations = new cdb.admin.Visualizations({ type: "derived" });
},
render_content: function() {
this.$content = $("<div>");
var temp_content = this.getTemplate('dashboard/views/<API key>');
this.$content.append(temp_content({ description: this._TEXTS.loading }));
// Tables combo
this.tableCombo = new cdb.ui.common.<API key>({
model: this.visualizations,
user: this.options.user
});
this.$content.find('.tableListCombo').append(this.tableCombo.render().el);
this.addView(this.tableCombo);
this.disableOkButton();
this._loadTables();
return this.$content;
},
_onToggleDisabled: function() {
this.tableCombo[ this.model.get("disabled") ? "disable" : "enable" ]()
this.$(".combo_wrapper")[( this.model.get("disabled") ? "addClass" : "removeClass" )]('disabled');
},
_loadTables: function() {
this.visualizations.bind('reset', this._onReset, this);
this.visualizations.options.set({ type: "table", per_page: 100000 });
var order = { data: { o: { updated_at: "desc" }, exclude_raster: true }};
this.visualizations.fetch(order);
},
_onReset: function() {
this.visualizations.unbind(null, null, this); // do this one time and one time only
if (this.visualizations.size() == 0) {
this.emptyState = true;
this._showEmpyState();
} else {
this.emptyState = false;
this._showControls();
}
},
_showEmpyState: function() {
var self = this;
this.$el.find(".loader").fadeOut(250, function() {
$(this).addClass("hidden");
self.$el.find("p").html(self._TEXTS.no_tables);
self.$el.find(".ok.button").removeClass("green").addClass("grey");
self.$el.find(".ok.button").html("Ok, let's import some data");
self.$el.find(".ok.button").fadeIn(250, function() {
self.enableOkButton();
});
});
},
_showControls: function() {
var self = this;
this.$el.find(".loader").fadeOut(250, function() {
$(this).addClass("hidden");
self.$el.find("p").html(self._TEXTS.description);
self.$el.find(".combo_wrapper").addClass('active');
self.$el.find(".ok.button").fadeIn(250, function() { $(this).removeClass("hidden"); });
self.$el.find(".cancel").fadeIn(250);
});
this._setupScroll();
},
_setupScroll: function() {
this.$scrollPane = this.$el.find(".scrollpane");
this.$scrollPane.jScrollPane({ showArrows: true, animateScroll: true, animateDuration: 150 });
this.api = this.$scrollPane.data('jsp');
},
_cleanString: function(s, n) {
if (s) {
s = s.replace(/<(?:.|\n)*?>/gm, ''); // strip HTML tags
s = s.substr(0, n-1) + (s.length > n ? '…' : ''); // truncate string
}
return s;
},
_onAddTableItem: function(e) {
this.killEvent(e);
if (this.model.get("disabled")) return;
var table = this.tableCombo.getSelected();
if (table) {
var model = new cdb.core.Model(table);
this.table_items.add(model);
}
},
_afterAddItem: function() {
if (this.table_items.length >= this._MAX_LAYERS) {
this.model.set("disabled", true);
}
},
_afterRemoveItem: function() {
if (this.table_items.length < this._MAX_LAYERS) {
this.model.set("disabled", false);
}
},
_addTableItem: function(model) {
this.enableOkButton();
this._afterAddItem();
var view = new cdb.admin.<API key>({ model: model });
this.$(".tables").append(view.render());
view.bind("remove", this._onRemoveItem, this);
view.show();
this._refreshScrollPane();
},
_onRemoveItem: function(item) {
this.table_items.remove(item.model);
this._refreshScrollPane();
this._afterRemoveItem();
},
_onRemove: function() {
if (this.table_items.length == 0) this.disableOkButton();
},
_refreshScrollPane: function() {
var self = this;
this.$(".scrollpane").animate({
height: this.$(".tables").height() + 5 }, { duration: 150, complete: function() {
self.api && self.api.reinitialise();
}});
},
_ok: function(ev) {
this.killEvent(ev);
if (this.emptyState) {
this.hide();
this.trigger("navigate_tables", this);
} else {
if (this.table_items.length === 0) return;
this.hide();
this.<API key>();
}
},
<API key>: function() {
var selected_tables = this.table_items.pluck("vis_id");
var tables = _.compact(
this.visualizations.map(function(m) {
if (_.contains(selected_tables, m.get('id'))) {
return m.get('table').name
}
return false;
})
);
var dlg = new cdb.admin.NameVisualization({
msg: this._TEXTS.new_vis_title,
onResponse: function(name) {
var vis = new cdb.admin.Visualization();
vis.save({ name: name, tables: tables }).success(function() {
window.location.href = vis.viewUrl();
});
}
});
dlg.bind("will_open", function() {
$("body").css({ overflow: "hidden" });
}, this);
dlg.bind("was_removed", function() {
$("body").css({ overflow: "auto" });
}, this);
dlg.appendToBody().open();
},
clean: function() {
$(".select2-drop.select2-drop-active").hide();
cdb.admin.BaseDialog.prototype.clean.call(this);
}
});
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0) on Wed May 09 10:30:52 EDT 2007 -->
<TITLE>
B-Index
</TITLE>
<META NAME="date" CONTENT="2007-05-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="B-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-1.html"><B>PREV LETTER</B></A>
<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR>
<A NAME="_B_"></A><H2>
<B>B</B></H2>
<DL>
<DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class)"><B>buildTestSuite(Class<?>)</B></A> -
Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A>
<DD>Scan through a given class <code>c</code> to find any inner classes
that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>.
<DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class, java.lang.String)"><B>buildTestSuite(Class<?>, String)</B></A> -
Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A>
<DD>Scan through a given class <code>c</code> to find any inner classes
that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>.
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-1.html"><B>PREV LETTER</B></A>
<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR>
</BODY>
</HTML>
|
#pragma once
#include <QtCore/QMap>
#include <QtGui/QIcon>
class Property;
class BoolPropertyManager;
class <API key>
{
BoolPropertyManager* <API key>;
friend class BoolPropertyManager;
public:
<API key>();
<API key>(const <API key>&) = delete;
<API key>& operator=(const <API key>&) = delete;
QMap<const Property*, bool> values_;
const QIcon checkedIcon_;
const QIcon uncheckedIcon_;
};
|
# The purpose of these tests are to ensure that calling ufuncs with quantities
# returns quantities with the right units, or raises exceptions.
import warnings
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
from ... import units as u
from ...tests.helper import raises
from ...extern.six.moves import zip
from ...utils.compat import NUMPY_LT_1_13
class TestUfuncCoverage(object):
"""Test that we cover all ufunc's"""
def test_coverage(self):
all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values()
if type(ufunc) == np.ufunc])
from .. import quantity_helper as qh
all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS |
set(qh.UFUNC_HELPERS.keys()))
assert all_np_ufuncs - all_q_ufuncs == set([])
assert all_q_ufuncs - all_np_ufuncs == set([])
class <API key>(object):
"""
Test trigonometric functions
"""
def test_sin_scalar(self):
q = np.sin(30. * u.degree)
assert q.unit == u.<API key>
assert_allclose(q.value, 0.5)
def test_sin_array(self):
q = np.sin(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian)
assert q.unit == u.<API key>
assert_allclose(q.value,
np.array([0., 1. / np.sqrt(2.), 1.]), atol=1.e-15)
def test_arcsin_scalar(self):
q1 = 30. * u.degree
q2 = np.arcsin(np.sin(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_arcsin_array(self):
q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian
q2 = np.arcsin(np.sin(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.sin(3. * u.m)
assert exc.value.args[0] == ("Can only apply 'sin' function "
"to quantities with angle units")
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.arcsin(3. * u.m)
assert exc.value.args[0] == ("Can only apply 'arcsin' function to "
"dimensionless quantities")
def <API key>(self):
a = 15 * u.kpc
b = 27 * u.pc
with warnings.catch_warnings():
warnings.filterwarnings('error')
np.arcsin(b/a)
def test_cos_scalar(self):
q = np.cos(np.pi / 3. * u.radian)
assert q.unit == u.<API key>
assert_allclose(q.value, 0.5)
def test_cos_array(self):
q = np.cos(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian)
assert q.unit == u.<API key>
assert_allclose(q.value,
np.array([1., 1. / np.sqrt(2.), 0.]), atol=1.e-15)
def test_arccos_scalar(self):
q1 = np.pi / 3. * u.radian
q2 = np.arccos(np.cos(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_arccos_array(self):
q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian
q2 = np.arccos(np.cos(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.cos(3. * u.s)
assert exc.value.args[0] == ("Can only apply 'cos' function "
"to quantities with angle units")
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.arccos(3. * u.s)
assert exc.value.args[0] == ("Can only apply 'arccos' function to "
"dimensionless quantities")
def test_tan_scalar(self):
q = np.tan(np.pi / 3. * u.radian)
assert q.unit == u.<API key>
assert_allclose(q.value, np.sqrt(3.))
def test_tan_array(self):
q = np.tan(np.array([0., 45., 135., 180.]) * u.degree)
assert q.unit == u.<API key>
assert_allclose(q.value,
np.array([0., 1., -1., 0.]), atol=1.e-15)
def test_arctan_scalar(self):
q = np.pi / 3. * u.radian
assert np.arctan(np.tan(q))
def test_arctan_array(self):
q = np.array([10., 30., 70., 80.]) * u.degree
assert_allclose(np.arctan(np.tan(q)).to_value(q.unit), q.value)
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.tan(np.array([1, 2, 3]) * u.N)
assert exc.value.args[0] == ("Can only apply 'tan' function "
"to quantities with angle units")
def <API key>(self):
with pytest.raises(TypeError) as exc:
np.arctan(np.array([1, 2, 3]) * u.N)
assert exc.value.args[0] == ("Can only apply 'arctan' function to "
"dimensionless quantities")
def test_arctan2_valid(self):
q1 = np.array([10., 30., 70., 80.]) * u.m
q2 = 2.0 * u.km
assert np.arctan2(q1, q2).unit == u.radian
assert_allclose(np.arctan2(q1, q2).value,
np.arctan2(q1.value, q2.to_value(q1.unit)))
q3 = q1 / q2
q4 = 1.
at2 = np.arctan2(q3, q4)
assert_allclose(at2.value, np.arctan2(q3.to_value(1), q4))
def <API key>(self):
with pytest.raises(u.UnitsError) as exc:
np.arctan2(np.array([1, 2, 3]) * u.N, 1. * u.s)
assert "compatible dimensions" in exc.value.args[0]
with pytest.raises(u.UnitsError) as exc:
np.arctan2(np.array([1, 2, 3]) * u.N, 1.)
assert "dimensionless quantities when other arg" in exc.value.args[0]
def test_radians(self):
q1 = np.deg2rad(180. * u.degree)
assert_allclose(q1.value, np.pi)
assert q1.unit == u.radian
q2 = np.radians(180. * u.degree)
assert_allclose(q2.value, np.pi)
assert q2.unit == u.radian
# the following doesn't make much sense in terms of the name of the
# routine, but we check it gives the correct result.
q3 = np.deg2rad(3. * u.radian)
assert_allclose(q3.value, 3.)
assert q3.unit == u.radian
q4 = np.radians(3. * u.radian)
assert_allclose(q4.value, 3.)
assert q4.unit == u.radian
with pytest.raises(TypeError):
np.deg2rad(3. * u.m)
with pytest.raises(TypeError):
np.radians(3. * u.m)
def test_degrees(self):
# the following doesn't make much sense in terms of the name of the
# routine, but we check it gives the correct result.
q1 = np.rad2deg(60. * u.degree)
assert_allclose(q1.value, 60.)
assert q1.unit == u.degree
q2 = np.degrees(60. * u.degree)
assert_allclose(q2.value, 60.)
assert q2.unit == u.degree
q3 = np.rad2deg(np.pi * u.radian)
assert_allclose(q3.value, 180.)
assert q3.unit == u.degree
q4 = np.degrees(np.pi * u.radian)
assert_allclose(q4.value, 180.)
assert q4.unit == u.degree
with pytest.raises(TypeError):
np.rad2deg(3. * u.m)
with pytest.raises(TypeError):
np.degrees(3. * u.m)
class <API key>(object):
"""
Test other mathematical functions
"""
def <API key>(self):
assert np.multiply(4. * u.m, 2. / u.s) == 8. * u.m / u.s
assert np.multiply(4. * u.m, 2.) == 8. * u.m
assert np.multiply(4., 2. / u.s) == 8. / u.s
def test_multiply_array(self):
assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) ==
np.arange(0, 6., 2.) * u.m / u.s)
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_scalar(self, function):
assert function(4. * u.m, 2. * u.s) == function(4., 2.) * u.m / u.s
assert function(4. * u.m, 2.) == function(4., 2.) * u.m
assert function(4., 2. * u.s) == function(4., 2.) / u.s
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_array(self, function):
assert np.all(function(np.arange(3.) * u.m, 2. * u.s) ==
function(np.arange(3.), 2.) * u.m / u.s)
def <API key>(self):
inch = u.Unit(0.0254 * u.m)
dividend = np.array([1., 2., 3.]) * u.m
divisor = np.array([3., 4., 5.]) * inch
quotient = dividend // divisor
remainder = dividend % divisor
assert_allclose(quotient.value, [13., 19., 23.])
assert quotient.unit == u.<API key>
assert_allclose(remainder.value, [0.0094, 0.0696, 0.079])
assert remainder.unit == dividend.unit
quotient2 = np.floor_divide(dividend, divisor)
remainder2 = np.remainder(dividend, divisor)
assert np.all(quotient2 == quotient)
assert np.all(remainder2 == remainder)
quotient3, remainder3 = divmod(dividend, divisor)
assert np.all(quotient3 == quotient)
assert np.all(remainder3 == remainder)
with pytest.raises(TypeError):
divmod(dividend, u.km)
with pytest.raises(TypeError):
dividend // u.km
with pytest.raises(TypeError):
dividend % u.km
if hasattr(np, 'divmod'): # not NUMPY_LT_1_13
quotient4, remainder4 = np.divmod(dividend, divisor)
assert np.all(quotient4 == quotient)
assert np.all(remainder4 == remainder)
with pytest.raises(TypeError):
np.divmod(dividend, u.km)
def test_sqrt_scalar(self):
assert np.sqrt(4. * u.m) == 2. * u.m ** 0.5
def test_sqrt_array(self):
assert np.all(np.sqrt(np.array([1., 4., 9.]) * u.m)
== np.array([1., 2., 3.]) * u.m ** 0.5)
def test_square_scalar(self):
assert np.square(4. * u.m) == 16. * u.m ** 2
def test_square_array(self):
assert np.all(np.square(np.array([1., 2., 3.]) * u.m)
== np.array([1., 4., 9.]) * u.m ** 2)
def <API key>(self):
assert np.reciprocal(4. * u.m) == 0.25 / u.m
def <API key>(self):
assert np.all(np.reciprocal(np.array([1., 2., 4.]) * u.m)
== np.array([1., 0.5, 0.25]) / u.m)
# cbrt only introduced in numpy 1.10
# heaviside only introduced in numpy 1.13
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def <API key>(self):
assert np.heaviside(0. * u.m, 0.5) == 0.5 * u.<API key>
assert np.heaviside(0. * u.s,
25 * u.percent) == 0.25 * u.<API key>
assert np.heaviside(2. * u.J, 0.25) == 1. * u.<API key>
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def <API key>(self):
values = np.array([-1., 0., 0., +1.])
halfway = np.array([0.75, 0.25, 0.75, 0.25]) * u.<API key>
assert np.all(np.heaviside(values * u.m,
halfway * u.<API key>) ==
[0, 0.25, 0.75, +1.] * u.<API key>)
@pytest.mark.skipif("not hasattr(np, 'cbrt')")
def test_cbrt_scalar(self):
assert np.cbrt(8. * u.m**3) == 2. * u.m
@pytest.mark.skipif("not hasattr(np, 'cbrt')")
def test_cbrt_array(self):
# Calculate cbrt on both sides since on Windows the cube root of 64
# does not exactly equal 4. See 4388.
values = np.array([1., 8., 64.])
assert np.all(np.cbrt(values * u.m**3) ==
np.cbrt(values) * u.m)
def test_power_scalar(self):
assert np.power(4. * u.m, 2.) == 16. * u.m ** 2
assert np.power(4., 200. * u.cm / u.m) == \
u.Quantity(16., u.<API key>)
# regression check on #1696
assert np.power(4. * u.m, 0.) == 1. * u.<API key>
def test_power_array(self):
assert np.all(np.power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.power(np.arange(4.) * u.m, 0.) ==
1. * u.<API key>)
# float_power only introduced in numpy 1.12
@pytest.mark.skipif("not hasattr(np, 'float_power')")
def <API key>(self):
assert np.all(np.float_power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.float_power(np.arange(4.) * u.m, 0.) ==
1. * u.<API key>)
@raises(ValueError)
def <API key>(self):
np.power(4. * u.m, [2., 4.])
@raises(ValueError)
def <API key>(self):
np.power([2., 4.] * u.m, [2., 4.])
def <API key>(self):
# Identical unit fractions are converted automatically to dimensionless
# and should be allowed as base for np.power: #4764
q = [2., 4.] * u.m / u.m
powers = [2., 4.]
res = np.power(q, powers)
assert np.all(res.value == q.value ** powers)
assert res.unit == u.<API key>
# The same holds for unit fractions that are scaled dimensionless.
q2 = [2., 4.] * u.m / u.cm
# Test also against different types of exponent
for cls in (list, tuple, np.array, np.ma.array, u.Quantity):
res2 = np.power(q2, cls(powers))
assert np.all(res2.value == q2.to_value(1) ** powers)
assert res2.unit == u.<API key>
# Though for single powers, we keep the composite unit.
res3 = q2 ** 2
assert np.all(res3.value == q2.value ** 2)
assert res3.unit == q2.unit ** 2
assert np.all(res3 == q2 ** [2, 2])
def test_power_invalid(self):
with pytest.raises(TypeError) as exc:
np.power(3., 4. * u.m)
assert "raise something to a dimensionless" in exc.value.args[0]
def <API key>(self):
assert np.copysign(3 * u.m, 1.) == 3. * u.m
assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m
assert np.copysign(3 * u.m, -1.) == -3. * u.m
assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m
def test_copysign_array(self):
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) == -np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) == -np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, np.array([-2., 2., -4.]) * u.m) == np.array([-1., 2., -3.]) * u.s)
q = np.copysign(np.array([1., 2., 3.]), -3 * u.m)
assert np.all(q == np.array([-1., -2., -3.]))
assert not isinstance(q, u.Quantity)
def test_ldexp_scalar(self):
assert np.ldexp(4. * u.m, 2) == 16. * u.m
def test_ldexp_array(self):
assert np.all(np.ldexp(np.array([1., 2., 3.]) * u.m, [3, 2, 1])
== np.array([8., 8., 6.]) * u.m)
def test_ldexp_invalid(self):
with pytest.raises(TypeError):
np.ldexp(3. * u.m, 4.)
with pytest.raises(TypeError):
np.ldexp(3., u.Quantity(4, u.m, dtype=int))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_scalar(self, function):
q = function(3. * u.m / (6. * u.m))
assert q.unit == u.<API key>
assert q.value == function(0.5)
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_array(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert q.unit == u.<API key>
assert np.all(q.value
== function(np.array([1. / 3., 1. / 2., 1.])))
# should also work on quantities that can be made dimensionless
q2 = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert q2.unit == u.<API key>
assert_allclose(q2.value,
function(np.array([100. / 3., 100. / 2., 100.])))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def <API key>(self, function):
# Can't use exp() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
function(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
def test_modf_scalar(self):
q = np.modf(9. * u.m / (600. * u.cm))
assert q == (0.5 * u.<API key>,
1. * u.<API key>)
def test_modf_array(self):
v = np.arange(10.) * u.m / (500. * u.cm)
q = np.modf(v)
n = np.modf(v.to_value(u.<API key>))
assert q[0].unit == u.<API key>
assert q[1].unit == u.<API key>
assert all(q[0].value == n[0])
assert all(q[1].value == n[1])
def test_frexp_scalar(self):
q = np.frexp(3. * u.m / (6. * u.m))
assert q == (np.array(0.5), np.array(0.0))
def test_frexp_array(self):
q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d
in zip(q[0], q[1], [1. / 3., 1. / 2., 1.]))
def <API key>(self):
# Can't use prod() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
np.frexp(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
# also does not work on quantities that can be made dimensionless
with pytest.raises(TypeError) as exc:
np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def <API key>(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm), 1.)
assert q.unit == u.<API key>
assert_allclose(q.value,
function(np.array([100. / 3., 100. / 2., 100.]), 1.))
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def <API key>(self, function):
with pytest.raises(TypeError) as exc:
function(1. * u.km / u.s, 3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
class TestInvariantUfuncs(object):
# np.positive was only added in numpy 1.13.
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.fabs,
np.conj, np.conjugate,
np.negative, np.spacing, np.rint,
np.floor, np.ceil] +
[np.positive] if hasattr(np, 'positive') else [])
def <API key>(self, ufunc):
q_i = 4.7 * u.m
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert q_o.value == ufunc(q_i.value)
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.conjugate,
np.negative, np.rint,
np.floor, np.ceil])
def <API key>(self, ufunc):
q_i = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert np.all(q_o.value == ufunc(q_i.value))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def <API key>(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.km
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def <API key>(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.us
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def <API key>(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
<API key> = np.array([0.])
q_o = ufunc(q_i1, <API key>)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, <API key>))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def <API key>(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class <API key>(object):
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def <API key>(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.Ms
q_o = ufunc(q_i1, q_i2)
assert not isinstance(q_o, u.Quantity)
assert q_o.dtype == np.bool
assert np.all(q_o == ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
q_o2 = ufunc(q_i1 / q_i2, 2.)
assert not isinstance(q_o2, u.Quantity)
assert q_o2.dtype == np.bool
assert np.all(q_o2 == ufunc((q_i1 / q_i2)
.to_value(u.<API key>), 2.))
# comparison with 0., inf, nan is OK even for dimensional quantities
for <API key> in (0., np.inf, np.nan):
ufunc(q_i1, <API key>)
ufunc(q_i1, <API key>*np.ones(len(q_i1)))
# and just for completeness
ufunc(q_i1, np.array([0., np.inf, np.nan]))
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def <API key>(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class TestInplaceUfuncs(object):
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
# without scaling
s = value * u.rad
check = s
np.sin(s, out=s)
assert check is s
assert check.unit == u.<API key>
# with scaling
s2 = (value * u.rad).to(u.deg)
check2 = s2
np.sin(s2, out=s2)
assert check2 is s2
assert check2.unit == u.<API key>
assert_allclose(s.value, s2.value)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
"""Check inplace works with non-quantity input and quantity output"""
s = value * u.m
check = s
np.absolute(value, out=s)
assert check is s
assert np.all(check.value == np.absolute(value))
assert check.unit is u.<API key>
np.sqrt(value, out=s)
assert check is s
assert np.all(check.value == np.sqrt(value))
assert check.unit is u.<API key>
np.exp(value, out=s)
assert check is s
assert np.all(check.value == np.exp(value))
assert check.unit is u.<API key>
np.arcsin(value/10., out=s)
assert check is s
assert np.all(check.value == np.arcsin(value/10.))
assert check.unit is u.radian
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
v = 100. * value * u.cm / u.m
v_copy = v.copy()
tmp = v.copy()
check = v
np.modf(v, tmp, v) # cannot use out1,out2 keywords with numpy 1.7
assert check is v
assert check.unit == u.<API key>
v2 = v_copy.to(u.<API key>)
check2 = v2
np.modf(v2, tmp, v2)
assert check2 is v2
assert check2.unit == u.<API key>
# can also replace in last position if no scaling is needed
v3 = v_copy.to(u.<API key>)
check3 = v3
np.modf(v3, v3, tmp)
assert check3 is v3
assert check3.unit == u.<API key>
# in np<1.13, without __array_ufunc__, one cannot replace input with
# first output when scaling
v4 = v_copy.copy()
if NUMPY_LT_1_13:
with pytest.raises(TypeError):
np.modf(v4, v4, tmp)
else:
check4 = v4
np.modf(v4, v4, tmp)
assert check4 is v4
assert check4.unit == u.<API key>
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
s = value * u.cycle
check = s
s /= 2.
assert check is s
assert np.all(check.value == value / 2.)
s /= u.s
assert check is s
assert check.unit == u.cycle / u.s
s *= 2. * u.s
assert check is s
assert np.all(check == value * u.cycle)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
s = value * u.cycle
check = s
np.arctan2(s, s, out=s)
assert check is s
assert check.unit == u.radian
with pytest.raises(u.UnitsError):
s += 1. * u.m
assert check is s
assert check.unit == u.radian
np.arctan2(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.radian
np.add(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.deg
np.multiply(2. / u.s, s, out=s)
assert check is s
assert check.unit == u.deg / u.s
def <API key>(self):
s = np.array([1., 2., 3.]) * u.<API key>
np.add(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert np.all(s.value == np.array([3., 6., 9.]))
assert s.unit is u.<API key>
np.arctan2(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert_allclose(s.value, np.arctan2(1., 2.))
assert s.unit is u.radian
@pytest.mark.skipif(NUMPY_LT_1_13, reason="numpy >=1.13 required.")
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def <API key>(self, value):
v = value * u.m
divisor = 70.*u.cm
v1 = v.copy()
tmp = v.copy()
check = np.divmod(v1, divisor, out=(tmp, v1))
assert check[0] is tmp and check[1] is v1
assert tmp.unit == u.<API key>
assert v1.unit == v.unit
v2 = v.copy()
check2 = np.divmod(v2, divisor, out=(v2, tmp))
assert check2[0] is v2 and check2[1] is tmp
assert v2.unit == u.<API key>
assert tmp.unit == v.unit
v3a = v.copy()
v3b = v.copy()
check3 = np.divmod(v3a, divisor, out=(v3a, v3b))
assert check3[0] is v3a and check3[1] is v3b
assert v3a.unit == u.<API key>
assert v3b.unit == v.unit
def <API key>(self):
# ensure inplace works also for non-contiguous data (closes #1834)
s = np.arange(10.) * u.m
s_copy = s.copy()
s2 = s[::2]
s2 += 1. * u.cm
assert np.all(s[::2] > s_copy[::2])
assert np.all(s[1::2] == s_copy[1::2])
def <API key>(self):
"""Check that inplace operations check properly for casting.
First two tests that check that float32 is kept close #3976.
"""
a1 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a1 *= np.float32(10)
assert a1.unit is u.m
assert a1.dtype == np.float32
a2 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a2 += (20.*u.km)
assert a2.unit is u.m
assert a2.dtype == np.float32
# For integer, in-place only works if no conversion is done.
a3 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
a3 += u.Quantity(10, u.m, dtype=np.int64)
assert a3.unit is u.m
assert a3.dtype == np.int32
a4 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
with pytest.raises(TypeError):
a4 += u.Quantity(10, u.mm, dtype=np.int64)
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncAt(object):
"""Test that 'at' method for ufuncs (calculates in-place at given indices)
For Quantities, since calculations are in-place, it makes sense only
if the result is still a quantity, and if the unit does not have to change
"""
def <API key>(self):
q = np.arange(10.) * u.m
i = np.array([1, 2])
qv = q.value.copy()
np.negative.at(q, i)
np.negative.at(qv, i)
assert np.all(q.value == qv)
assert q.unit is u.m
# cannot change from quantity to bool array
with pytest.raises(TypeError):
np.isfinite.at(q, i)
# for selective in-place, cannot change the unit
with pytest.raises(u.UnitsError):
np.square.at(q, i)
# except if the unit does not change (i.e., dimensionless)
d = np.arange(10.) * u.<API key>
dv = d.value.copy()
np.square.at(d, i)
np.square.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.<API key>
d = np.arange(10.) * u.<API key>
dv = d.value.copy()
np.log.at(d, i)
np.log.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.<API key>
# also for sine it doesn't work, even if given an angle
a = np.arange(10.) * u.radian
with pytest.raises(u.UnitsError):
np.sin.at(a, i)
# except, for consistency, if we have made radian equivalent to
# dimensionless (though hopefully it will never be needed)
av = a.value.copy()
with u.<API key>(u.<API key>()):
np.sin.at(a, i)
np.sin.at(av, i)
assert_allclose(a.value, av)
# but we won't do double conversion
ad = np.arange(10.) * u.degree
with pytest.raises(u.UnitsError):
np.sin.at(ad, i)
def <API key>(self):
s = np.arange(10.) * u.m
i = np.array([1, 2])
check = s.value.copy()
np.add.at(s, i, 1.*u.km)
np.add.at(check, i, 1000.)
assert np.all(s.value == check)
assert s.unit is u.m
with pytest.raises(u.UnitsError):
np.add.at(s, i, 1.*u.s)
# also raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.at(s, i, 1*u.s)
# but be fine if it does not
s = np.arange(10.) * u.m
check = s.value.copy()
np.multiply.at(s, i, 2.*u.<API key>)
np.multiply.at(check, i, 2)
assert np.all(s.value == check)
s = np.arange(10.) * u.m
np.multiply.at(s, i, 2.)
assert np.all(s.value == check)
# of course cannot change class of data either
with pytest.raises(TypeError):
np.greater.at(s, i, 1.*u.km)
@pytest.mark.xfail("NUMPY_LT_1_13")
class <API key>(object):
"""Test 'reduce', 'reduceat' and 'accumulate' methods for ufuncs
For Quantities, it makes sense only if the unit does not have to change
"""
def <API key>(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
i = np.array([0, 5, 1, 6])
with pytest.raises(ValueError):
np.sin.reduce(s)
with pytest.raises(ValueError):
np.sin.accumulate(s)
with pytest.raises(ValueError):
np.sin.reduceat(s, i)
def <API key>(self):
s = np.arange(10.) * u.m
i = np.array([0, 5, 1, 6])
check = s.value.copy()
s_add_reduce = np.add.reduce(s)
check_add_reduce = np.add.reduce(check)
assert s_add_reduce.value == check_add_reduce
assert s_add_reduce.unit is u.m
s_add_accumulate = np.add.accumulate(s)
<API key> = np.add.accumulate(check)
assert np.all(s_add_accumulate.value == <API key>)
assert s_add_accumulate.unit is u.m
s_add_reduceat = np.add.reduceat(s, i)
check_add_reduceat = np.add.reduceat(check, i)
assert np.all(s_add_reduceat.value == check_add_reduceat)
assert s_add_reduceat.unit is u.m
# reduce(at) or accumulate on comparisons makes no sense,
# as intermediate result is not even a Quantity
with pytest.raises(TypeError):
np.greater.reduce(s)
with pytest.raises(TypeError):
np.greater.accumulate(s)
with pytest.raises(TypeError):
np.greater.reduceat(s, i)
# raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.reduce(s)
with pytest.raises(u.UnitsError):
np.multiply.accumulate(s)
with pytest.raises(u.UnitsError):
np.multiply.reduceat(s, i)
# but be fine if it does not
s = np.arange(10.) * u.<API key>
check = s.value.copy()
s_multiply_reduce = np.multiply.reduce(s)
<API key> = np.multiply.reduce(check)
assert s_multiply_reduce.value == <API key>
assert s_multiply_reduce.unit is u.<API key>
<API key> = np.multiply.accumulate(s)
<API key> = np.multiply.accumulate(check)
assert np.all(<API key>.value == <API key>)
assert <API key>.unit is u.<API key>
s_multiply_reduceat = np.multiply.reduceat(s, i)
<API key> = np.multiply.reduceat(check, i)
assert np.all(s_multiply_reduceat.value == <API key>)
assert s_multiply_reduceat.unit is u.<API key>
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncOuter(object):
"""Test 'outer' methods for ufuncs
Just a few spot checks, since it uses the same code as the regular
ufunc call
"""
def <API key>(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
with pytest.raises(ValueError):
np.sin.outer(s)
def <API key>(self):
s1 = np.arange(10.) * u.m
s2 = np.arange(2.) * u.s
check1 = s1.value
check2 = s2.value
s12_multiply_outer = np.multiply.outer(s1, s2)
<API key> = np.multiply.outer(check1, check2)
assert np.all(s12_multiply_outer.value == <API key>)
assert s12_multiply_outer.unit == s1.unit * s2.unit
# raise UnitsError if appropriate
with pytest.raises(u.UnitsError):
np.add.outer(s1, s2)
# but be fine if it does not
s3 = np.arange(2.) * s1.unit
check3 = s3.value
s13_add_outer = np.add.outer(s1, s3)
check13_add_outer = np.add.outer(check1, check3)
assert np.all(s13_add_outer.value == check13_add_outer)
assert s13_add_outer.unit is s1.unit
s13_greater_outer = np.greater.outer(s1, s3)
<API key> = np.greater.outer(check1, check3)
assert type(s13_greater_outer) is np.ndarray
assert np.all(s13_greater_outer == <API key>)
|
#include "third_party/blink/public/common/page/<API key>.h"
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/debug/<API key>.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/strcat.h"
#include "base/trace_event/trace_event.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/widget/<API key>.mojom.h"
#include "ui/gfx/<API key>.h"
namespace blink {
namespace {
// Used to generate unique "TabSwitching::Latency" event ids. Note: The address
// of <API key> can't be used as an id because a single
// <API key> can generate multiple overlapping events.
int <API key> = 0;
const char* GetHistogramSuffix(
bool has_saved_frames,
const mojom::<API key>& start_state) {
if (has_saved_frames)
return "WithSavedFrames";
if (start_state.<API key>) {
return "<API key>";
} else {
return "<API key>";
}
}
void <API key>(const base::TimeTicks requested_time,
const gfx::<API key>& feedback) {
const base::TimeDelta delta = feedback.timestamp - requested_time;
UMA_HISTOGRAM_TIMES("Aura.<API key>", delta);
}
void <API key>(
const base::TimeTicks requested_time,
const gfx::<API key>& feedback) {
const base::TimeDelta delta = feedback.timestamp - requested_time;
// Histogram to record the content to visible duration after restoring a page
// from back-forward cache. Here min, max bucket size are same as the
// "PageLoad.PaintTiming.<API key>" metric.
base::<API key>(
"BackForwardCache.Restore.<API key>", delta,
base::Milliseconds(10), base::Minutes(10), 100);
}
} // namespace
void <API key>(
mojom::<API key> const& from,
mojom::<API key>& to) {
to.event_start_time = std::min(to.event_start_time, from.event_start_time);
to.<API key> |= from.<API key>;
to.<API key> |= from.<API key>;
to.<API key> |= from.<API key>;
to.<API key> |= from.<API key>;
}
<API key>::<API key>()
: <API key>(
base::FeatureList::IsEnabled(blink::features::kTabSwitchMetrics2)) {}
<API key>::~<API key>() = default;
base::OnceCallback<void(const gfx::<API key>&)>
<API key>::TabWasShown(
bool has_saved_frames,
mojom::<API key> start_state,
base::TimeTicks <API key>) {
DCHECK(!start_state->event_start_time.is_null());
DCHECK(!<API key>.is_null());
DCHECK(!<API key>);
DCHECK(<API key>.is_null());
// Invalidate previously issued callbacks, to avoid accessing a null
// |<API key>|.
// called twice without a call to TabWasHidden() in-between, and remove this
// mitigation.
weak_ptr_factory_.InvalidateWeakPtrs();
has_saved_frames_ = has_saved_frames;
<API key> = std::move(start_state);
<API key> = <API key>;
// |<API key>| is only reset by <API key>
// once the metrics have been emitted.
return base::BindOnce(
&<API key>::<API key>,
weak_ptr_factory_.GetWeakPtr(), false /* is_incomplete */,
<API key>-><API key>,
<API key>-><API key>,
<API key>-><API key>);
}
base::OnceCallback<void(const gfx::<API key>&)>
<API key>::TabWasShown(
bool has_saved_frames,
base::TimeTicks event_start_time,
bool <API key>,
bool <API key>,
bool <API key>,
bool <API key>,
base::TimeTicks <API key>) {
return TabWasShown(
has_saved_frames,
mojom::<API key>::New(
event_start_time, <API key>, <API key>,
<API key>, <API key>),
<API key>);
}
void <API key>::TabWasHidden() {
if (<API key>) {
<API key>(true /* is_incomplete */,
true /* <API key> */,
false /* <API key> */,
false /* <API key> */,
gfx::<API key>::Failure());
weak_ptr_factory_.InvalidateWeakPtrs();
}
}
void <API key>::<API key>(
bool is_incomplete,
bool <API key>,
bool <API key>,
bool <API key>,
const gfx::<API key>& feedback) {
DCHECK(<API key>);
DCHECK(!<API key>.is_null());
// If the DCHECK fail, make sure <API key>::WasShown was triggered
// for recording the event.
DCHECK(<API key> || <API key> ||
<API key>);
if (<API key>) {
<API key>(
<API key>->event_start_time, feedback);
}
if (<API key>) {
<API key>(<API key>->event_start_time, feedback);
}
if (!<API key>)
return;
// Tab switching has occurred.
auto tab_switch_result = TabSwitchResult::kSuccess;
if (is_incomplete)
tab_switch_result = TabSwitchResult::kIncomplete;
else if (feedback.flags & gfx::<API key>::kFailure)
tab_switch_result = TabSwitchResult::<API key>;
const auto tab_switch_duration =
feedback.timestamp - <API key>->event_start_time;
// Record trace events.
<API key>(
"latency", "TabSwitching::Latency",
TRACE_ID_LOCAL(<API key>),
<API key>->event_start_time);
<API key>(
"latency", "TabSwitching::Latency",
TRACE_ID_LOCAL(<API key>), feedback.timestamp,
"result", tab_switch_result, "latency",
tab_switch_duration.InMillisecondsF());
++<API key>;
const char* suffix =
GetHistogramSuffix(has_saved_frames_, *<API key>);
// Record result histogram.
if (<API key>) {
base::<API key>(
base::StrCat({"Browser.Tabs.TabSwitchResult2.", suffix}),
tab_switch_result);
} else {
base::<API key>(
base::StrCat({"Browser.Tabs.TabSwitchResult.", suffix}),
tab_switch_result);
}
// Record latency histogram.
switch (tab_switch_result) {
case TabSwitchResult::kSuccess: {
if (<API key>) {
base::UmaHistogramTimes(
base::StrCat({"Browser.Tabs.<API key>.", suffix}),
tab_switch_duration);
} else {
base::UmaHistogramTimes(
base::StrCat({"Browser.Tabs.TotalSwitchDuration.", suffix}),
tab_switch_duration);
}
break;
}
case TabSwitchResult::kIncomplete: {
if (<API key>) {
base::UmaHistogramTimes(
base::StrCat(
{"Browser.Tabs.<API key>.", suffix}),
tab_switch_duration);
} else {
base::UmaHistogramTimes(
base::StrCat(
{"Browser.Tabs.<API key>.", suffix}),
tab_switch_duration);
}
break;
}
case TabSwitchResult::<API key>: {
break;
}
}
// Record legacy latency histogram.
UMA_HISTOGRAM_TIMES(
"MPArch.<API key>",
feedback.timestamp - <API key>);
// Reset tab switch information.
has_saved_frames_ = false;
<API key>.reset();
<API key> = base::TimeTicks();
}
} // namespace blink
|
package de.uni.freiburg.iig.telematik.sewol.accesscontrol.rbac.lattice.graphic;
import org.apache.commons.collections15.Factory;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
public class RoleGraphViewer {
Graph<Integer, String> g;
int nodeCount, edgeCount;
Factory<Integer> vertexFactory;
Factory<String> edgeFactory;
/** Creates a new instance of SimpleGraphView */
public RoleGraphViewer() {
// Graph<V, E> where V is the type of the vertices and E is the type of
// the edges
g = new SparseMultigraph<Integer, String>();
nodeCount = 0;
edgeCount = 0;
vertexFactory = new Factory<Integer>() { // My vertex factory
public Integer create() {
return nodeCount++;
}
};
edgeFactory = new Factory<String>() { // My edge factory
public String create() {
return "E" + edgeCount++;
}
};
}
}
|
/**
* @author
*/
imports("Controls.Composite.Carousel");
using("System.Fx.Marquee");
var Carousel = Control.extend({
onChange: function (e) {
var ul = this.find('.x-carousel-header'), t;
if (t = ul.first(e.from))
t.removeClass('<API key>');
if(t = ul.first(e.to))
t.addClass('<API key>');
},
init: function (options) {
var me = this;
me.marquee = new Marquee(me, options.direction, options.loop, options.deferUpdate);
if (options.duration != null)
me.marquee.duration = options.duration;
if (options.delay != null)
me.marquee.delay = options.delay;
me.marquee.on('changing', me.onChange, me);
me.query('.x-carousel-header > li').setWidth(me.getWidth() / me.marquee.length).on(options.event || 'mouseover', function (e) {
me.marquee.moveTo(this.index());
});
me.onChange({to: 0});
me.marquee.start();
}
}).defineMethods("marquee", "moveTo moveBy start stop");
|
#include <lib.h>
#include <string.h>
#include <stddef.h>
char *lsearch(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
bcopy(key, last, width);
*count += 1;
return(last);
}
char *lfind(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
return((char *)NULL);
}
|
#!/usr/bin/env python
from django.core.management import setup_environ
import settings
setup_environ(settings)
import socket
from trivia.models import *
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((settings.IRC_SERVER, settings.IRC_PORT))
def send(msg):
irc.send(msg + "\r\n")
print "{SENT} " + msg
return
def msg(user, msg):
send("PRIVMSG " + user + " :" + msg)
return
def processline(line):
parts = line.split(' :',1)
args = parts[0].split(' ')
if (len(parts) > 1):
args.append(parts[1])
if args[0] == "PING":
send("PONG :" + args[1])
return
try:
if args[3] == "!questions":
questions = str(Question.objects.all())
msg(args[2], questions)
return
except IndexError:
return
# When we're done, remember to return.
return
send("USER " + (settings.IRC_NICKNAME + " ")*4)
send("NICK " + settings.IRC_NICKNAME)
for channel in settings.IRC_CHANNELS:
send("JOIN " + channel)
while True:
# EXIST
line = irc.recv(1024).rstrip()
if "\r\n" in line:
linesep = line.split()
for l in linesep:
processline(l)
continue
processline(line)
|
<reference path="../../src/CaseModel.ts" />
<reference path="../../src/CaseViewer.ts" />
<reference path="../../src/PlugInManager.ts" />
class AnnotationPlugIn extends AssureIt.PlugInSet {
constructor(public plugInManager: AssureIt.PlugInManager) {
super(plugInManager);
this.HTMLRenderPlugIn = new <API key>(plugInManager);
}
}
class <API key> extends AssureIt.HTMLRenderPlugIn {
IsEnabled(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel) : boolean {
return true;
}
Delegate(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel, element: JQuery) : boolean {
if(caseModel.Annotations.length == 0) return;
var text : string = "";
var p : {top: number; left: number} = element.position();
for(var i : number = 0; i < caseModel.Annotations.length; i++) {
text += "@" + caseModel.Annotations[i].Name + "<br>";
}
$('<div class="anno">' +
'<p>' + text + '</p>' +
'</div>')
.css({position: 'absolute', 'font-size': 25, color: 'gray', top: p.top - 20, left: p.left + 80}).appendTo(element);
return true;
}
}
|
import React from "react";
import { expect } from "chai";
import { mount } from "enzyme";
import { Provider } from "react-redux";
import Editor from "../../../src/notebook/providers/editor";
import { dummyStore } from "../../utils";
import {
UPDATE_CELL_SOURCE,
FOCUS_CELL_EDITOR
} from "../../../src/notebook/constants";
describe("EditorProvider", () => {
const store = dummyStore();
const setup = (id, cellFocused = true) =>
mount(
<Provider store={store}>
<Editor id={id} cellFocused={cellFocused} />
</Provider>
);
it("can be constructed", () => {
const component = setup("test");
expect(component).to.not.be.null;
});
it("onChange updates cell source", () =>
new Promise(resolve => {
const dispatch = action => {
expect(action.id).to.equal("test");
expect(action.source).to.equal("i love nteract");
expect(action.type).to.equal(UPDATE_CELL_SOURCE);
resolve();
};
store.dispatch = dispatch;
const wrapper = setup("test");
const onChange = wrapper
.findWhere(n => n.prop("onChange") !== undefined)
.first()
.prop("onChange");
onChange("i love nteract");
}));
it("onFocusChange can update editor focus", () =>
new Promise(resolve => {
const dispatch = action => {
expect(action.id).to.equal("test");
expect(action.type).to.equal(FOCUS_CELL_EDITOR);
resolve();
};
store.dispatch = dispatch;
const wrapper = setup("test");
const onFocusChange = wrapper
.findWhere(n => n.prop("onFocusChange") !== undefined)
.first()
.prop("onFocusChange");
onFocusChange(true);
}));
});
|
#include <errno.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <assert.h>
#include <limits.h>
#include "child.h"
#include "net.h"
extern char** environ;
struct internal_child_info {
int flags;
const struct child_start_info* csi;
int* childfd;
int pty_slave;
};
__attribute__((noreturn))
static void
child_child_1(void* arg)
{
struct internal_child_info* ci = arg;
/* Resets O_CLOEXEC */
for (int i = 0; i < 3; ++i)
xdup3nc(ci->childfd[i], i, 0);
if (ci->csi->child_chdir && chdir(ci->csi->child_chdir) == -1)
die_errno("chdir");
if (ci->flags & CHILD_SETSID)
if (setsid() == (pid_t) -1)
die_errno("setsid");
if (ci->pty_slave != -1) {
if (ioctl(ci->pty_slave, TIOCSCTTY, 0) == -1)
die_errno("TIOCSCTTY");
if (tcsetpgrp(ci->pty_slave, getpid()) == -1)
die_errno("tcsetpgrp");
}
for (int i = 0; i < NSIG; ++i)
signal(i, SIG_DFL);
sigset_t no_signals;
VERIFY(sigemptyset(&no_signals) == 0);
VERIFY(sigprocmask(SIG_SETMASK, &no_signals, NULL) == 0);
if (ci->csi->pre_exec)
ci->csi->pre_exec(ci->csi->pre_exec_data);
xexecvpe(ci->csi->exename,
ci->csi->argv,
ci->csi->environ ?: (const char* const*) environ);
}
__attribute__((noreturn))
static void
child_child(struct internal_child_info* ci)
{
struct errinfo ei = { 0 };
ei.want_msg = true;
if (!catch_error(child_child_1, ci, &ei))
abort();
fprintf(stderr, "%s: %s\n", ei.prgname, ei.msg);
fflush(stderr);
_exit(127); // Do not allow errors to propagate further
}
static void
child_cleanup(void* arg)
{
struct child* child = arg;
if (!child->dead) {
if (child->pty_master == NULL) {
int sig = child->deathsig ?: SIGTERM;
pid_t child_pid = child->pid;
if (sig < 0) {
/* Send to process group instead */
sig = -sig;
child_pid = -child_pid;
}
(void) kill(child_pid, sig);
} else {
/* In the pty case, the system's automatic SIGHUP should
* take care of the killing. */
fdh_destroy(child->pty_master);
}
if (!child->skip_cleanup_wait && !<API key>)
child_wait(child);
}
}
struct child*
child_start(const struct child_start_info* csi)
{
struct child* child = xcalloc(sizeof (*child));
struct cleanup* cl_waiter = cleanup_allocate();
SCOPED_RESLIST(rl);
int flags = csi->flags;
int pty_master = -1;
int pty_slave = -1;
if (flags & (CHILD_PTY_STDIN |
CHILD_PTY_STDOUT |
CHILD_PTY_STDERR |
CHILD_CTTY))
{
flags |= (CHILD_CTTY | CHILD_SETSID);
}
if (flags & CHILD_CTTY) {
pty_master = xopen("/dev/ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC, 0);
if (grantpt(pty_master) || unlockpt(pty_master))
die_errno("grantpt/unlockpt");
#ifdef HAVE_PTSNAME
// Yes, yes, ptsname is not thread-safe. We're
// single-threaded.
char* pty_slave_name = xstrdup(ptsname(pty_master));
#else
int pty_slave_num;
if (ioctl(pty_master, TIOCGPTN, &pty_slave_num) != 0)
die_errno("TIOCGPTN");
char* pty_slave_name = xaprintf("/dev/pts/%d", pty_slave_num);
#endif
pty_slave = xopen(pty_slave_name, O_RDWR | O_NOCTTY | O_CLOEXEC, 0);
if (csi->pty_setup)
csi->pty_setup(pty_master, pty_slave, csi->pty_setup_data);
}
int childfd[3];
int parentfd[3];
if (flags & <API key>) {
flags &= ~(CHILD_PTY_STDIN | CHILD_PTY_STDOUT);
xsocketpair(AF_UNIX, SOCK_STREAM, 0, &childfd[0], &parentfd[0]);
childfd[1] = xdup(childfd[0]);
parentfd[1] = xdup(parentfd[0]);
} else {
if (flags & CHILD_PTY_STDIN) {
childfd[0] = xdup(pty_slave);
parentfd[0] = xdup(pty_master);
} else if (flags & CHILD_NULL_STDIN) {
childfd[0] = xopen("/dev/null", O_RDONLY, 0);
parentfd[0] = xopen("/dev/null", O_WRONLY, 0);
} else {
xpipe(&childfd[0], &parentfd[0]);
}
if (flags & CHILD_PTY_STDOUT) {
childfd[1] = xdup(pty_slave);
parentfd[1] = xdup(pty_master);
} else if (flags & CHILD_NULL_STDOUT) {
childfd[1] = xopen("/dev/null", O_WRONLY, 0);
parentfd[1] = xopen("/dev/null", O_RDONLY, 0);
} else {
xpipe(&parentfd[1], &childfd[1]);
}
}
// If child has a pty for both stdout and stderr, from our POV, it
// writes only to stdout.
if ((flags & CHILD_PTY_STDERR) && (flags & CHILD_PTY_STDOUT))
flags |= CHILD_MERGE_STDERR;
if (flags & CHILD_MERGE_STDERR) {
childfd[2] = xdup(childfd[1]);
parentfd[2] = xopen("/dev/null", O_RDONLY, 0);
} else if (flags & CHILD_PTY_STDERR) {
childfd[2] = xdup(pty_slave);
parentfd[2] = xdup(pty_master);
} else if (flags & <API key>) {
childfd[2] = xdup(2);
} else if (flags & CHILD_NULL_STDERR) {
childfd[2] = xopen("/dev/null", O_WRONLY, 0);
parentfd[2] = xopen("/dev/null", O_RDONLY, 0);
} else {
xpipe(&parentfd[2], &childfd[2]);
}
<API key>(rl->parent);
child->flags = flags;
child->deathsig = csi->deathsig;
if (pty_master != -1)
child->pty_master = fdh_dup(pty_master);
child->fd[0] = fdh_dup(parentfd[0]);
child->fd[1] = fdh_dup(parentfd[1]);
if ((flags & <API key>) == 0)
child->fd[2] = fdh_dup(parentfd[2]);
// We need to block all signals until the child calls signal(2) to
// reset its signal handlers to the default. If we didn't, the
// child could run handlers we didn't expect.
sigset_t all_blocked;
sigset_t prev_blocked;
VERIFY(sigfillset(&all_blocked) == 0);
VERIFY(sigprocmask(SIG_SETMASK, &all_blocked, &prev_blocked) == 0);
pid_t child_pid = fork();
if (child_pid == 0) {
struct internal_child_info ci = {
.flags = flags,
.csi = csi,
.pty_slave = pty_slave,
.childfd = childfd,
};
child_child(&ci); // Never returns
}
VERIFY(sigprocmask(SIG_SETMASK, &prev_blocked, NULL) == 0);
if (child_pid == -1)
die_errno("fork");
child->pid = child_pid;
cleanup_commit(cl_waiter, child_cleanup, child);
return child;
}
bool
child_poll_death(struct child* child)
{
if (!child->dead) {
int ret = waitpid(child->pid, &child->status, WNOHANG);
if (ret < 0)
die_errno("waitpid");
if (ret > 0)
child->dead = true;
}
return child->dead;
}
int
child_wait(struct child* child)
{
int ret;
// N.B. THE COMMENTED CODE BELOW IS WRONG.
// <API key>();
// ret = waitpid(child->pid, &child->status, 0);
// } while (ret < 0 && errno == EINTR);
// It looks correct, doesn't it?
// Consider what happens if we get a fatal signal, say SIGINT,
// immediately after a successful return from waitpid() and
// before we restore the signal mask that blocks SIGINT.
// SIGINT runs the global cleanup handlers, one of which calls
// kill() on our subprocess's PID. (Normally, the assignment
// to child->dead below prevents our calling kill().) When
// waitpid() completes successfully, the kernel frees the
// process table entry for the process waited on. Between the
// waitpid() return and our call to kill(), another process
// can move into that process table slot, resulting in our
// subsequent kill() going to wrong process and killing an
// innocent program.
// Instead, we first block SIGCHLD (in addition to signals like
// SIGINT), then, _WITHOUT_ unblocking signals, call waitpid(...,
// WNOHANG). If that succeeds, our child is dead and we remember
// its status. If waitpid() indicates that our child is still
// running, we then wait for signals; when the child dies, we loop
// around and call waitpid() again. That waitpid() might fail if
// a different child died, or if we got a non-SIGCHLD signal, but
// eventually our child will die, waitpid() will succeed, and
// we'll exit the loop.
sigset_t block_during_poll;
if (!child->dead) {
sigemptyset(&block_during_poll);
for (int i = 1; i < NSIG; ++i)
if (!sigismember(&<API key>, i))
sigaddset(&block_during_poll, i);
sigdelset(&block_during_poll, SIGCHLD);
}
while (!child->dead) {
ret = waitpid(child->pid, &child->status, WNOHANG);
if (ret < 0) {
// waitpid will fail if child->pid isn't really our child;
// that means we have a bug somewhere, since it should be
// a zombie until we wait for it.
die_errno("waitpid(%u)", (unsigned) child->pid);
}
if (ret > 0) {
child->dead = true;
} else {
sigsuspend(&block_during_poll);
}
}
return child->status;
}
void
child_kill(struct child* child, int signo)
{
if (!child->dead && kill(child->pid, signo) == -1)
die_errno("kill");
}
static bool
any_poll_active_p(const struct pollfd* p, size_t n)
{
for (size_t i = 0; i < n; ++i)
if (p[i].fd != -1)
return true;
return false;
}
struct child_communication*
child_communicate(
struct child* child,
const void* data_for_child_in,
size_t data_for_child_size)
{
const uint8_t* data_for_child = data_for_child_in;
size_t bytes_consumed = 0;
size_t chunk_size = 512;
struct pollfd p[ARRAYSIZE(child->fd)];
memset(&p, 0, sizeof (p));
struct {
struct cleanup* cl;
uint8_t* buf;
size_t pos;
size_t sz;
} ob[ARRAYSIZE(child->fd)-1];
memset(&ob, 0, sizeof (ob));
for (int i = 0; i < ARRAYSIZE(p); ++i) {
int fd = child->fd[i]->fd;
<API key>(fd, non_blocking);
p[i].fd = fd;
p[i].events = (i == 0) ? POLLIN : POLLOUT;
}
for (;;) {
if (p[0].fd != -1) {
size_t nr_to_write = data_for_child_size - bytes_consumed;
if (nr_to_write > 0) {
ssize_t nr_written =
write(p[0].fd,
data_for_child + bytes_consumed,
XMIN(nr_to_write, (size_t) SSIZE_MAX));
if (nr_written == -1 && !error_temporary_p(errno))
die_errno("write[child]");
bytes_consumed += XMAX(nr_written, 0);
}
if (bytes_consumed == data_for_child_size) {
fdh_destroy(child->fd[0]);
p[0].fd = -1;
}
}
for (size_t i = 0; i < ARRAYSIZE(ob); ++i) {
int fd = p[i+1].fd;
if (fd == -1)
continue;
if (ob[i].pos == ob[i].sz) {
struct cleanup* newcl = cleanup_allocate();
size_t newsz;
if (SATADD(&newsz, ob[i].sz, chunk_size))
die(ERANGE, "too many bytes from child");
void* newbuf = realloc(ob[i].buf, newsz);
if (newbuf == NULL)
die(ENOMEM, "could not allocate iobuf");
cleanup_commit(newcl, free, newbuf);
cleanup_forget(ob[i].cl);
ob[i].cl = newcl;
ob[i].buf = newbuf;
ob[i].sz = newsz;
}
size_t to_read = ob[i].sz - ob[i].pos;
ssize_t nr_read = read(fd, ob[i].buf + ob[i].pos, to_read);
if (nr_read == -1 && !error_temporary_p(errno))
die_errno("read[child:%d]", fd);
ob[i].pos += XMAX(0, nr_read);
if (nr_read == 0) {
fdh_destroy(child->fd[i+1]);
p[i+1].fd = -1;
}
}
if (!any_poll_active_p(p, ARRAYSIZE(p)))
break;
int rc;
{
<API key>();
rc = poll(p, ARRAYSIZE(p), -1);
}
if (rc == -1 && errno != EINTR)
die_errno("poll");
}
struct child_communication* com = xcalloc(sizeof (*com));
com->status = child_wait(child);
com->bytes_consumed = bytes_consumed;
for (size_t i = 0; i < ARRAYSIZE(ob); ++i) {
com->out[i].bytes = ob[i].buf;
com->out[i].nr = ob[i].pos;
}
return com;
}
bool
<API key>(int status)
{
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
|
{-# LANGUAGE TemplateHaskell #-}
{-| Contains TemplateHaskell stuff I don't want to recompile every time I make
changes to other files, a pre-compiled header, so to say. Don't know if that
even works.
-}
module FeedGipeda.THGenerated
( benchmarkClosure
, stringDict
, __remoteTable
) where
import Control.Distributed.Process (Closure, Process, Static,
liftIO)
import Control.Distributed.Process.Closure (SerializableDict,
functionTDict, mkClosure,
remotable)
import FeedGipeda.GitShell (SHA)
import FeedGipeda.Repo (Repo)
import qualified FeedGipeda.Slave as Slave
import FeedGipeda.Types (Timeout)
benchmarkProcess :: (String, Repo, SHA, Rational) -> Process String
benchmarkProcess (benchmarkScript, repo, sha, timeout) =
liftIO (Slave.benchmark benchmarkScript repo sha (fromRational timeout))
remotable ['benchmarkProcess]
benchmarkClosure :: String -> Repo -> SHA -> Timeout -> Closure (Process String)
benchmarkClosure benchmarkScript repo commit timeout =
$(mkClosure 'benchmarkProcess) (benchmarkScript, repo, commit, toRational timeout)
stringDict :: Static (SerializableDict String)
stringDict =
$(functionTDict 'benchmarkProcess)
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "record".
*
* @property string $todaydetail
* @property string $st_classmark
* @property string $startday
* @property string $endday
* @property integer $totalday
* @property string $country
* @property string $countryEN
* @property string $st_name
* @property string $st_nameEN
* @property string $gaokaohao
* @property string $idcard
* @property string $sex
* @property string $st_year
* @property string $st_class
* @property string $academy
* @property string $major
* @property string $status
* @property string $model
* @property string $today
*/
class Record extends \yii\db\ActiveRecord
{
private static $_instance;
public static function getinstance()
{
if(!(self::$_instance instanceof self))
{
self::$_instance =new self();
}
return self::$_instance;
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'record';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['todaydetail', 'st_classmark'], 'required'],
[['idcard'],'string', 'length' =>18],
[['startday', 'endday'],'string', 'length' =>10],
[['totalday'], 'integer'],
[['todaydetail', 'model', 'today'], 'string', 'max' => 50],
[['st_classmark','refusereason','reason', 'country', 'countryEN', 'st_name', 'st_nameEN', 'gaokaohao', 'st_year', 'st_class', 'academy', 'major'], 'string', 'max' => 100],
[['sex', 'status'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'todaydetail' => '',
'today' => '()',
'st_classmark' => '',
'refusereason' => '()',
'reason' => '( :)',
'startday' => '',
'endday' => '',
'totalday' => '',
'country' => '',
'countryEN' => '',
'st_name' => '',
'st_nameEN' => '',
'gaokaohao' => '()',
'idcard' => '',
'sex' => '(male/female)',
'st_year' => '',
'st_class' => '',
'academy' => '',
'major' => '',
'status' => '()',
'model' => '',
];
}
}
|
package com.michaelbaranov.microba.gradient;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.michaelbaranov.microba.common.<API key>;
/**
* A very basic implementation of {@link <API key>} used by
* default by {@link GradientBar}. This implementation has bounds 0 - 100 and
* is mutable.
*
* @author Michael Baranov
*
*/
public class <API key> extends <API key> {
protected static final int POSITION_COLUMN = 0;
protected static final int COLOR_COLUMN = 1;
protected List positionList = new ArrayList(32);
protected List colorList = new ArrayList(32);
/**
* Constructor.
*/
public <API key>() {
super();
positionList.add(new Integer(0));
colorList.add(Color.YELLOW);
positionList.add(new Integer(50));
colorList.add(Color.RED);
positionList.add(new Integer(100));
colorList.add(Color.GREEN);
}
public int getLowerBound() {
return 0;
}
public int getUpperBound() {
return 100;
}
public int getRowCount() {
return positionList.size();
}
public int getColumnCount() {
return 2;
}
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return Integer.class;
case COLOR_COLUMN:
return Color.class;
}
return super.getColumnClass(columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return positionList.get(rowIndex);
case COLOR_COLUMN:
return colorList.get(rowIndex);
}
return null;
}
/**
* Adds a color point.
*
* @param color
* @param position
*/
public void add(Color color, int position) {
colorList.add(color);
positionList.add(new Integer(position));
<API key>();
}
/**
* Removes a color point at specified index.
*
* @param index
*/
public void remove(int index) {
colorList.remove(index);
positionList.remove(index);
<API key>();
}
/**
* Removes all color points.
*/
public void clear() {
colorList.clear();
positionList.clear();
<API key>();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.