code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0006_add_verbose_names'),
('home', '0006_cafepage'),
]
operations = [
migrations.CreateModel(
name='Area',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('area_name', models.CharField(max_length=50)),
],
),
migrations.AddField(
model_name='cafepage',
name='cafe_logo_image',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, null=True, to='wagtailimages.Image'),
),
migrations.AddField(
model_name='cafepage',
name='area',
field=models.ForeignKey(related_name='+', blank=True, on_delete=django.db.models.deletion.SET_NULL, null=True, to='home.Area'),
),
]
|
taedori81/gentlecoffee
|
home/migrations/0007_auto_20150909_0741.py
|
Python
|
bsd-3-clause
| 1,094 |
# Additional include directories
INCLUDE_DIRECTORIES( ${WG_TOOLS_SOURCE_DIR}/core/interfaces )
INCLUDE_DIRECTORIES( ${WG_TOOLS_SOURCE_DIR}/core/lib )
SET( WG_TOOLS_THIRD_PARTY_DIR ${WG_TOOLS_SOURCE_DIR}/core/third_party )
INCLUDE_DIRECTORIES( ${WG_TOOLS_THIRD_PARTY_DIR} )
ADD_DEFINITIONS( -DBW_BUILD_PLATFORM="${BW_PLATFORM}" )
IF( BW_PLATFORM_WINDOWS )
BW_ADD_COMPILE_FLAGS(
/fp:fast # Fast floating point model
)
# Windows version definitions
ADD_DEFINITIONS(
-DNTDDI_VERSION=0x05010000 # NTDDI_WINXP
-D_WIN32_WINNT=0x0501 # Windows XP
-D_WIN32_WINDOWS=0x0501
-D_WIN32_IE=0x0600
)
# Standard preprocessor definitions
ADD_DEFINITIONS(
-D_CRT_SECURE_NO_WARNINGS
-D_CRT_NONSTDC_NO_DEPRECATE
-D_CRT_SECURE_NO_DEPRECATE
-D_CRT_NONSTDC_NO_DEPRECATE
#-DD3DXFX_LARGEADDRESS_HANDLE # NOT YET FOR WOWP
)
ENDIF()
IF( NOT BW_NO_UNICODE )
ADD_DEFINITIONS( -DUNICODE -D_UNICODE )
ENDIF()
# Remove /STACK:10000000 set by CMake. This value for stack size
# is very high, limiting the number of threads we can spawn.
# Default value used by Windows is 1MB which is good enough.
STRING( REGEX REPLACE "/STACK:[0-9]+" ""
CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}" )
|
dava/wgtf
|
build/cmake/WGToolsProject.cmake
|
CMake
|
bsd-3-clause
| 1,236 |
import pytest
import pandas as pd
import pandas.util.testing as tm
class TestDatetimeIndex:
@pytest.mark.parametrize('tz', ['US/Eastern', 'Asia/Tokyo'])
def test_fillna_datetime64(self, tz):
# GH 11343
idx = pd.DatetimeIndex(['2011-01-01 09:00', pd.NaT,
'2011-01-01 11:00'])
exp = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 10:00',
'2011-01-01 11:00'])
tm.assert_index_equal(
idx.fillna(pd.Timestamp('2011-01-01 10:00')), exp)
# tz mismatch
exp = pd.Index([pd.Timestamp('2011-01-01 09:00'),
pd.Timestamp('2011-01-01 10:00', tz=tz),
pd.Timestamp('2011-01-01 11:00')], dtype=object)
tm.assert_index_equal(
idx.fillna(pd.Timestamp('2011-01-01 10:00', tz=tz)), exp)
# object
exp = pd.Index([pd.Timestamp('2011-01-01 09:00'), 'x',
pd.Timestamp('2011-01-01 11:00')], dtype=object)
tm.assert_index_equal(idx.fillna('x'), exp)
idx = pd.DatetimeIndex(['2011-01-01 09:00', pd.NaT,
'2011-01-01 11:00'], tz=tz)
exp = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 10:00',
'2011-01-01 11:00'], tz=tz)
tm.assert_index_equal(
idx.fillna(pd.Timestamp('2011-01-01 10:00', tz=tz)), exp)
exp = pd.Index([pd.Timestamp('2011-01-01 09:00', tz=tz),
pd.Timestamp('2011-01-01 10:00'),
pd.Timestamp('2011-01-01 11:00', tz=tz)],
dtype=object)
tm.assert_index_equal(
idx.fillna(pd.Timestamp('2011-01-01 10:00')), exp)
# object
exp = pd.Index([pd.Timestamp('2011-01-01 09:00', tz=tz),
'x',
pd.Timestamp('2011-01-01 11:00', tz=tz)],
dtype=object)
tm.assert_index_equal(idx.fillna('x'), exp)
|
cbertinato/pandas
|
pandas/tests/indexes/datetimes/test_missing.py
|
Python
|
bsd-3-clause
| 2,024 |
package Chisel
import scala.collection.mutable.ArrayBuffer
import ChiselError._
object ChiselError {
val ChiselErrors = new ArrayBuffer[ChiselError];
def apply(m: String, n: Node): ChiselError =
new ChiselError(() => m, n.line)
def apply(mf: => String, n: Node): ChiselError =
new ChiselError(() => mf, n.line)
def apply(m: String, stack: Array[StackTraceElement]): ChiselError =
new ChiselError(() => m, findFirstUserLine(stack))
def apply(mf: => String, stack: Array[StackTraceElement]): ChiselError =
new ChiselError(() => mf, findFirstUserLine(stack))
def findFirstUserLine(stack: Array[StackTraceElement]): StackTraceElement = {
for(i <- 1 until stack.length) {
val ste = stack(i)
val classname = ste.getClassName
val dotPos = classname.lastIndexOf('.')
if( dotPos > 0 ) {
val pkg = classname.subSequence(0, dotPos)
if (pkg != "Chisel" && !classname.contains("scala"))
return ste
}
}
println("COULDN'T FIND LINE NUMBER")
return stack(0)
}
def findFirstUserInd(stack: Array[StackTraceElement]): Int = {
for(i <- 1 until stack.length) {
val ste = stack(i)
val classname = ste.getClassName
val dotPos = classname.lastIndexOf('.')
val pkg = classname.subSequence(0, dotPos)
if (pkg != "Chisel" && !classname.contains("scala"))
return i
}
println("COULDN'T FIND LINE NUMBER")
return 0
}
def printError(msgFun: () => String, line: StackTraceElement) = {
println(msgFun() + " on line " + line.getLineNumber +
" in class " + line.getClassName +
" in file " + line.getFileName)
}
}
class ChiselError(val msgFun: () => String, val line: StackTraceElement) {
def printError: Unit = ChiselError.printError(msgFun, line)
}
|
seyedmaysamlavasani/GorillaPP
|
chisel/chisel/src/main/scala/ChiselError.scala
|
Scala
|
bsd-3-clause
| 1,823 |
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif
#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/fcall.h"
#include "kernel/operators.h"
#include "kernel/memory.h"
#include "kernel/array.h"
#include "ext/spl/spl_exceptions.h"
#include "kernel/exception.h"
#include "kernel/object.h"
/**
* Url validator.
*
* @package Ice/Validation
* @category Security
* @author Ice Team
* @copyright (c) 2014-2021 Ice Team
* @license http://iceframework.org/license
*
* <pre><code>
* $validation = new Ice\Validation();
*
* $validation->rules([
* 'website' => 'url'
* ]);
*
* $valid = $validation->validate($_POST);
*
* if (!$valid) {
* $messages = $validation->getMessages();
* }
* </code></pre>
*/
ZEPHIR_INIT_CLASS(Ice_Validation_Validator_Url) {
ZEPHIR_REGISTER_CLASS_EX(Ice\\Validation\\Validator, Url, ice, validation_validator_url, ice_validation_validator_ce, ice_validation_validator_url_method_entry, 0);
return SUCCESS;
}
/**
* Validate the validator
* Options: label, message
*
* @param Validation validation
* @param string field
* @return boolean
*/
PHP_METHOD(Ice_Validation_Validator_Url, validate) {
zend_bool _0, _10$$4;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval field;
zval *validation, validation_sub, *field_param = NULL, value, label, message, i18n, replace, _1, _2, _3$$4, _4$$4, _6$$4, _9$$4, _11$$4, _12$$4, _16$$4, _5$$5, _7$$7, _8$$8, _13$$9, _14$$9, _15$$9;
zval *this_ptr = getThis();
ZVAL_UNDEF(&validation_sub);
ZVAL_UNDEF(&value);
ZVAL_UNDEF(&label);
ZVAL_UNDEF(&message);
ZVAL_UNDEF(&i18n);
ZVAL_UNDEF(&replace);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_2);
ZVAL_UNDEF(&_3$$4);
ZVAL_UNDEF(&_4$$4);
ZVAL_UNDEF(&_6$$4);
ZVAL_UNDEF(&_9$$4);
ZVAL_UNDEF(&_11$$4);
ZVAL_UNDEF(&_12$$4);
ZVAL_UNDEF(&_16$$4);
ZVAL_UNDEF(&_5$$5);
ZVAL_UNDEF(&_7$$7);
ZVAL_UNDEF(&_8$$8);
ZVAL_UNDEF(&_13$$9);
ZVAL_UNDEF(&_14$$9);
ZVAL_UNDEF(&_15$$9);
ZVAL_UNDEF(&field);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(validation, ice_validation_ce)
Z_PARAM_STR(field)
ZEND_PARSE_PARAMETERS_END();
#endif
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &validation, &field_param);
if (UNEXPECTED(Z_TYPE_P(field_param) != IS_STRING && Z_TYPE_P(field_param) != IS_NULL)) {
zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'field' must be of the type string"));
RETURN_MM_NULL();
}
if (EXPECTED(Z_TYPE_P(field_param) == IS_STRING)) {
zephir_get_strval(&field, field_param);
} else {
ZEPHIR_INIT_VAR(&field);
ZVAL_EMPTY_STRING(&field);
}
ZEPHIR_CALL_METHOD(&value, validation, "getvalue", NULL, 0, &field);
zephir_check_call_status();
_0 = ZEPHIR_IS_STRING_IDENTICAL(&value, "");
if (!(_0)) {
_0 = Z_TYPE_P(&value) == IS_NULL;
}
if (_0) {
RETURN_MM_BOOL(1);
}
ZVAL_LONG(&_1, 273);
ZEPHIR_CALL_FUNCTION(&_2, "filter_var", NULL, 132, &value, &_1);
zephir_check_call_status();
if (!(zephir_is_true(&_2))) {
ZEPHIR_INIT_VAR(&_4$$4);
ZVAL_STRING(&_4$$4, "label");
ZEPHIR_CALL_METHOD(&_3$$4, this_ptr, "has", NULL, 0, &_4$$4);
zephir_check_call_status();
if (zephir_is_true(&_3$$4)) {
ZEPHIR_INIT_VAR(&_5$$5);
ZVAL_STRING(&_5$$5, "label");
ZEPHIR_CALL_METHOD(&label, this_ptr, "get", NULL, 0, &_5$$5);
zephir_check_call_status();
} else {
ZEPHIR_CALL_METHOD(&label, validation, "getlabel", NULL, 0, &field);
zephir_check_call_status();
}
ZEPHIR_INIT_NVAR(&_4$$4);
ZVAL_STRING(&_4$$4, "message");
ZEPHIR_CALL_METHOD(&_6$$4, this_ptr, "has", NULL, 0, &_4$$4);
zephir_check_call_status();
if (zephir_is_true(&_6$$4)) {
ZEPHIR_INIT_VAR(&_7$$7);
ZVAL_STRING(&_7$$7, "message");
ZEPHIR_CALL_METHOD(&message, this_ptr, "get", NULL, 0, &_7$$7);
zephir_check_call_status();
} else {
ZEPHIR_INIT_VAR(&_8$$8);
ZVAL_STRING(&_8$$8, "url");
ZEPHIR_CALL_METHOD(&message, validation, "getdefaultmessage", NULL, 0, &_8$$8);
zephir_check_call_status();
}
ZEPHIR_CALL_METHOD(&_9$$4, validation, "gettranslate", NULL, 0);
zephir_check_call_status();
_10$$4 = ZEPHIR_IS_TRUE_IDENTICAL(&_9$$4);
if (_10$$4) {
ZEPHIR_CALL_METHOD(&_11$$4, validation, "getdi", NULL, 0);
zephir_check_call_status();
ZEPHIR_INIT_NVAR(&_4$$4);
ZVAL_STRING(&_4$$4, "i18n");
ZEPHIR_CALL_METHOD(&_12$$4, &_11$$4, "has", NULL, 0, &_4$$4);
zephir_check_call_status();
_10$$4 = zephir_is_true(&_12$$4);
}
if (_10$$4) {
ZEPHIR_CALL_METHOD(&_13$$9, validation, "getdi", NULL, 0);
zephir_check_call_status();
ZEPHIR_INIT_VAR(&_14$$9);
ZVAL_STRING(&_14$$9, "i18n");
ZEPHIR_CALL_METHOD(&i18n, &_13$$9, "get", NULL, 0, &_14$$9);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&_15$$9, &i18n, "translate", NULL, 0, &label);
zephir_check_call_status();
ZEPHIR_CPY_WRT(&label, &_15$$9);
ZEPHIR_CALL_METHOD(&_15$$9, &i18n, "translate", NULL, 0, &message);
zephir_check_call_status();
ZEPHIR_CPY_WRT(&message, &_15$$9);
}
ZEPHIR_INIT_VAR(&replace);
zephir_create_array(&replace, 1, 0);
zephir_array_update_string(&replace, SL(":field"), &label, PH_COPY | PH_SEPARATE);
ZEPHIR_CALL_FUNCTION(&_16$$4, "strtr", NULL, 110, &message, &replace);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(NULL, validation, "addmessage", NULL, 0, &field, &_16$$4);
zephir_check_call_status();
RETURN_MM_BOOL(0);
}
RETURN_MM_BOOL(1);
}
|
ice/framework
|
build/php8/ice/validation/validator/url.zep.c
|
C
|
bsd-3-clause
| 5,658 |
<?php
namespace Dashboard;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Dashboard\Model\Offer;
use Dashboard\Model\OfferTable;
use Application\Model\Session;
use Application\Model\SessionTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
__DIR__ . '/autoload_login.php',
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
'autoload_login' => function($sm) {
$login = new Login();
return $login->checkLogin();
},
'Dashboard\Model\OfferTable' => function($sm) {
$tableGateway = $sm->get('OfferTableGateway');
$table = new OfferTable($tableGateway);
return $table;
},
'OfferTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Offer());
return new TableGateway('offers', $dbAdapter, null, $resultSetPrototype);
},
'Application\Model\SessionTable' => function($sm) {
$tableGateway = $sm->get('SessionTableGateway');
$table = new SessionTable($tableGateway);
return $table;
},
'SessionTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Session());
return new TableGateway('sessions', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
|
mmatusik/panel
|
module/Dashboard/Module.php
|
PHP
|
bsd-3-clause
| 2,445 |
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "bistro/bistro/runners/TaskRunner.h"
#include <folly/Random.h>
#include "bistro/bistro/config/Config.h"
#include "bistro/bistro/config/Job.h"
#include "bistro/bistro/config/Node.h"
#include "bistro/bistro/statuses/TaskStatus.h"
#include "bistro/bistro/if/gen-cpp2/common_types.h"
namespace facebook { namespace bistro {
using namespace std;
TaskRunner::TaskRunner()
: schedulerID_(
apache::thrift::FRAGILE,
time(nullptr),
// Seeded from /dev/urandom, which is important given that it would be
// pretty useless for rand to correlate with startTime.
folly::Random::rand64(folly::ThreadLocalPRNG())
) {
}
TaskRunnerResponse TaskRunner::runTask(
const Config& config,
const std::shared_ptr<const Job>& job,
const std::shared_ptr<const Node>& node,
const TaskStatus* prev_status,
std::function<void(const cpp2::RunningTask& rt, TaskStatus&& status)> cb
) noexcept {
// These pieces of data are always passed to the job, though your runner
// could add more.
const auto& path_to_node = node->getPathToNode();
folly::dynamic job_args = folly::dynamic::object
("id", job->name())
("path_to_node", folly::dynamic(path_to_node.begin(), path_to_node.end()))
("config", job->config())
("resources_by_node", folly::dynamic::object()) // populated below
;
if (prev_status) {
job_args["prev_status"] = prev_status->toDynamic();
}
// Capture the essential details for a task in a RunningTask struct.
cpp2::RunningTask rt;
rt.job = job->name();
rt.node = node->name();
// Record the resources used by this task, see comment on struct RunningTask.
// Also prepare a dynamic version of the same data to pass to the task.
const auto& job_resources = job->resources();
auto& resources_by_node = job_args.at("resources_by_node");
for (const auto& n : node->traverseUp()) {
addNodeResourcesToRunningTask(
&rt,
&resources_by_node,
config,
n.name(),
n.level(),
job_resources
);
}
// rt.workerShard is set as needed by runTaskImpl.
rt.invocationID.startTime = time(nullptr);
rt.invocationID.rand = folly::Random::rand64(folly::ThreadLocalPRNG());
if (prev_status) {
rt.nextBackoffDuration = job->backoffSettings().getNext(
prev_status->backoffDuration()
);
} else {
// Make up something. Or, should I leave this unset, and check in Snapshot?
cpp2::BackoffDuration bd;
bd.seconds = 0;
bd.noMoreBackoffs = false;
rt.nextBackoffDuration = job->backoffSettings().getNext(bd);
}
return runTaskImpl(job, node, rt, job_args, cb);
}
void TaskRunner::addNodeResourcesToRunningTask(
cpp2::RunningTask* out_rt,
folly::dynamic* out_resources_by_node,
const Config& config,
const std::string& node_name,
const int node_level,
const ResourceVector& job_resources) noexcept {
const auto& resource_ids = config.levelIDToResourceID[node_level];
// Keep the RunningTask compact by not sending nodes with empty resources
if (resource_ids.empty()) {
return;
}
out_rt->nodeResources.emplace_back();
auto& nr = out_rt->nodeResources.back();
nr.node = node_name;
auto& node_resources =
((*out_resources_by_node)[nr.node] = folly::dynamic::object());
for (int resource_id : resource_ids) {
const auto& rsrc_name = config.resourceNames.lookup(resource_id);
const auto rsrc_val = job_resources[resource_id];
nr.resources.emplace_back(apache::thrift::FRAGILE, rsrc_name, rsrc_val);
node_resources[rsrc_name] = rsrc_val;
}
}
}}
|
linearregression/bistro
|
bistro/runners/TaskRunner.cpp
|
C++
|
bsd-3-clause
| 3,869 |
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBlurDrawLooper.h"
#include "SkBlurMask.h"
#include "SkBlurMaskFilter.h"
#include "SkGradientShader.h"
#include "SkMatrix.h"
#include "SkTArray.h"
namespace skiagm {
class RectsGM : public GM {
public:
RectsGM() {
this->setBGColor(0xFF000000);
this->makePaints();
this->makeMatrices();
this->makeRects();
}
protected:
uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
SkString onShortName() SK_OVERRIDE {
return SkString("rects");
}
SkISize onISize() SK_OVERRIDE {
return SkISize::Make(1200, 900);
}
void makePaints() {
{
// no AA
SkPaint p;
p.setColor(SK_ColorWHITE);
fPaints.push_back(p);
}
{
// AA
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
fPaints.push_back(p);
}
{
// AA with translucent
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setAlpha(0x66);
fPaints.push_back(p);
}
{
// AA with mask filter
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
SkMaskFilter* mf = SkBlurMaskFilter::Create(
kNormal_SkBlurStyle,
SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(5)),
SkBlurMaskFilter::kHighQuality_BlurFlag);
p.setMaskFilter(mf)->unref();
fPaints.push_back(p);
}
{
// AA with radial shader
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
SkPoint center = SkPoint::Make(SkIntToScalar(-5), SkIntToScalar(30));
SkColor colors[] = { SK_ColorBLUE, SK_ColorRED, SK_ColorGREEN };
SkScalar pos[] = { 0, SK_ScalarHalf, SK_Scalar1 };
SkShader* s = SkGradientShader::CreateRadial(center,
SkIntToScalar(20),
colors,
pos,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
p.setShader(s)->unref();
fPaints.push_back(p);
}
{
// AA with blur
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
SkBlurDrawLooper* shadowLooper =
SkBlurDrawLooper::Create(SK_ColorWHITE,
SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(10)),
SkIntToScalar(5), SkIntToScalar(10),
SkBlurDrawLooper::kIgnoreTransform_BlurFlag |
SkBlurDrawLooper::kOverrideColor_BlurFlag |
SkBlurDrawLooper::kHighQuality_BlurFlag);
SkAutoUnref aurL0(shadowLooper);
p.setLooper(shadowLooper);
fPaints.push_back(p);
}
{
// AA with stroke style
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeWidth(SkIntToScalar(3));
fPaints.push_back(p);
}
{
// AA with bevel-stroke style
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeJoin(SkPaint::kBevel_Join);
p.setStrokeWidth(SkIntToScalar(3));
fPaints.push_back(p);
}
{
// AA with round-stroke style
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeJoin(SkPaint::kRound_Join);
p.setStrokeWidth(SkIntToScalar(3));
fPaints.push_back(p);
}
{
// AA with stroke style, width = 0
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStroke_Style);
fPaints.push_back(p);
}
{
// AA with stroke style, width wider than rect width and/or height
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeWidth(SkIntToScalar(40));
fPaints.push_back(p);
}
{
// AA with stroke and fill style
SkPaint p;
p.setColor(SK_ColorWHITE);
p.setAntiAlias(true);
p.setStyle(SkPaint::kStrokeAndFill_Style);
p.setStrokeWidth(SkIntToScalar(2));
fPaints.push_back(p);
}
}
void makeMatrices() {
{
// 1x1.5 scale
SkMatrix m;
m.setScale(1, 1.5f);
fMatrices.push_back(m);
}
{
// 1.5x1.5 scale
SkMatrix m;
m.setScale(1.5f, 1.5f);
fMatrices.push_back(m);
}
{
// 1x1.5 skew
SkMatrix m;
m.setSkew(1, 1.5f);
fMatrices.push_back(m);
}
{
// 1.5x1.5 skew
SkMatrix m;
m.setSkew(1.5f, 1.5f);
fMatrices.push_back(m);
}
{
// 30 degree rotation
SkMatrix m;
m.setRotate(SkIntToScalar(30));
fMatrices.push_back(m);
}
{
// 90 degree rotation
SkMatrix m;
m.setRotate(SkIntToScalar(90));
fMatrices.push_back(m);
}
}
void makeRects() {
{
// small square
SkRect r = SkRect::MakeLTRB(0, 0, 30, 30);
fRects.push_back(r);
}
{
// thin vertical
SkRect r = SkRect::MakeLTRB(0, 0, 2, 40);
fRects.push_back(r);
}
{
// thin horizontal
SkRect r = SkRect::MakeLTRB(0, 0, 40, 2);
fRects.push_back(r);
}
{
// very thin
SkRect r = SkRect::MakeLTRB(0, 0, 0.25f, 10);
fRects.push_back(r);
}
{
// zaftig
SkRect r = SkRect::MakeLTRB(0, 0, 60, 60);
fRects.push_back(r);
}
}
// position the current test on the canvas
static void position(SkCanvas* canvas, int testCount) {
canvas->translate(SK_Scalar1 * 100 * (testCount % 10) + SK_Scalar1 / 4,
SK_Scalar1 * 100 * (testCount / 10) + 3 * SK_Scalar1 / 4);
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkAutoCommentBlock acb(canvas, "onDraw");
canvas->translate(20 * SK_Scalar1, 20 * SK_Scalar1);
int testCount = 0;
canvas->addComment("Test", "Various Paints");
for (int i = 0; i < fPaints.count(); ++i) {
for (int j = 0; j < fRects.count(); ++j, ++testCount) {
canvas->save();
this->position(canvas, testCount);
canvas->drawRect(fRects[j], fPaints[i]);
canvas->restore();
}
}
canvas->addComment("Test", "Matrices");
SkPaint paint;
paint.setColor(SK_ColorWHITE);
paint.setAntiAlias(true);
for (int i = 0; i < fMatrices.count(); ++i) {
for (int j = 0; j < fRects.count(); ++j, ++testCount) {
canvas->save();
this->position(canvas, testCount);
canvas->concat(fMatrices[i]);
canvas->drawRect(fRects[j], paint);
canvas->restore();
}
}
}
private:
SkTArray<SkPaint> fPaints;
SkTArray<SkMatrix> fMatrices;
SkTArray<SkRect> fRects;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new RectsGM; }
static GMRegistry reg(MyFactory);
}
|
jtg-gg/skia
|
gm/rects.cpp
|
C++
|
bsd-3-clause
| 8,643 |
## django-canvas-api-token
A reusable django app for handling the workflow of generating per-user
Canvas API oauth tokens. The app assumes that your django project is using the
[django_auth_lti](https://github.com/Harvard-University-iCommons/django-auth-lti)
middleware.
Install
-------
pip install django-canvas-api-token
Setup
-----
1. Add `"canvas_api_token"` to your `INSTALLED_APPS` in django settings
2. Insert the url configuration into your project/app urls.py
```
url(r'^canvas_api_token/', include('canvas_api_token.urls'))
```
3. Run `python manage.py migrate` to ensure db tables are initialized.
4. Use the admin site to create a `canvas_dev_key` entry using the `consumer_key` and developer key values from your Canvas consumer where ...
* `client_id` is the integer client id value of your Canvas [developer key](https://canvas.instructure.com/doc/api/file.oauth.html)
* `client_secret` is the random string 'secret' value of your Canvas developer key
#### Example developer_key usage
If you are making use of the [canvas-docker](https://hub.docker.com/r/lbjay/canvas-docker/) image for development it comes
with a pre-loaded developer key. If, in addition, you are using this extension app (django-canvas-api-token)
within [harvard-dce/dce_course_admin](https://github.com/harvard-dce/dce_course_admin) and using the example consumer key,
the developer key record values would be:
* `client_id=1`
* `client_secret=test_developer_key`
* `consumer_key=dce_course_admin`
## License
django-canvas-api-token is licensed under the BSD license
## Copyright
2017 President and Fellows of Harvard College
|
harvard-dce/django-canvas-api-token
|
README.md
|
Markdown
|
bsd-3-clause
| 1,640 |
// AUTOMATICALLY GENERATED BY MIDDLECRAFT
/* Allows plugins to access server functions without needing to link the actual server Jar. */
package net.minecraft.server;
public abstract class ItemPickaxe extends ItemTool {
// FIELDS
private static Block[] goodAgainst;
private int field_4208;
// METHODS
/**
* Returns if the item (tool) can harvest results from the block type.
*/
public abstract boolean canHarvestBlock(Block a);
}
|
N3X15/MiddleCraft
|
src-interface/net/minecraft/server/ItemPickaxe.java
|
Java
|
bsd-3-clause
| 446 |
/**
* @file
* This is the IPv4 packet segmentation and reassembly implementation.
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Jani Monoses <[email protected]>
* Simon Goldschmidt
* original reassembly code by Adam Dunkels <[email protected]>
*
*/
#include "lwip/opt.h"
#include "lwip/ip_frag.h"
#include "lwip/def.h"
#include "lwip/inet_chksum.h"
#include "lwip/netif.h"
#include "lwip/snmp.h"
#include "lwip/stats.h"
#include "lwip/icmp.h"
#include "lwip/lwip_ctxt.h"
#include <string.h>
#if IP_REASSEMBLY
/**
* The IP reassembly code currently has the following limitations:
* - IP header options are not supported
* - fragments must not overlap (e.g. due to different routes),
* currently, overlapping or duplicate fragments are thrown away
* if IP_REASS_CHECK_OVERLAP=1 (the default)!
*
* @todo: work with IP header options
*/
/** Setting this to 0, you can turn off checking the fragments for overlapping
* regions. The code gets a little smaller. Only use this if you know that
* overlapping won't occur on your network! */
#ifndef IP_REASS_CHECK_OVERLAP
#define IP_REASS_CHECK_OVERLAP 1
#endif /* IP_REASS_CHECK_OVERLAP */
/** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
* full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
* Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
* is set to 1, so one datagram can be reassembled at a time, only. */
#ifndef IP_REASS_FREE_OLDEST
#define IP_REASS_FREE_OLDEST 1
#endif /* IP_REASS_FREE_OLDEST */
#define IP_REASS_FLAG_LASTFRAG 0x01
/** This is a helper struct which holds the starting
* offset and the ending offset of this fragment to
* easily chain the fragments.
* It has the same packing requirements as the IP header, since it replaces
* the IP header in memory in incoming fragments (after copying it) to keep
* track of the various fragments. (-> If the IP header doesn't need packing,
* this struct doesn't need packing, too.)
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct ip_reass_helper {
PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
PACK_STRUCT_FIELD(u16_t start);
PACK_STRUCT_FIELD(u16_t end);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB) \
(ip_addr_cmp(&(iphdrA)->src, &(iphdrB)->src) && \
ip_addr_cmp(&(iphdrA)->dest, &(iphdrB)->dest) && \
IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0
/* global variables */
//static struct ip_reassdata *reassdatagrams;
//static u16_t ip_reass_pbufcount;
/* function prototypes */
static void ip_reass_dequeue_datagram(void* ctxt, struct ip_reassdata *ipr, struct ip_reassdata *prev);
static int ip_reass_free_complete_datagram(void* ctxt, struct ip_reassdata *ipr, struct ip_reassdata *prev);
/**
* Reassembly timer base function
* for both NO_SYS == 0 and 1 (!).
*
* Should be called every 1000 msec (defined by IP_TMR_INTERVAL).
*/
void
ip_reass_tmr(void* ctxt)
{
struct ip_reassdata *r, *prev = NULL;
r = ((LwipCntxt*)ctxt)->reassdatagrams;
while (r != NULL) {
/* Decrement the timer. Once it reaches 0,
* clean up the incomplete fragment assembly */
if (r->timer > 0) {
r->timer--;
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n",(u16_t)r->timer));
prev = r;
r = r->next;
} else {
/* reassembly timed out */
struct ip_reassdata *tmp;
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n"));
tmp = r;
/* get the next pointer before freeing */
r = r->next;
/* free the helper struct and all enqueued pbufs */
ip_reass_free_complete_datagram(ctxt, tmp, prev);
}
}
}
/**
* Free a datagram (struct ip_reassdata) and all its pbufs.
* Updates the total count of enqueued pbufs (ip_reass_pbufcount),
* SNMP counters and sends an ICMP time exceeded packet.
*
* @param ipr datagram to free
* @param prev the previous datagram in the linked list
* @return the number of pbufs freed
*/
static int
ip_reass_free_complete_datagram(void* ctxt, struct ip_reassdata *ipr, struct ip_reassdata *prev)
{
u16_t pbufs_freed = 0;
u8_t clen;
struct pbuf *p;
struct ip_reass_helper *iprh;
LWIP_ASSERT("prev != ipr", prev != ipr);
if (prev != NULL) {
LWIP_ASSERT("prev->next == ipr", prev->next == ipr);
}
snmp_inc_ipreasmfails();
#if LWIP_ICMP
iprh = (struct ip_reass_helper *)ipr->p->payload;
if (iprh->start == 0) {
/* The first fragment was received, send ICMP time exceeded. */
/* First, de-queue the first pbuf from r->p. */
p = ipr->p;
ipr->p = iprh->next_pbuf;
/* Then, copy the original header into it. */
SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN);
icmp_time_exceeded(ctxt, p, ICMP_TE_FRAG);
clen = pbuf_clen(p);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed += clen;
pbuf_free(ctxt, p);
}
#endif /* LWIP_ICMP */
/* First, free all received pbufs. The individual pbufs need to be released
separately as they have not yet been chained */
p = ipr->p;
while (p != NULL) {
struct pbuf *pcur;
iprh = (struct ip_reass_helper *)p->payload;
pcur = p;
/* get the next pointer before freeing */
p = iprh->next_pbuf;
clen = pbuf_clen(pcur);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed += clen;
pbuf_free(ctxt, pcur);
}
/* Then, unchain the struct ip_reassdata from the list and free it. */
ip_reass_dequeue_datagram(ctxt, ipr, prev);
LWIP_ASSERT("ip_reass_pbufcount >= clen", (((LwipCntxt*)ctxt)->ip_reass_pbufcount) >= pbufs_freed);
(((LwipCntxt*)ctxt)->ip_reass_pbufcount) -= pbufs_freed;
return pbufs_freed;
}
#if IP_REASS_FREE_OLDEST
/**
* Free the oldest datagram to make room for enqueueing new fragments.
* The datagram 'fraghdr' belongs to is not freed!
*
* @param fraghdr IP header of the current fragment
* @param pbufs_needed number of pbufs needed to enqueue
* (used for freeing other datagrams if not enough space)
* @return the number of pbufs freed
*/
static int
ip_reass_remove_oldest_datagram(void* ctxt, struct ip_hdr *fraghdr, int pbufs_needed)
{
/* @todo Can't we simply remove the last datagram in the
* linked list behind reassdatagrams?
*/
struct ip_reassdata *r, *oldest, *prev;
int pbufs_freed = 0, pbufs_freed_current;
int other_datagrams;
/* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
* but don't free the datagram that 'fraghdr' belongs to! */
do {
oldest = NULL;
prev = NULL;
other_datagrams = 0;
r = ((LwipCntxt*)ctxt)->reassdatagrams;
while (r != NULL) {
if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) {
/* Not the same datagram as fraghdr */
other_datagrams++;
if (oldest == NULL) {
oldest = r;
} else if (r->timer <= oldest->timer) {
/* older than the previous oldest */
oldest = r;
}
}
if (r->next != NULL) {
prev = r;
}
r = r->next;
}
if (oldest != NULL) {
pbufs_freed_current = ip_reass_free_complete_datagram(ctxt, oldest, prev);
pbufs_freed += pbufs_freed_current;
}
} while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1));
return pbufs_freed;
}
#endif /* IP_REASS_FREE_OLDEST */
/**
* Enqueues a new fragment into the fragment queue
* @param fraghdr points to the new fragments IP hdr
* @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space)
* @return A pointer to the queue location into which the fragment was enqueued
*/
static struct ip_reassdata*
ip_reass_enqueue_new_datagram(void* ctxt, struct ip_hdr *fraghdr, int clen)
{
struct ip_reassdata* ipr;
/* No matching previous fragment found, allocate a new reassdata struct */
ipr = (struct ip_reassdata *)memp_malloc(ctxt, MEMP_REASSDATA);
if (ipr == NULL) {
#if IP_REASS_FREE_OLDEST
if (ip_reass_remove_oldest_datagram(ctxt, fraghdr, clen) >= clen) {
ipr = (struct ip_reassdata *)memp_malloc(ctxt, MEMP_REASSDATA);
}
if (ipr == NULL)
#endif /* IP_REASS_FREE_OLDEST */
{
IPFRAG_STATS_INC(ip_frag.memerr);
LWIP_DEBUGF(IP_REASS_DEBUG,("Failed to alloc reassdata struct\n"));
return NULL;
}
}
memset(ipr, 0, sizeof(struct ip_reassdata));
ipr->timer = IP_REASS_MAXAGE;
/* enqueue the new structure to the front of the list */
ipr->next = ((LwipCntxt*)ctxt)->reassdatagrams;
((LwipCntxt*)ctxt)->reassdatagrams = ipr;
/* copy the ip header for later tests and input */
/* @todo: no ip options supported? */
SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN);
return ipr;
}
/**
* Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs.
* @param ipr points to the queue entry to dequeue
*/
static void
ip_reass_dequeue_datagram(void* ctxt, struct ip_reassdata *ipr, struct ip_reassdata *prev)
{
/* dequeue the reass struct */
if (((LwipCntxt*)ctxt)->reassdatagrams == ipr) {
/* it was the first in the list */
((LwipCntxt*)ctxt)->reassdatagrams = ipr->next;
} else {
/* it wasn't the first, so it must have a valid 'prev' */
LWIP_ASSERT("sanity check linked list", prev != NULL);
prev->next = ipr->next;
}
/* now we can free the ip_reass struct */
memp_free(ctxt, MEMP_REASSDATA, ipr);
}
/**
* Chain a new pbuf into the pbuf list that composes the datagram. The pbuf list
* will grow over time as new pbufs are rx.
* Also checks that the datagram passes basic continuity checks (if the last
* fragment was received at least once).
* @param root_p points to the 'root' pbuf for the current datagram being assembled.
* @param new_p points to the pbuf for the current fragment
* @return 0 if invalid, >0 otherwise
*/
static int
ip_reass_chain_frag_into_datagram_and_validate(void* ctxt, struct ip_reassdata *ipr, struct pbuf *new_p)
{
struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
struct pbuf *q;
u16_t offset,len;
struct ip_hdr *fraghdr;
int valid = 1;
/* Extract length and fragment offset from current fragment */
fraghdr = (struct ip_hdr*)new_p->payload;
len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
/* overwrite the fragment's ip header from the pbuf with our helper struct,
* and setup the embedded helper structure. */
/* make sure the struct ip_reass_helper fits into the IP header */
LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN",
sizeof(struct ip_reass_helper) <= IP_HLEN);
iprh = (struct ip_reass_helper*)new_p->payload;
iprh->next_pbuf = NULL;
iprh->start = offset;
iprh->end = offset + len;
/* Iterate through until we either get to the end of the list (append),
* or we find on with a larger offset (insert). */
for (q = ipr->p; q != NULL;) {
iprh_tmp = (struct ip_reass_helper*)q->payload;
if (iprh->start < iprh_tmp->start) {
/* the new pbuf should be inserted before this */
iprh->next_pbuf = q;
if (iprh_prev != NULL) {
/* not the fragment with the lowest offset */
#if IP_REASS_CHECK_OVERLAP
if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) {
/* fragment overlaps with previous or following, throw away */
goto freepbuf;
}
#endif /* IP_REASS_CHECK_OVERLAP */
iprh_prev->next_pbuf = new_p;
} else {
/* fragment with the lowest offset */
ipr->p = new_p;
}
break;
} else if(iprh->start == iprh_tmp->start) {
/* received the same datagram twice: no need to keep the datagram */
goto freepbuf;
#if IP_REASS_CHECK_OVERLAP
} else if(iprh->start < iprh_tmp->end) {
/* overlap: no need to keep the new datagram */
goto freepbuf;
#endif /* IP_REASS_CHECK_OVERLAP */
} else {
/* Check if the fragments received so far have no wholes. */
if (iprh_prev != NULL) {
if (iprh_prev->end != iprh_tmp->start) {
/* There is a fragment missing between the current
* and the previous fragment */
valid = 0;
}
}
}
q = iprh_tmp->next_pbuf;
iprh_prev = iprh_tmp;
}
/* If q is NULL, then we made it to the end of the list. Determine what to do now */
if (q == NULL) {
if (iprh_prev != NULL) {
/* this is (for now), the fragment with the highest offset:
* chain it to the last fragment */
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start);
#endif /* IP_REASS_CHECK_OVERLAP */
iprh_prev->next_pbuf = new_p;
if (iprh_prev->end != iprh->start) {
valid = 0;
}
} else {
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("no previous fragment, this must be the first fragment!",
ipr->p == NULL);
#endif /* IP_REASS_CHECK_OVERLAP */
/* this is the first fragment we ever received for this ip datagram */
ipr->p = new_p;
}
}
/* At this point, the validation part begins: */
/* If we already received the last fragment */
if ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0) {
/* and had no wholes so far */
if (valid) {
/* then check if the rest of the fragments is here */
/* Check if the queue starts with the first datagram */
if (((struct ip_reass_helper*)ipr->p->payload)->start != 0) {
valid = 0;
} else {
/* and check that there are no wholes after this datagram */
iprh_prev = iprh;
q = iprh->next_pbuf;
while (q != NULL) {
iprh = (struct ip_reass_helper*)q->payload;
if (iprh_prev->end != iprh->start) {
valid = 0;
break;
}
iprh_prev = iprh;
q = iprh->next_pbuf;
}
/* if still valid, all fragments are received
* (because to the MF==0 already arrived */
if (valid) {
LWIP_ASSERT("sanity check", ipr->p != NULL);
LWIP_ASSERT("sanity check",
((struct ip_reass_helper*)ipr->p->payload) != iprh);
LWIP_ASSERT("validate_datagram:next_pbuf!=NULL",
iprh->next_pbuf == NULL);
LWIP_ASSERT("validate_datagram:datagram end!=datagram len",
iprh->end == ipr->datagram_len);
}
}
}
/* If valid is 0 here, there are some fragments missing in the middle
* (since MF == 0 has already arrived). Such datagrams simply time out if
* no more fragments are received... */
return valid;
}
/* If we come here, not all fragments were received, yet! */
return 0; /* not yet valid! */
#if IP_REASS_CHECK_OVERLAP
freepbuf:
(((LwipCntxt*)ctxt)->ip_reass_pbufcount) -= pbuf_clen(new_p);
pbuf_free(ctxt, new_p);
return 0;
#endif /* IP_REASS_CHECK_OVERLAP */
}
/**
* Reassembles incoming IP fragments into an IP datagram.
*
* @param p points to a pbuf chain of the fragment
* @return NULL if reassembly is incomplete, ? otherwise
*/
struct pbuf *
ip_reass(void* ctxt, struct pbuf *p)
{
struct pbuf *r;
struct ip_hdr *fraghdr;
struct ip_reassdata *ipr;
struct ip_reass_helper *iprh;
u16_t offset, len;
u8_t clen;
struct ip_reassdata *ipr_prev = NULL;
IPFRAG_STATS_INC(ip_frag.recv);
snmp_inc_ipreasmreqds();
fraghdr = (struct ip_hdr*)p->payload;
if ((IPH_HL(fraghdr) * 4) != IP_HLEN) {
LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: IP options currently not supported!\n"));
IPFRAG_STATS_INC(ip_frag.err);
goto nullreturn;
}
offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
/* Check if we are allowed to enqueue more datagrams. */
clen = pbuf_clen(p);
if (( (((LwipCntxt*)ctxt)->ip_reass_pbufcount) + clen) > IP_REASS_MAX_PBUFS) {
#if IP_REASS_FREE_OLDEST
if (!ip_reass_remove_oldest_datagram(ctxt, fraghdr, clen) ||
(((((LwipCntxt*)ctxt)->ip_reass_pbufcount) + clen) > IP_REASS_MAX_PBUFS))
#endif /* IP_REASS_FREE_OLDEST */
{
/* No datagram could be freed and still too many pbufs enqueued */
LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n",
(((LwipCntxt*)ctxt)->ip_reass_pbufcount), clen, IP_REASS_MAX_PBUFS));
IPFRAG_STATS_INC(ip_frag.memerr);
/* @todo: send ICMP time exceeded here? */
/* drop this pbuf */
goto nullreturn;
}
}
/* Look for the datagram the fragment belongs to in the current datagram queue,
* remembering the previous in the queue for later dequeueing. */
for (ipr = ((LwipCntxt*)ctxt)->reassdatagrams; ipr != NULL; ipr = ipr->next) {
/* Check if the incoming fragment matches the one currently present
in the reassembly buffer. If so, we proceed with copying the
fragment into the buffer. */
if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass: matching previous fragment ID=%"X16_F"\n",
ntohs(IPH_ID(fraghdr))));
IPFRAG_STATS_INC(ip_frag.cachehit);
break;
}
ipr_prev = ipr;
}
if (ipr == NULL) {
/* Enqueue a new datagram into the datagram queue */
ipr = ip_reass_enqueue_new_datagram(ctxt, fraghdr, clen);
/* Bail if unable to enqueue */
if(ipr == NULL) {
goto nullreturn;
}
} else {
if (((ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
((ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
/* ipr->iphdr is not the header from the first fragment, but fraghdr is
* -> copy fraghdr into ipr->iphdr since we want to have the header
* of the first fragment (for ICMP time exceeded and later, for copying
* all options, if supported)*/
SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN);
}
}
/* Track the current number of pbufs current 'in-flight', in order to limit
the number of fragments that may be enqueued at any one time */
(((LwipCntxt*)ctxt)->ip_reass_pbufcount) += clen;
/* At this point, we have either created a new entry or pointing
* to an existing one */
/* check for 'no more fragments', and update queue entry*/
if ((IPH_OFFSET(fraghdr) & PP_NTOHS(IP_MF)) == 0) {
ipr->flags |= IP_REASS_FLAG_LASTFRAG;
ipr->datagram_len = offset + len;
LWIP_DEBUGF(IP_REASS_DEBUG,
("ip_reass: last fragment seen, total len %"S16_F"\n",
ipr->datagram_len));
}
/* find the right place to insert this pbuf */
/* @todo: trim pbufs if fragments are overlapping */
if (ip_reass_chain_frag_into_datagram_and_validate(ctxt, ipr, p)) {
/* the totally last fragment (flag more fragments = 0) was received at least
* once AND all fragments are received */
ipr->datagram_len += IP_HLEN;
/* save the second pbuf before copying the header over the pointer */
r = ((struct ip_reass_helper*)ipr->p->payload)->next_pbuf;
/* copy the original ip header back to the first pbuf */
fraghdr = (struct ip_hdr*)(ipr->p->payload);
SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
IPH_LEN_SET(fraghdr, htons(ipr->datagram_len));
IPH_OFFSET_SET(fraghdr, 0);
IPH_CHKSUM_SET(fraghdr, 0);
/* @todo: do we need to set calculate the correct checksum? */
IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN));
p = ipr->p;
/* chain together the pbufs contained within the reass_data list. */
while(r != NULL) {
iprh = (struct ip_reass_helper*)r->payload;
/* hide the ip header for every succeding fragment */
pbuf_header(r, -IP_HLEN);
pbuf_cat(p, r);
r = iprh->next_pbuf;
}
/* release the sources allocate for the fragment queue entry */
ip_reass_dequeue_datagram(ctxt, ipr, ipr_prev);
/* and adjust the number of pbufs currently queued for reassembly. */
(((LwipCntxt*)ctxt)->ip_reass_pbufcount) -= pbuf_clen(p);
/* Return the pbuf chain */
return p;
}
/* the datagram is not (yet?) reassembled completely */
LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass_pbufcount: %d out\n", ((LwipCntxt*)ctxt)->ip_reass_pbufcount));
return NULL;
nullreturn:
LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: nullreturn\n"));
IPFRAG_STATS_INC(ip_frag.drop);
pbuf_free(ctxt, p);
return NULL;
}
#endif /* IP_REASSEMBLY */
#if IP_FRAG
#if IP_FRAG_USES_STATIC_BUF
static u8_t buf[LWIP_MEM_ALIGN_SIZE(IP_FRAG_MAX_MTU + MEM_ALIGNMENT - 1)];
#else /* IP_FRAG_USES_STATIC_BUF */
#if !LWIP_NETIF_TX_SINGLE_PBUF
/** Allocate a new struct pbuf_custom_ref */
static struct pbuf_custom_ref*
ip_frag_alloc_pbuf_custom_ref(void* ctxt)
{
return (struct pbuf_custom_ref*)memp_malloc(ctxt, MEMP_FRAG_PBUF);
}
/** Free a struct pbuf_custom_ref */
static void
ip_frag_free_pbuf_custom_ref(void* ctxt, struct pbuf_custom_ref* p)
{
LWIP_ASSERT("p != NULL", p != NULL);
memp_free(ctxt, MEMP_FRAG_PBUF, p);
}
/** Free-callback function to free a 'struct pbuf_custom_ref', called by
* pbuf_free. */
static void
ipfrag_free_pbuf_custom(void* ctxt, struct pbuf *p)
{
struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref*)p;
LWIP_ASSERT("pcr != NULL", pcr != NULL);
LWIP_ASSERT("pcr == p", (void*)pcr == (void*)p);
if (pcr->original != NULL) {
pbuf_free(ctxt, pcr->original);
}
ip_frag_free_pbuf_custom_ref(ctxt, pcr);
}
#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
#endif /* IP_FRAG_USES_STATIC_BUF */
/**
* Fragment an IP datagram if too large for the netif.
*
* Chop the datagram in MTU sized chunks and send them in order
* by using a fixed size static memory buffer (PBUF_REF) or
* point PBUF_REFs into p (depending on IP_FRAG_USES_STATIC_BUF).
*
* @param p ip packet to send
* @param netif the netif on which to send
* @param dest destination ip address to which to send
*
* @return ERR_OK if sent successfully, err_t otherwise
*/
err_t
ip_frag(void* ctxt, struct pbuf *p, struct netif *netif, ip_addr_t *dest)
{
struct pbuf *rambuf;
#if IP_FRAG_USES_STATIC_BUF
struct pbuf *header;
#else
#if !LWIP_NETIF_TX_SINGLE_PBUF
struct pbuf *newpbuf;
#endif
struct ip_hdr *original_iphdr;
#endif
struct ip_hdr *iphdr;
u16_t nfb;
u16_t left, cop;
u16_t mtu = netif->mtu;
u16_t ofo, omf;
u16_t last;
u16_t poff = IP_HLEN;
u16_t tmp;
#if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF
u16_t newpbuflen = 0;
u16_t left_to_copy;
#endif
/* Get a RAM based MTU sized pbuf */
#if IP_FRAG_USES_STATIC_BUF
/* When using a static buffer, we use a PBUF_REF, which we will
* use to reference the packet (without link header).
* Layer and length is irrelevant.
*/
rambuf = pbuf_alloc(ctxt, PBUF_LINK, 0, PBUF_REF);
if (rambuf == NULL) {
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc(PBUF_LINK, 0, PBUF_REF) failed\n"));
return ERR_MEM;
}
rambuf->tot_len = rambuf->len = mtu;
rambuf->payload = LWIP_MEM_ALIGN((void *)buf);
/* Copy the IP header in it */
iphdr = (struct ip_hdr *)rambuf->payload;
SMEMCPY(iphdr, p->payload, IP_HLEN);
#else /* IP_FRAG_USES_STATIC_BUF */
original_iphdr = (struct ip_hdr *)p->payload;
iphdr = original_iphdr;
#endif /* IP_FRAG_USES_STATIC_BUF */
/* Save original offset */
tmp = ntohs(IPH_OFFSET(iphdr));
ofo = tmp & IP_OFFMASK;
omf = tmp & IP_MF;
left = p->tot_len - IP_HLEN;
nfb = (mtu - IP_HLEN) / 8;
while (left) {
last = (left <= mtu - IP_HLEN);
/* Set new offset and MF flag */
tmp = omf | (IP_OFFMASK & (ofo));
if (!last) {
tmp = tmp | IP_MF;
}
/* Fill this fragment */
cop = last ? left : nfb * 8;
#if IP_FRAG_USES_STATIC_BUF
poff += pbuf_copy_partial(p, (u8_t*)iphdr + IP_HLEN, cop, poff);
#else /* IP_FRAG_USES_STATIC_BUF */
#if LWIP_NETIF_TX_SINGLE_PBUF
rambuf = pbuf_alloc(ctxt, PBUF_IP, cop, PBUF_RAM);
if (rambuf == NULL) {
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
poff += pbuf_copy_partial(p, rambuf->payload, cop, poff);
/* make room for the IP header */
if(pbuf_header(rambuf, IP_HLEN)) {
pbuf_free(ctxt, rambuf);
return ERR_MEM;
}
/* fill in the IP header */
SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
iphdr = rambuf->payload;
#else /* LWIP_NETIF_TX_SINGLE_PBUF */
/* When not using a static buffer, create a chain of pbufs.
* The first will be a PBUF_RAM holding the link and IP header.
* The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
* but limited to the size of an mtu.
*/
rambuf = pbuf_alloc(ctxt, PBUF_LINK, IP_HLEN, PBUF_RAM);
if (rambuf == NULL) {
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(p->len >= (IP_HLEN)));
SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
iphdr = (struct ip_hdr *)rambuf->payload;
/* Can just adjust p directly for needed offset. */
p->payload = (u8_t *)p->payload + poff;
p->len -= poff;
left_to_copy = cop;
while (left_to_copy) {
struct pbuf_custom_ref *pcr;
newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
/* Is this pbuf already empty? */
if (!newpbuflen) {
p = p->next;
continue;
}
pcr = ip_frag_alloc_pbuf_custom_ref(ctxt);
if (pcr == NULL) {
pbuf_free(ctxt, rambuf);
return ERR_MEM;
}
/* Mirror this pbuf, although we might not need all of it. */
newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen);
if (newpbuf == NULL) {
ip_frag_free_pbuf_custom_ref(ctxt, pcr);
pbuf_free(ctxt, rambuf);
return ERR_MEM;
}
pbuf_ref(p);
pcr->original = p;
pcr->pc.custom_free_function = ipfrag_free_pbuf_custom;
/* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
* so that it is removed when pbuf_dechain is later called on rambuf.
*/
pbuf_cat(rambuf, newpbuf);
left_to_copy -= newpbuflen;
if (left_to_copy) {
p = p->next;
}
}
poff = newpbuflen;
#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
#endif /* IP_FRAG_USES_STATIC_BUF */
/* Correct header */
IPH_OFFSET_SET(iphdr, htons(tmp));
IPH_LEN_SET(iphdr, htons(cop + IP_HLEN));
IPH_CHKSUM_SET(iphdr, 0);
IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN));
#if IP_FRAG_USES_STATIC_BUF
if (last) {
pbuf_realloc(ctxt, rambuf, left + IP_HLEN);
}
/* This part is ugly: we alloc a RAM based pbuf for
* the link level header for each chunk and then
* free it.A PBUF_ROM style pbuf for which pbuf_header
* worked would make things simpler.
*/
header = pbuf_alloc(ctxt, PBUF_LINK, 0, PBUF_RAM);
if (header != NULL) {
pbuf_chain(header, rambuf);
netif->output(netif, header, dest);
IPFRAG_STATS_INC(ip_frag.xmit);
snmp_inc_ipfragcreates();
pbuf_free(ctxt, header);
} else {
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc() for header failed\n"));
pbuf_free(ctxt, rambuf);
return ERR_MEM;
}
#else /* IP_FRAG_USES_STATIC_BUF */
/* No need for separate header pbuf - we allowed room for it in rambuf
* when allocated.
*/
netif->output(ctxt, netif, rambuf, dest);
IPFRAG_STATS_INC(ip_frag.xmit);
/* Unfortunately we can't reuse rambuf - the hardware may still be
* using the buffer. Instead we free it (and the ensuing chain) and
* recreate it next time round the loop. If we're lucky the hardware
* will have already sent the packet, the free will really free, and
* there will be zero memory penalty.
*/
pbuf_free(ctxt, rambuf);
#endif /* IP_FRAG_USES_STATIC_BUF */
left -= cop;
ofo += nfb;
}
#if IP_FRAG_USES_STATIC_BUF
pbuf_free(ctxt, rambuf);
#endif /* IP_FRAG_USES_STATIC_BUF */
snmp_inc_ipfragoks();
return ERR_OK;
}
#endif /* IP_FRAG */
|
zoranzhao/NoSSim
|
lwip/lwip/src/core/ipv4/ip_frag.c
|
C
|
bsd-3-clause
| 29,580 |
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <machine/segments.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <libgen.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <pthread_np.h>
#include <sysexits.h>
#include <machine/vmm.h>
#include <vmmapi.h>
#include "bhyverun.h"
#include "acpi.h"
#include "inout.h"
#include "dbgport.h"
#include "legacy_irq.h"
#include "mem.h"
#include "mevent.h"
#include "mptbl.h"
#include "pci_emul.h"
#include "pci_lpc.h"
#include "xmsr.h"
#include "ioapic.h"
#include "spinup_ap.h"
#include "rtc.h"
#define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */
#define VMEXIT_SWITCH 0 /* force vcpu switch in mux mode */
#define VMEXIT_CONTINUE 1 /* continue from next instruction */
#define VMEXIT_RESTART 2 /* restart current instruction */
#define VMEXIT_ABORT 3 /* abort the vm run loop */
#define VMEXIT_RESET 4 /* guest machine has reset */
#define MB (1024UL * 1024)
#define GB (1024UL * MB)
typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
char *vmname;
int guest_ncpus;
static int pincpu = -1;
static int guest_vmexit_on_hlt, guest_vmexit_on_pause, disable_x2apic;
static int virtio_msix = 1;
static int foundcpus;
static int strictio;
static int acpi;
static char *progname;
static const int BSP = 0;
static int cpumask;
static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
struct vm_exit vmexit[VM_MAXCPU];
struct bhyvestats {
uint64_t vmexit_bogus;
uint64_t vmexit_bogus_switch;
uint64_t vmexit_hlt;
uint64_t vmexit_pause;
uint64_t vmexit_mtrap;
uint64_t vmexit_inst_emul;
uint64_t cpu_switch_rotate;
uint64_t cpu_switch_direct;
int io_reset;
} stats;
struct mt_vmm_info {
pthread_t mt_thr;
struct vmctx *mt_ctx;
int mt_vcpu;
} mt_vmm_info[VM_MAXCPU];
static void
usage(int code)
{
fprintf(stderr,
"Usage: %s [-aehAHIPW] [-g <gdb port>] [-s <pci>] [-S <pci>]\n"
" %*s [-c vcpus] [-p pincpu] [-m mem] [-l <lpc>] <vm>\n"
" -a: local apic is in XAPIC mode (default is X2APIC)\n"
" -A: create an ACPI table\n"
" -g: gdb port\n"
" -c: # cpus (default 1)\n"
" -p: pin vcpu 'n' to host cpu 'pincpu + n'\n"
" -H: vmexit from the guest on hlt\n"
" -P: vmexit from the guest on pause\n"
" -W: force virtio to use single-vector MSI\n"
" -e: exit on unhandled I/O access\n"
" -h: help\n"
" -s: <slot,driver,configinfo> PCI slot config\n"
" -S: <slot,driver,configinfo> legacy PCI slot config\n"
" -l: LPC device configuration\n"
" -m: memory size in MB\n",
progname, (int)strlen(progname), "");
exit(code);
}
void *
paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
{
return (vm_map_gpa(ctx, gaddr, len));
}
int
fbsdrun_disable_x2apic(void)
{
return (disable_x2apic);
}
int
fbsdrun_vmexit_on_pause(void)
{
return (guest_vmexit_on_pause);
}
int
fbsdrun_vmexit_on_hlt(void)
{
return (guest_vmexit_on_hlt);
}
int
fbsdrun_virtio_msix(void)
{
return (virtio_msix);
}
static void *
fbsdrun_start_thread(void *param)
{
char tname[MAXCOMLEN + 1];
struct mt_vmm_info *mtp;
int vcpu;
mtp = param;
vcpu = mtp->mt_vcpu;
snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
pthread_set_name_np(mtp->mt_thr, tname);
vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
/* not reached */
exit(1);
return (NULL);
}
void
fbsdrun_addcpu(struct vmctx *ctx, int vcpu, uint64_t rip)
{
int error;
if (cpumask & (1 << vcpu)) {
fprintf(stderr, "addcpu: attempting to add existing cpu %d\n",
vcpu);
exit(1);
}
cpumask |= 1 << vcpu;
foundcpus++;
/*
* Set up the vmexit struct to allow execution to start
* at the given RIP
*/
vmexit[vcpu].rip = rip;
vmexit[vcpu].inst_length = 0;
mt_vmm_info[vcpu].mt_ctx = ctx;
mt_vmm_info[vcpu].mt_vcpu = vcpu;
error = pthread_create(&mt_vmm_info[vcpu].mt_thr, NULL,
fbsdrun_start_thread, &mt_vmm_info[vcpu]);
assert(error == 0);
}
static int
vmexit_catch_reset(void)
{
stats.io_reset++;
return (VMEXIT_RESET);
}
static int
vmexit_catch_inout(void)
{
return (VMEXIT_ABORT);
}
static int
vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
uint32_t eax)
{
#if BHYVE_DEBUG
/*
* put guest-driven debug here
*/
#endif
return (VMEXIT_CONTINUE);
}
static int
vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
{
int error;
int bytes, port, in, out;
uint32_t eax;
int vcpu;
vcpu = *pvcpu;
port = vme->u.inout.port;
bytes = vme->u.inout.bytes;
eax = vme->u.inout.eax;
in = vme->u.inout.in;
out = !in;
/* We don't deal with these */
if (vme->u.inout.string || vme->u.inout.rep)
return (VMEXIT_ABORT);
/* Special case of guest reset */
if (out && port == 0x64 && (uint8_t)eax == 0xFE)
return (vmexit_catch_reset());
/* Extra-special case of host notifications */
if (out && port == GUEST_NIO_PORT)
return (vmexit_handle_notify(ctx, vme, pvcpu, eax));
error = emulate_inout(ctx, vcpu, in, port, bytes, &eax, strictio);
if (error == 0 && in)
error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RAX, eax);
if (error == 0)
return (VMEXIT_CONTINUE);
else {
fprintf(stderr, "Unhandled %s%c 0x%04x\n",
in ? "in" : "out",
bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'), port);
return (vmexit_catch_inout());
}
}
static int
vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
{
fprintf(stderr, "vm exit rdmsr 0x%x, cpu %d\n", vme->u.msr.code,
*pvcpu);
return (VMEXIT_ABORT);
}
static int
vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
{
int newcpu;
int retval = VMEXIT_CONTINUE;
newcpu = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code,vme->u.msr.wval);
return (retval);
}
static int
vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
{
int newcpu;
int retval = VMEXIT_CONTINUE;
newcpu = spinup_ap(ctx, *pvcpu,
vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
return (retval);
}
static int
vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
fprintf(stderr, "vm exit[%d]\n", *pvcpu);
fprintf(stderr, "\treason\t\tVMX\n");
fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
fprintf(stderr, "\terror\t\t%d\n", vmexit->u.vmx.error);
fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
fprintf(stderr, "\tqualification\t0x%016lx\n",
vmexit->u.vmx.exit_qualification);
return (VMEXIT_ABORT);
}
static int
vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
stats.vmexit_bogus++;
return (VMEXIT_RESTART);
}
static int
vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
stats.vmexit_hlt++;
/*
* Just continue execution with the next instruction. We use
* the HLT VM exit as a way to be friendly with the host
* scheduler.
*/
return (VMEXIT_CONTINUE);
}
static int
vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
stats.vmexit_pause++;
return (VMEXIT_CONTINUE);
}
static int
vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
stats.vmexit_mtrap++;
return (VMEXIT_RESTART);
}
static int
vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
{
int err;
stats.vmexit_inst_emul++;
err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
&vmexit->u.inst_emul.vie);
if (err) {
if (err == EINVAL) {
fprintf(stderr,
"Failed to emulate instruction at 0x%lx\n",
vmexit->rip);
} else if (err == ESRCH) {
fprintf(stderr, "Unhandled memory access to 0x%lx\n",
vmexit->u.inst_emul.gpa);
}
return (VMEXIT_ABORT);
}
return (VMEXIT_CONTINUE);
}
static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
[VM_EXITCODE_INOUT] = vmexit_inout,
[VM_EXITCODE_VMX] = vmexit_vmx,
[VM_EXITCODE_BOGUS] = vmexit_bogus,
[VM_EXITCODE_RDMSR] = vmexit_rdmsr,
[VM_EXITCODE_WRMSR] = vmexit_wrmsr,
[VM_EXITCODE_MTRAP] = vmexit_mtrap,
[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
};
static void
vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip)
{
cpuset_t mask;
int error, rc, prevcpu;
enum vm_exitcode exitcode;
if (pincpu >= 0) {
CPU_ZERO(&mask);
CPU_SET(pincpu + vcpu, &mask);
error = pthread_setaffinity_np(pthread_self(),
sizeof(mask), &mask);
assert(error == 0);
}
while (1) {
error = vm_run(ctx, vcpu, rip, &vmexit[vcpu]);
if (error != 0) {
/*
* It is possible that 'vmmctl' or some other process
* has transitioned the vcpu to CANNOT_RUN state right
* before we tried to transition it to RUNNING.
*
* This is expected to be temporary so just retry.
*/
if (errno == EBUSY)
continue;
else
break;
}
prevcpu = vcpu;
exitcode = vmexit[vcpu].exitcode;
if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
exitcode);
exit(1);
}
rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
switch (rc) {
case VMEXIT_CONTINUE:
rip = vmexit[vcpu].rip + vmexit[vcpu].inst_length;
break;
case VMEXIT_RESTART:
rip = vmexit[vcpu].rip;
break;
case VMEXIT_RESET:
exit(0);
default:
exit(1);
}
}
fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
}
static int
num_vcpus_allowed(struct vmctx *ctx)
{
int tmp, error;
error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
/*
* The guest is allowed to spinup more than one processor only if the
* UNRESTRICTED_GUEST capability is available.
*/
if (error == 0)
return (VM_MAXCPU);
else
return (1);
}
void
fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
{
int err, tmp;
if (fbsdrun_vmexit_on_hlt()) {
err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
if (err < 0) {
fprintf(stderr, "VM exit on HLT not supported\n");
exit(1);
}
vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
if (cpu == BSP)
handler[VM_EXITCODE_HLT] = vmexit_hlt;
}
if (fbsdrun_vmexit_on_pause()) {
/*
* pause exit support required for this mode
*/
err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
if (err < 0) {
fprintf(stderr,
"SMP mux requested, no pause support\n");
exit(1);
}
vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
if (cpu == BSP)
handler[VM_EXITCODE_PAUSE] = vmexit_pause;
}
if (fbsdrun_disable_x2apic())
err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
else
err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
if (err) {
fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
exit(1);
}
vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
}
int
main(int argc, char *argv[])
{
int c, error, gdb_port, err, bvmcons;
int max_vcpus;
struct vmctx *ctx;
uint64_t rip;
size_t memsize;
bvmcons = 0;
progname = basename(argv[0]);
gdb_port = 0;
guest_ncpus = 1;
memsize = 256 * MB;
while ((c = getopt(argc, argv, "abehAHIPWp:g:c:s:S:m:l:")) != -1) {
switch (c) {
case 'a':
disable_x2apic = 1;
break;
case 'A':
acpi = 1;
break;
case 'b':
bvmcons = 1;
break;
case 'p':
pincpu = atoi(optarg);
break;
case 'c':
guest_ncpus = atoi(optarg);
break;
case 'g':
gdb_port = atoi(optarg);
break;
case 'l':
if (lpc_device_parse(optarg) != 0) {
errx(EX_USAGE, "invalid lpc device "
"configuration '%s'", optarg);
}
break;
case 's':
if (pci_parse_slot(optarg, 0) != 0)
exit(1);
else
break;
case 'S':
if (pci_parse_slot(optarg, 1) != 0)
exit(1);
else
break;
case 'm':
error = vm_parse_memsize(optarg, &memsize);
if (error)
errx(EX_USAGE, "invalid memsize '%s'", optarg);
break;
case 'H':
guest_vmexit_on_hlt = 1;
break;
case 'I':
/*
* The "-I" option was used to add an ioapic to the
* virtual machine.
*
* An ioapic is now provided unconditionally for each
* virtual machine and this option is now deprecated.
*/
break;
case 'P':
guest_vmexit_on_pause = 1;
break;
case 'e':
strictio = 1;
break;
case 'W':
virtio_msix = 0;
break;
case 'h':
usage(0);
default:
usage(1);
}
}
argc -= optind;
argv += optind;
if (argc != 1)
usage(1);
vmname = argv[0];
ctx = vm_open(vmname);
if (ctx == NULL) {
perror("vm_open");
exit(1);
}
max_vcpus = num_vcpus_allowed(ctx);
if (guest_ncpus > max_vcpus) {
fprintf(stderr, "%d vCPUs requested but only %d available\n",
guest_ncpus, max_vcpus);
exit(1);
}
fbsdrun_set_capabilities(ctx, BSP);
err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
if (err) {
fprintf(stderr, "Unable to setup memory (%d)\n", err);
exit(1);
}
init_mem();
init_inout();
legacy_irq_init();
rtc_init(ctx);
/*
* Exit if a device emulation finds an error in it's initilization
*/
if (init_pci(ctx) != 0)
exit(1);
ioapic_init(0);
if (gdb_port != 0)
init_dbgport(gdb_port);
if (bvmcons)
init_bvmcons();
error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
assert(error == 0);
/*
* build the guest tables, MP etc.
*/
mptable_build(ctx, guest_ncpus);
if (acpi) {
error = acpi_build(ctx, guest_ncpus);
assert(error == 0);
}
/*
* Change the proc title to include the VM name.
*/
setproctitle("%s", vmname);
/*
* Add CPU 0
*/
fbsdrun_addcpu(ctx, BSP, rip);
/*
* Head off to the main event dispatch loop
*/
mevent_dispatch();
exit(1);
}
|
jhbsz/OSI-OS
|
usr.sbin/bhyve/bhyverun.c
|
C
|
bsd-3-clause
| 15,294 |
namespace Orchard.Lists.Models
{
public class ListPartSettings
{
public string ContainedContentType { get; set; }
}
}
|
alexbocharov/Orchard2
|
src/Orchard.Web/Modules/Orchard.Lists/Models/ListPartSettings.cs
|
C#
|
bsd-3-clause
| 137 |
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#ifndef XENIA_APU_AUDIO_SYSTEM_H_
#define XENIA_APU_AUDIO_SYSTEM_H_
#include <atomic>
#include <queue>
#include "xenia/base/mutex.h"
#include "xenia/base/threading.h"
#include "xenia/cpu/processor.h"
#include "xenia/kernel/xthread.h"
#include "xenia/memory.h"
#include "xenia/xbox.h"
namespace xe {
namespace apu {
class AudioDriver;
class XmaDecoder;
class AudioSystem {
public:
virtual ~AudioSystem();
Memory* memory() const { return memory_; }
cpu::Processor* processor() const { return processor_; }
XmaDecoder* xma_decoder() const { return xma_decoder_.get(); }
virtual X_STATUS Setup(kernel::KernelState* kernel_state);
virtual void Shutdown();
X_STATUS RegisterClient(uint32_t callback, uint32_t callback_arg,
size_t* out_index);
void UnregisterClient(size_t index);
void SubmitFrame(size_t index, uint32_t samples_ptr);
protected:
explicit AudioSystem(cpu::Processor* processor);
virtual void Initialize();
void WorkerThreadMain();
virtual X_STATUS CreateDriver(size_t index,
xe::threading::Semaphore* semaphore,
AudioDriver** out_driver) = 0;
virtual void DestroyDriver(AudioDriver* driver) = 0;
// TODO(gibbed): respect XAUDIO2_MAX_QUEUED_BUFFERS somehow (ie min(64,
// XAUDIO2_MAX_QUEUED_BUFFERS))
static const size_t kMaximumQueuedFrames = 64;
Memory* memory_ = nullptr;
cpu::Processor* processor_ = nullptr;
std::unique_ptr<XmaDecoder> xma_decoder_;
std::atomic<bool> worker_running_ = {false};
kernel::object_ref<kernel::XHostThread> worker_thread_;
xe::global_critical_region global_critical_region_;
static const size_t kMaximumClientCount = 8;
struct {
AudioDriver* driver;
uint32_t callback;
uint32_t callback_arg;
uint32_t wrapped_callback_arg;
} clients_[kMaximumClientCount];
std::unique_ptr<xe::threading::Semaphore>
client_semaphores_[kMaximumClientCount];
// Event is always there in case we have no clients.
std::unique_ptr<xe::threading::Event> shutdown_event_;
xe::threading::WaitHandle* wait_handles_[kMaximumClientCount + 1];
std::queue<size_t> unused_clients_;
};
} // namespace apu
} // namespace xe
#endif // XENIA_APU_AUDIO_SYSTEM_H_
|
KitoHo/xenia
|
src/xenia/apu/audio_system.h
|
C
|
bsd-3-clause
| 2,754 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>DN_LISTHOTKEY</title>
<meta http-equiv="Content-Type" Content="text/html; charset=Windows-1251">
<link rel="stylesheet" type="text/css" href="../../../styles/styles.css">
<script language="javascript" src='../../links.js' type="text/javascript"></script>
</head>
<body>
<h1>DN_LISTHOTKEY</h1>
<div class=navbar>
<a href="index_dn.html">Ñîáûòèÿ</a> |
<a href="../index.html">Dialog API</a><br>
</div>
<div class=shortdescr>
Ñîîáùåíèå <dfn>DN_LISTHOTKEY</dfn> îïîâåùàåò îáðàáîò÷èê î òîì, ÷òî ïîëüçîâàòåëü
äëÿ ñìåíû ïóíêòà â ñïèñêå (<a href="../controls/di_combobox.html">DI_COMBOBOX</a>, <a href="../controls/di_listbox.html">DI_LISTBOX</a>)
âîñïîëüçîâàëñÿ ãîðÿ÷èìè êëàâèøàìè.
</div>
<h3>Param1</h3>
<div class=descr>
ID ýëåìåíòà <a href="../controls/di_combobox.html">DI_COMBOBOX</a> èëè <a href="../controls/di_listbox.html">DI_LISTBOX</a>.
</div>
<h3>Param2</h3>
<div class=descr>
Ïîçèöèÿ âûáðàííîãî ýëåìåíòà â ñïèñêå.
</div>
<h3>Return</h3>
<div class=descr>
FALSE - ðàçðåøèòü èçìåíåíèå,<br>
TRUE - ïëàãèí ñàì îòðàáîòàë ñîáûòèå.
</div>
<h3>Ýëåìåíòû</h3>
<div class=descr>
<table class="cont">
<tr class="cont"><th class="cont" width="40%">Ýëåìåíò</th><th class="cont" width="60%">Îïèñàíèå</th></tr>
<tr class="cont"><td class="cont" width="40%"><a href="../controls/di_combobox.html">DI_COMBOBOX</a></td>
<td class="cont" width="60%">êîìáèíèðîâàííûé ñïèñîê</td></tr>
<tr class="cont"><td class="cont" width="40%"><a href="../controls/di_listbox.html">DI_LISTBOX</a></td>
<td class="cont" width="60%">ñïèñîê</td></tr>
</table>
</div>
<div class=see>Ñìîòðèòå òàêæå:</div><div class=seecont>
<a href="../dialoginit.html">DialogInit</a><br>
</div>
</body>
</html>
|
data-man/FarAS
|
enc/enc_rus2/meta/dialogapi/dmsg/dn_listhotkey.html
|
HTML
|
bsd-3-clause
| 1,757 |
/*
Copyright 2011 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include <cstdio>
#include <webp/decode.h>
#include "imageio.h"
#include "fmath.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
namespace webp_pvt {
class WebpInput : public ImageInput
{
public:
WebpInput() { init(); }
virtual ~WebpInput() { close(); }
virtual const char* format_name() const { return "webp"; }
virtual bool open (const std::string &name, ImageSpec &spec);
virtual bool read_native_scanline (int y, int z, void *data);
virtual bool close ();
private:
std::string m_filename;
uint8_t *m_decoded_image;
long int m_image_size;
long int m_scanline_size;
FILE *m_file;
void init()
{
m_image_size = m_scanline_size = 0;
m_decoded_image = NULL;
m_file = NULL;
}
};
bool
WebpInput::open (const std::string &name, ImageSpec &spec)
{
m_filename = name;
m_file = fopen(m_filename.c_str(), "rb");
if (!m_file)
{
error ("Could not open file \"%s\"", m_filename.c_str());
return false;
}
fseek (m_file, 0, SEEK_END);
m_image_size = ftell(m_file);
fseek (m_file, 0, SEEK_SET);
std::vector<uint8_t> encoded_image;
encoded_image.resize(m_image_size, 0);
fread(&encoded_image[0], sizeof(uint8_t), encoded_image.size(), m_file);
int width = 0, height = 0;
if(!WebPGetInfo(&encoded_image[0], encoded_image.size(), &width, &height))
{
error ("%s is not a WebP image file", m_filename.c_str());
close();
return false;
}
const int CHANNEL_NUM = 4;
m_scanline_size = width * CHANNEL_NUM;
m_spec = ImageSpec(width, height, CHANNEL_NUM, TypeDesc::UINT8);
spec = m_spec;
if (!(m_decoded_image = WebPDecodeRGBA(&encoded_image[0], encoded_image.size(), &m_spec.width, &m_spec.height)))
{
error ("Couldn't decode %s", m_filename.c_str());
close();
return false;
}
return true;
}
bool
WebpInput::read_native_scanline (int y, int z, void *data)
{
if (y < 0 || y >= m_spec.width) // out of range scanline
return false;
memcpy(data, &m_decoded_image[y*m_scanline_size], m_scanline_size);
return true;
}
bool
WebpInput::close()
{
if (m_file)
{
fclose(m_file);
m_file = NULL;
}
if (m_decoded_image)
{
free(m_decoded_image); // this was allocated by WebPDecodeRGB and should be fread by free
m_decoded_image = NULL;
}
return true;
}
} // namespace webp_pvt
// Obligatory material to make this a recognizeable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
DLLEXPORT int webp_imageio_version = OIIO_PLUGIN_VERSION;
DLLEXPORT ImageInput *webp_input_imageio_create () {
return new webp_pvt::WebpInput;
}
DLLEXPORT const char *webp_input_extensions[] = {
"webp", NULL
};
OIIO_PLUGIN_EXPORTS_END
OIIO_PLUGIN_NAMESPACE_END
|
jeremyselan/oiio
|
src/webp.imageio/webpinput.cpp
|
C++
|
bsd-3-clause
| 4,469 |
// AUTOMATICALLY GENERATED BY MIDDLECRAFT
/* Allows plugins to access server functions without needing to link the actual server Jar. */
package net.minecraft.server;
public abstract class EntityList {
// FIELDS
private static java.util.Map field_849;
private static java.util.Map field_848;
private static java.util.Map field_851;
private static java.util.Map field_850;
// METHODS
}
|
N3X15/MiddleCraft
|
src-interface/net/minecraft/server/EntityList.java
|
Java
|
bsd-3-clause
| 395 |
import numpy as np
from numpy.testing import *
import unittest
from conformalmapping import *
class TestCircle(unittest.TestCase):
def test_invalid(self):
with self.assertRaises(Exception):
c = Circle(center = 0.0 + 0.0j, radius = -1)
def test_boundbox(self):
c = Circle(center = 0.0 + 0.0j, radius = 1.0)
box = c.boundbox()
# by inspection three decimal place seems ok
assert_allclose(box, np.array([-1.0, 1.0, -1.0, 1.0]), 3)
def test_fromVector(self):
c = Circle.from_vector([1.0, 1.0j, -1.0])
self.assertAlmostEqual(c.radius, 1.0)
self.assertAlmostEqual(c.center, 0.0 + 0.0j)
def test_circlestr(self):
c = Circle.from_vector([1.0, 1.0j, -1.0])
str(c)
c = Circle.from_vector([1.0, 1.0j, np.inf])
str(c)
def test_circlerepr(self):
c = Circle.from_vector([1.0, 1.0j, -1.0])
repr(c)
c = Circle.from_vector([1.0, 1.0j, np.inf])
repr(c)
def test_dist(self):
c = Circle(center = 0.0 + 0.0j, radius = 1.0)
self.assertAlmostEqual(c.dist(-3.0), 2.0)
self.assertAlmostEqual(c.dist(-2.0), 1.0)
self.assertAlmostEqual(c.dist(2.0), 1.0)
self.assertAlmostEqual(c.dist(3.0), 2.0)
self.assertAlmostEqual(c.dist(-3.0j), 2.0)
self.assertAlmostEqual(c.dist(-2.0j), 1.0)
self.assertAlmostEqual(c.dist(2.0j), 1.0)
self.assertAlmostEqual(c.dist(3.0j), 2.0)
def test_isinside(self):
c = Circle.from_vector([1.0, 1.0j, -1.0])
# clearly inside
for iv in [0.5, -0.5, 0.5j, -0.5j]:
self.assertEqual(True, c.isinside(iv))
# clearly outside
for ov in [2.0, -2.0, 2.0j, -2.0j]:
self.assertEqual(False, c.isinside(ov))
def test_threePointCheck(self):
c = Circle.from_points(0, 5, 7j)
def test_zlineCheck(self):
z1 = Circle.from_points(0, 1, np.inf)
self.assertEqual(True, np.isinf(z1.radius) )
self.assertEqual(z1.isinf(), True)
self.assertEqual(True, z1.isinside(1j))
self.assertEqual(False, z1.isinside(-1j))
if __name__ == '__main__':
unittest.begin()
|
AndrewWalker/cmtoolkit
|
tests/test_circle.py
|
Python
|
bsd-3-clause
| 2,207 |
#ifndef XGBOOST_LEARNER_LEARNER_INL_HPP_
#define XGBOOST_LEARNER_LEARNER_INL_HPP_
/*!
* \file learner-inl.hpp
* \brief learning algorithm
* \author Tianqi Chen
*/
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <limits>
#include "../sync/sync.h"
#include "../utils/io.h"
#include "./objective.h"
#include "./evaluation.h"
#include "../gbm/gbm.h"
namespace xgboost {
/*! \brief namespace for learning algorithm */
namespace learner {
/*!
* \brief learner that takes do gradient boosting on specific objective functions
* and do training and prediction
*/
class BoostLearner : public rabit::Serializable {
public:
BoostLearner(void) {
obj_ = NULL;
gbm_ = NULL;
name_obj_ = "reg:linear";
name_gbm_ = "gbtree";
silent= 0;
prob_buffer_row = 1.0f;
distributed_mode = 0;
pred_buffer_size = 0;
seed_per_iteration = 0;
seed = 0;
save_base64 = 0;
}
virtual ~BoostLearner(void) {
if (obj_ != NULL) delete obj_;
if (gbm_ != NULL) delete gbm_;
}
/*!
* \brief add internal cache space for mat, this can speedup prediction for matrix,
* please cache prediction for training and eval data
* warning: if the model is loaded from file from some previous training history
* set cache data must be called with exactly SAME
* data matrices to continue training otherwise it will cause error
* \param mats array of pointers to matrix whose prediction result need to be cached
*/
inline void SetCacheData(const std::vector<DMatrix*>& mats) {
utils::Assert(cache_.size() == 0, "can only call cache data once");
// assign buffer index
size_t buffer_size = 0;
for (size_t i = 0; i < mats.size(); ++i) {
bool dupilicate = false;
for (size_t j = 0; j < i; ++j) {
if (mats[i] == mats[j]) dupilicate = true;
}
if (dupilicate) continue;
// set mats[i]'s cache learner pointer to this
mats[i]->cache_learner_ptr_ = this;
cache_.push_back(CacheEntry(mats[i], buffer_size, mats[i]->info.num_row()));
buffer_size += mats[i]->info.num_row();
}
char str_temp[25];
utils::SPrintf(str_temp, sizeof(str_temp), "%lu",
static_cast<unsigned long>(buffer_size));
this->SetParam("num_pbuffer", str_temp);
this->pred_buffer_size = buffer_size;
}
/*!
* \brief set parameters from outside
* \param name name of the parameter
* \param val value of the parameter
*/
inline void SetParam(const char *name, const char *val) {
using namespace std;
// in this version, bst: prefix is no longer required
if (strncmp(name, "bst:", 4) != 0) {
std::string n = "bst:"; n += name;
this->SetParam(n.c_str(), val);
}
if (!strcmp(name, "silent")) silent = atoi(val);
if (!strcmp(name, "dsplit")) {
if (!strcmp(val, "col")) {
this->SetParam("updater", "distcol");
distributed_mode = 1;
} else if (!strcmp(val, "row")) {
this->SetParam("updater", "grow_histmaker,prune");
distributed_mode = 2;
} else {
utils::Error("%s is invalid value for dsplit, should be row or col", val);
}
}
if (!strcmp(name, "prob_buffer_row")) {
prob_buffer_row = static_cast<float>(atof(val));
utils::Check(distributed_mode == 0,
"prob_buffer_row can only be used in single node mode so far");
this->SetParam("updater", "grow_colmaker,refresh,prune");
}
if (!strcmp(name, "eval_metric")) evaluator_.AddEval(val);
if (!strcmp("seed", name)) {
seed = atoi(val); random::Seed(seed);
}
if (!strcmp("seed_per_iter", name)) seed_per_iteration = atoi(val);
if (!strcmp("save_base64", name)) save_base64 = atoi(val);
if (!strcmp(name, "num_class")) {
this->SetParam("num_output_group", val);
}
if (!strcmp(name, "nthread")) {
omp_set_num_threads(atoi(val));
}
if (gbm_ == NULL) {
if (!strcmp(name, "objective")) name_obj_ = val;
if (!strcmp(name, "booster")) name_gbm_ = val;
mparam.SetParam(name, val);
}
if (gbm_ != NULL) gbm_->SetParam(name, val);
if (obj_ != NULL) obj_->SetParam(name, val);
if (gbm_ == NULL || obj_ == NULL) {
cfg_.push_back(std::make_pair(std::string(name), std::string(val)));
}
}
// this is an internal function
// initialize the trainer, called at InitModel and LoadModel
inline void InitTrainer(bool calc_num_feature = true) {
if (calc_num_feature) {
// estimate feature bound
unsigned num_feature = 0;
for (size_t i = 0; i < cache_.size(); ++i) {
num_feature = std::max(num_feature,
static_cast<unsigned>(cache_[i].mat_->info.num_col()));
}
// run allreduce on num_feature to find the maximum value
rabit::Allreduce<rabit::op::Max>(&num_feature, 1);
if (num_feature > mparam.num_feature) mparam.num_feature = num_feature;
}
char str_temp[25];
utils::SPrintf(str_temp, sizeof(str_temp), "%d", mparam.num_feature);
this->SetParam("bst:num_feature", str_temp);
}
/*!
* \brief initialize the model
*/
inline void InitModel(void) {
this->InitTrainer();
// initialize model
this->InitObjGBM();
// reset the base score
mparam.base_score = obj_->ProbToMargin(mparam.base_score);
// initialize GBM model
gbm_->InitModel();
}
/*!
* \brief load model from stream
* \param fi input stream
* \param calc_num_feature whether call InitTrainer with calc_num_feature
*/
inline void LoadModel(utils::IStream &fi,
bool calc_num_feature = true) {
utils::Check(fi.Read(&mparam, sizeof(ModelParam)) != 0,
"BoostLearner: wrong model format");
{
// backward compatibility code for compatible with old model type
// for new model, Read(&name_obj_) is suffice
uint64_t len;
utils::Check(fi.Read(&len, sizeof(len)) != 0, "BoostLearner: wrong model format");
if (len >= std::numeric_limits<unsigned>::max()) {
int gap;
utils::Check(fi.Read(&gap, sizeof(gap)) != 0, "BoostLearner: wrong model format");
len = len >> static_cast<uint64_t>(32UL);
}
if (len != 0) {
name_obj_.resize(len);
utils::Check(fi.Read(&name_obj_[0], len) != 0, "BoostLearner: wrong model format");
}
}
utils::Check(fi.Read(&name_gbm_), "BoostLearner: wrong model format");
// delete existing gbm if any
if (obj_ != NULL) delete obj_;
if (gbm_ != NULL) delete gbm_;
this->InitTrainer(calc_num_feature);
this->InitObjGBM();
char tmp[32];
utils::SPrintf(tmp, sizeof(tmp), "%u", mparam.num_class);
obj_->SetParam("num_class", tmp);
gbm_->LoadModel(fi, mparam.saved_with_pbuffer != 0);
if (mparam.saved_with_pbuffer == 0) {
gbm_->ResetPredBuffer(pred_buffer_size);
}
}
// rabit load model from rabit checkpoint
virtual void Load(rabit::Stream *fi) {
// for row split, we should not keep pbuffer
this->LoadModel(*fi, false);
}
// rabit save model to rabit checkpoint
virtual void Save(rabit::Stream *fo) const {
// for row split, we should not keep pbuffer
this->SaveModel(*fo, distributed_mode != 2);
}
/*!
* \brief load model from file
* \param fname file name
*/
inline void LoadModel(const char *fname) {
utils::IStream *fi = utils::IStream::Create(fname, "r");
std::string header; header.resize(4);
// check header for different binary encode
// can be base64 or binary
utils::Check(fi->Read(&header[0], 4) != 0, "invalid model");
// base64 format
if (header == "bs64") {
utils::Base64InStream bsin(fi);
bsin.InitPosition();
this->LoadModel(bsin, true);
} else if (header == "binf") {
this->LoadModel(*fi, true);
} else {
delete fi;
fi = utils::IStream::Create(fname, "r");
this->LoadModel(*fi, true);
}
delete fi;
}
inline void SaveModel(utils::IStream &fo, bool with_pbuffer) const {
ModelParam p = mparam;
p.saved_with_pbuffer = static_cast<int>(with_pbuffer);
fo.Write(&p, sizeof(ModelParam));
fo.Write(name_obj_);
fo.Write(name_gbm_);
gbm_->SaveModel(fo, with_pbuffer);
}
/*!
* \brief save model into file
* \param fname file name
* \param with_pbuffer whether save pbuffer together
*/
inline void SaveModel(const char *fname, bool with_pbuffer) const {
utils::IStream *fo = utils::IStream::Create(fname, "w");
if (save_base64 != 0 || !strcmp(fname, "stdout")) {
fo->Write("bs64\t", 5);
utils::Base64OutStream bout(fo);
this->SaveModel(bout, with_pbuffer);
bout.Finish('\n');
} else {
fo->Write("binf", 4);
this->SaveModel(*fo, with_pbuffer);
}
delete fo;
}
/*!
* \brief check if data matrix is ready to be used by training,
* if not intialize it
* \param p_train pointer to the matrix used by training
*/
inline void CheckInit(DMatrix *p_train) {
int ncol = static_cast<int>(p_train->info.info.num_col);
std::vector<bool> enabled(ncol, true);
// initialize column access
p_train->fmat()->InitColAccess(enabled, prob_buffer_row);
const int kMagicPage = 0xffffab02;
// check, if it is DMatrixPage, then use hist maker
if (p_train->magic == kMagicPage) {
this->SetParam("updater", "grow_histmaker,prune");
}
}
/*!
* \brief update the model for one iteration
* \param iter current iteration number
* \param p_train pointer to the data matrix
*/
inline void UpdateOneIter(int iter, const DMatrix &train) {
if (seed_per_iteration != 0 || rabit::IsDistributed()) {
random::Seed(this->seed * kRandSeedMagic + iter);
}
this->PredictRaw(train, &preds_);
obj_->GetGradient(preds_, train.info, iter, &gpair_);
gbm_->DoBoost(train.fmat(), this->FindBufferOffset(train), train.info.info, &gpair_);
}
/*!
* \brief whether model allow lazy checkpoint
*/
inline bool AllowLazyCheckPoint(void) const {
return gbm_->AllowLazyCheckPoint();
}
/*!
* \brief evaluate the model for specific iteration
* \param iter iteration number
* \param evals datas i want to evaluate
* \param evname name of each dataset
* \return a string corresponding to the evaluation result
*/
inline std::string EvalOneIter(int iter,
const std::vector<const DMatrix*> &evals,
const std::vector<std::string> &evname) {
std::string res;
char tmp[256];
utils::SPrintf(tmp, sizeof(tmp), "[%d]", iter);
res = tmp;
for (size_t i = 0; i < evals.size(); ++i) {
this->PredictRaw(*evals[i], &preds_);
obj_->EvalTransform(&preds_);
res += evaluator_.Eval(evname[i].c_str(), preds_, evals[i]->info, distributed_mode == 2);
}
return res;
}
/*!
* \brief simple evaluation function, with a specified metric
* \param data input data
* \param metric name of metric
* \return a pair of <evaluation name, result>
*/
std::pair<std::string, float> Evaluate(const DMatrix &data, std::string metric) {
if (metric == "auto") metric = obj_->DefaultEvalMetric();
IEvaluator *ev = CreateEvaluator(metric.c_str());
this->PredictRaw(data, &preds_);
obj_->EvalTransform(&preds_);
float res = ev->Eval(preds_, data.info);
delete ev;
return std::make_pair(metric, res);
}
/*!
* \brief get prediction
* \param data input data
* \param output_margin whether to only predict margin value instead of transformed prediction
* \param out_preds output vector that stores the prediction
* \param ntree_limit limit number of trees used for boosted tree
* predictor, when it equals 0, this means we are using all the trees
*/
inline void Predict(const DMatrix &data,
bool output_margin,
std::vector<float> *out_preds,
unsigned ntree_limit = 0,
bool pred_leaf = false
) const {
if (pred_leaf) {
gbm_->PredictLeaf(data.fmat(), data.info.info, out_preds, ntree_limit);
} else {
this->PredictRaw(data, out_preds, ntree_limit);
if (!output_margin) {
obj_->PredTransform(out_preds);
}
}
}
/*!
* \brief online prediction funciton, predict score for one instance at a time
* NOTE: use the batch prediction interface if possible, batch prediction is usually
* more efficient than online prediction
* This function is NOT threadsafe, make sure you only call from one thread
*
* \param inst the instance you want to predict
* \param output_margin whether to only predict margin value instead of transformed prediction
* \param out_preds output vector to hold the predictions
* \param ntree_limit limit the number of trees used in prediction
* \param root_index the root index
* \sa Predict
*/
inline void Predict(const SparseBatch::Inst &inst,
bool output_margin,
std::vector<float> *out_preds,
unsigned ntree_limit = 0) const {
gbm_->Predict(inst, out_preds, ntree_limit);
if (out_preds->size() == 1) {
(*out_preds)[0] += mparam.base_score;
}
if (!output_margin) {
obj_->PredTransform(out_preds);
}
}
/*! \brief dump model out */
inline std::vector<std::string> DumpModel(const utils::FeatMap& fmap, int option) {
return gbm_->DumpModel(fmap, option);
}
protected:
/*!
* \brief initialize the objective function and GBM,
* if not yet done
*/
inline void InitObjGBM(void) {
if (obj_ != NULL) return;
utils::Assert(gbm_ == NULL, "GBM and obj should be NULL");
obj_ = CreateObjFunction(name_obj_.c_str());
gbm_ = gbm::CreateGradBooster(name_gbm_.c_str());
this->InitAdditionDefaultParam();
// set parameters
for (size_t i = 0; i < cfg_.size(); ++i) {
obj_->SetParam(cfg_[i].first.c_str(), cfg_[i].second.c_str());
gbm_->SetParam(cfg_[i].first.c_str(), cfg_[i].second.c_str());
}
if (evaluator_.Size() == 0) {
evaluator_.AddEval(obj_->DefaultEvalMetric());
}
}
/*!
* \brief additional default value for specific objs
*/
inline void InitAdditionDefaultParam(void) {
if (name_obj_ == "count:poisson") {
obj_->SetParam("max_delta_step", "0.7");
gbm_->SetParam("max_delta_step", "0.7");
}
}
/*!
* \brief get un-transformed prediction
* \param data training data matrix
* \param out_preds output vector that stores the prediction
* \param ntree_limit limit number of trees used for boosted tree
* predictor, when it equals 0, this means we are using all the trees
*/
inline void PredictRaw(const DMatrix &data,
std::vector<float> *out_preds,
unsigned ntree_limit = 0) const {
gbm_->Predict(data.fmat(), this->FindBufferOffset(data),
data.info.info, out_preds, ntree_limit);
// add base margin
std::vector<float> &preds = *out_preds;
const bst_omp_uint ndata = static_cast<bst_omp_uint>(preds.size());
if (data.info.base_margin.size() != 0) {
utils::Check(preds.size() == data.info.base_margin.size(),
"base_margin.size does not match with prediction size");
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
preds[j] += data.info.base_margin[j];
}
} else {
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
preds[j] += mparam.base_score;
}
}
}
/*! \brief training parameter for regression */
struct ModelParam{
/* \brief global bias */
float base_score;
/* \brief number of features */
unsigned num_feature;
/* \brief number of class, if it is multi-class classification */
int num_class;
/*! \brief whether the model itself is saved with pbuffer */
int saved_with_pbuffer;
/*! \brief reserved field */
int reserved[30];
/*! \brief constructor */
ModelParam(void) {
std::memset(this, 0, sizeof(ModelParam));
base_score = 0.5f;
num_feature = 0;
num_class = 0;
saved_with_pbuffer = 0;
}
/*!
* \brief set parameters from outside
* \param name name of the parameter
* \param val value of the parameter
*/
inline void SetParam(const char *name, const char *val) {
using namespace std;
if (!strcmp("base_score", name)) base_score = static_cast<float>(atof(val));
if (!strcmp("num_class", name)) num_class = atoi(val);
if (!strcmp("bst:num_feature", name)) num_feature = atoi(val);
}
};
// data fields
// stored random seed
int seed;
// whether seed the PRNG each iteration
// this is important for restart from existing iterations
// default set to no, but will auto switch on in distributed mode
int seed_per_iteration;
// save model in base64 encoding
int save_base64;
// silent during training
int silent;
// distributed learning mode, if any, 0:none, 1:col, 2:row
int distributed_mode;
// cached size of predict buffer
size_t pred_buffer_size;
// maximum buffred row value
float prob_buffer_row;
// evaluation set
EvalSet evaluator_;
// model parameter
ModelParam mparam;
// gbm model that back everything
gbm::IGradBooster *gbm_;
// name of gbm model used for training
std::string name_gbm_;
// objective fnction
IObjFunction *obj_;
// name of objective function
std::string name_obj_;
// configurations
std::vector< std::pair<std::string, std::string> > cfg_;
// temporal storages for prediciton
std::vector<float> preds_;
// gradient pairs
std::vector<bst_gpair> gpair_;
protected:
// magic number to transform random seed
const static int kRandSeedMagic = 127;
// cache entry object that helps handle feature caching
struct CacheEntry {
const DMatrix *mat_;
size_t buffer_offset_;
size_t num_row_;
CacheEntry(const DMatrix *mat, size_t buffer_offset, size_t num_row)
:mat_(mat), buffer_offset_(buffer_offset), num_row_(num_row) {}
};
// find internal bufer offset for certain matrix, if not exist, return -1
inline int64_t FindBufferOffset(const DMatrix &mat) const {
for (size_t i = 0; i < cache_.size(); ++i) {
if (cache_[i].mat_ == &mat && mat.cache_learner_ptr_ == this) {
if (cache_[i].num_row_ == mat.info.num_row()) {
return static_cast<int64_t>(cache_[i].buffer_offset_);
}
}
}
return -1;
}
// data structure field
/*! \brief the entries indicates that we have internal prediction cache */
std::vector<CacheEntry> cache_;
};
} // namespace learner
} // namespace xgboost
#endif // XGBOOST_LEARNER_LEARNER_INL_HPP_
|
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
|
python-packages/xgboost-0.40/src/learner/learner-inl.hpp
|
C++
|
bsd-3-clause
| 19,052 |
/**
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* src/refocus/sampleGenerator.js
*/
const Joi = require('joi');
module.exports = Joi.object().keys({
name: Joi.string().regex(/^[a-zA-Z0-9-]+$/).required(),
description: Joi.string(),
tags: Joi.array().items(Joi.string()),
generatorTemplate: Joi.object().keys({
name: Joi.string().regex(/^[a-z0-9-]+$/).required(),
version: Joi.string().required(),
}),
aspects: Joi.array().min(1).items(Joi.string()).required(),
subjects: Joi.array().min(1).items(Joi.string()),
subjectQuery: Joi.string(),
context: Joi.object(),
}).xor('subjects', 'subjectQuery');
|
iamigo/refocus-schemas
|
src/refocus/sampleGenerator.js
|
JavaScript
|
bsd-3-clause
| 819 |
module Main where
import Foundation
import MougiIwasa (runMougiIwasa)
main :: IO ()
main = runMougiIwasa
|
ttoe/diffeq-hs
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 108 |
#!/usr/bin/python
import requests
import sys
import os.path
import time
status=0
url='http://192.168.200.3:8080/motech-platform-server/module/mds/rest/alertsmodule/alert'
Critical_Count = 0
High_Count = 0
Medium_Count = 0
Low_Count = 0
File='/tmp/AllmotechAlert.csv'
Header="DATE TIME"+","+"id"+","+"priority"+","+"alertType"+","+"name"+","+"description"
#Procedure to request motech URL
def request_alerts(page=None):
params = None
if page:
params = {'page': page}
r = requests.get(url, params=params, auth=('motech', 'motech@123'))
if r.status_code != 200:
status=2
if page:
print "Error while accesing MOTECH ALERTS at page %d with error %d" % (page, p.status_code)
else:
print "Error while accessing MOTECH ALERTS %d" % r.status_code
sys.exit(status)
else:
return r
#remove motechalert.csv from /tmp if exists
if ( os.path.exists(File) ):
os.remove(File)
r = request_alerts()
#Fetch the Total pages
#Check Response code
data = r.json()
#Calculate the Total Pages which needs to be analayzed
if (data['metadata']['totalCount'] > 0):
status=2
f = open(File,'a+')
f.write(Header)
f.write('\n')
pageCount=data['metadata']['totalCount']/data['metadata']['pageSize']
reminder=data['metadata']['totalCount']%data['metadata']['pageSize']
#Add one more page if TotalAlerts is not in multiple of pagesize
if reminder > 0:
pageCount = pageCount + 1
for index in range(1,pageCount+1):
#Fetch Records page wise starting page 1
p = request_alerts(index)
pr = p.json()
#Update the loopcount as per the number of alerts in the page
if (index == pageCount and reminder > 0):
loopCount = reminder
else:
loopCount= pr['metadata']['pageSize']
for count in range(0,loopCount):
if ((pr['data'][count]['status']) =='NEW'):
if ((pr['data'][count]['alertType']) =='CRITICAL'):
Critical_Count = Critical_Count + 1
if ((pr['data'][count]['alertType']) =='HIGH'):
High_Count = High_Count + 1
if ((pr['data'][count]['alertType']) =='MEDIUM'):
Medium_Count = Medium_Count + 1
if ((pr['data'][count]['alertType']) =='LOW'):
Low_Count = Low_Count + 1
datetime=time.strftime('%d-%b-%y %H:%M:%S', time.localtime((pr['data'][count]['creationDate'])/1000))
alert=datetime+","+str((pr['data'][count]['id']))+","+str((pr['data'][count]['priority']))+","+str((pr['data'][count]['alertType']))+","+str((pr['data'][count]['name']))+","+str((pr['data'][count]['description']))
f.write(alert)
f.write('\n')
f.close()
print "There are total %d New Alerts out of which ::CRITICAL:%d, HIGH:%d, MEDIUM:%d and LOW:%d" %(data['metadata']['totalCount'],Critical_Count,High_Count,Medium_Count,Low_Count)
else:
status=0;
print"No Alerts in system"
sys.exit(status)
|
motech-implementations/nms-deployment
|
nagios/MotechHealth/libexec/motechAlertParser.py
|
Python
|
bsd-3-clause
| 2,910 |
/*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.test.integrated;
/**
* @author Rhett Sutphin
*/
public interface SchemaInitializer {
void oneTimeSetup(ConnectionSource connectionSource);
void beforeAll(ConnectionSource connectionSource);
void beforeEach(ConnectionSource connectionSource);
void afterEach(ConnectionSource connectionSource);
void afterAll(ConnectionSource connectionSource);
}
|
NCIP/psc
|
test/infrastructure/src/main/java/edu/northwestern/bioinformatics/studycalendar/test/integrated/SchemaInitializer.java
|
Java
|
bsd-3-clause
| 592 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/media_stream_devices_controller.h"
#include "base/metrics/histogram.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/media/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/media_permission.h"
#include "chrome/browser/media/media_stream_capture_indicator.h"
#include "chrome/browser/media/media_stream_device_permissions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/media_stream_request.h"
#include "content/public/common/origin_util.h"
#include "extensions/common/constants.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_ANDROID)
#include "chrome/browser/android/preferences/pref_service_bridge.h"
#include "content/public/browser/android/content_view_core.h"
#include "ui/android/window_android.h"
#endif // OS_ANDROID
using content::BrowserThread;
namespace {
enum DevicePermissionActions {
kAllowHttps = 0,
kAllowHttp,
kDeny,
kCancel,
kPermissionActionsMax // Must always be last!
};
// Returns true if the given ContentSettingsType is being requested in
// |request|.
bool ContentTypeIsRequested(ContentSettingsType type,
const content::MediaStreamRequest& request) {
if (request.request_type == content::MEDIA_OPEN_DEVICE)
return true;
if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC)
return request.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE;
if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA)
return request.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE;
return false;
}
} // namespace
MediaStreamDevicesController::MediaStreamDevicesController(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback)
: web_contents_(web_contents),
request_(request),
callback_(callback) {
profile_ = Profile::FromBrowserContext(web_contents->GetBrowserContext());
content_settings_ = TabSpecificContentSettings::FromWebContents(web_contents);
content::MediaStreamRequestResult denial_reason = content::MEDIA_DEVICE_OK;
old_audio_setting_ = GetContentSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
request_, &denial_reason);
old_video_setting_ = GetContentSetting(
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, request_, &denial_reason);
// If either setting is ask, we show the infobar.
if (old_audio_setting_ == CONTENT_SETTING_ASK ||
old_video_setting_ == CONTENT_SETTING_ASK) {
return;
}
// Otherwise we can run the callback immediately.
RunCallback(old_audio_setting_, old_video_setting_, denial_reason);
}
MediaStreamDevicesController::~MediaStreamDevicesController() {
if (!callback_.is_null()) {
callback_.Run(content::MediaStreamDevices(),
content::MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
scoped_ptr<content::MediaStreamUI>());
}
}
// static
void MediaStreamDevicesController::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
prefs->RegisterBooleanPref(prefs::kVideoCaptureAllowed, true);
prefs->RegisterBooleanPref(prefs::kAudioCaptureAllowed, true);
prefs->RegisterListPref(prefs::kVideoCaptureAllowedUrls);
prefs->RegisterListPref(prefs::kAudioCaptureAllowedUrls);
}
bool MediaStreamDevicesController::IsAskingForAudio() const {
return old_audio_setting_ == CONTENT_SETTING_ASK;
}
bool MediaStreamDevicesController::IsAskingForVideo() const {
return old_video_setting_ == CONTENT_SETTING_ASK;
}
const std::string& MediaStreamDevicesController::GetSecurityOriginSpec() const {
return request_.security_origin.spec();
}
int MediaStreamDevicesController::GetIconID() const {
if (IsAskingForVideo())
return IDR_INFOBAR_MEDIA_STREAM_CAMERA;
return IDR_INFOBAR_MEDIA_STREAM_MIC;
}
base::string16 MediaStreamDevicesController::GetMessageText() const {
int message_id = IDS_MEDIA_CAPTURE_AUDIO_AND_VIDEO;
if (!IsAskingForAudio())
message_id = IDS_MEDIA_CAPTURE_VIDEO_ONLY;
else if (!IsAskingForVideo())
message_id = IDS_MEDIA_CAPTURE_AUDIO_ONLY;
return l10n_util::GetStringFUTF16(
message_id, base::UTF8ToUTF16(GetSecurityOriginSpec()));
}
base::string16 MediaStreamDevicesController::GetMessageTextFragment() const {
int message_id = IDS_MEDIA_CAPTURE_AUDIO_AND_VIDEO_PERMISSION_FRAGMENT;
if (!IsAskingForAudio())
message_id = IDS_MEDIA_CAPTURE_VIDEO_ONLY_PERMISSION_FRAGMENT;
else if (!IsAskingForVideo())
message_id = IDS_MEDIA_CAPTURE_AUDIO_ONLY_PERMISSION_FRAGMENT;
return l10n_util::GetStringUTF16(message_id);
}
bool MediaStreamDevicesController::HasUserGesture() const {
return request_.user_gesture;
}
GURL MediaStreamDevicesController::GetRequestingHostname() const {
return request_.security_origin;
}
void MediaStreamDevicesController::PermissionGranted() {
GURL origin(GetSecurityOriginSpec());
if (content::IsOriginSecure(origin)) {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kAllowHttps, kPermissionActionsMax);
} else {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kAllowHttp, kPermissionActionsMax);
}
RunCallback(GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
old_audio_setting_, CONTENT_SETTING_ALLOW),
GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
old_video_setting_, CONTENT_SETTING_ALLOW),
content::MEDIA_DEVICE_PERMISSION_DENIED);
}
void MediaStreamDevicesController::PermissionGranted(ContentSetting content_setting) {
GURL origin(GetSecurityOriginSpec());
if (content::IsOriginSecure(origin)) {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kAllowHttps, kPermissionActionsMax);
} else {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kAllowHttp, kPermissionActionsMax);
}
switch (content_setting) {
case CONTENT_SETTING_ALLOW:
RunCallback(GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
old_audio_setting_, CONTENT_SETTING_ALLOW),
GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
old_video_setting_, CONTENT_SETTING_ALLOW),
content::MEDIA_DEVICE_PERMISSION_DENIED);
break;
case CONTENT_SETTING_ALLOW_24H:
RunCallback(GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
old_audio_setting_, CONTENT_SETTING_ALLOW_24H),
GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
old_video_setting_, CONTENT_SETTING_ALLOW_24H),
content::MEDIA_DEVICE_PERMISSION_DENIED);
break;
case CONTENT_SETTING_SESSION_ONLY:
RunCallback(GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
old_audio_setting_, CONTENT_SETTING_SESSION_ONLY),
GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
old_video_setting_, CONTENT_SETTING_SESSION_ONLY),
content::MEDIA_DEVICE_PERMISSION_DENIED);
break;
default:
break;
}
}
void MediaStreamDevicesController::PermissionDenied() {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kDeny, kPermissionActionsMax);
RunCallback(GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
old_audio_setting_, CONTENT_SETTING_BLOCK),
GetNewSetting(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
old_video_setting_, CONTENT_SETTING_BLOCK),
content::MEDIA_DEVICE_PERMISSION_DENIED);
}
void MediaStreamDevicesController::Cancelled() {
UMA_HISTOGRAM_ENUMERATION("Media.DevicePermissionActions",
kCancel, kPermissionActionsMax);
RunCallback(old_audio_setting_, old_video_setting_,
content::MEDIA_DEVICE_PERMISSION_DISMISSED);
}
void MediaStreamDevicesController::RequestFinished() {
delete this;
}
content::MediaStreamDevices MediaStreamDevicesController::GetDevices(
ContentSetting audio_setting,
ContentSetting video_setting) {
bool audio_allowed = IsPermissionAllowed(audio_setting);
bool video_allowed = IsPermissionAllowed(video_setting);
if (!audio_allowed && !video_allowed)
return content::MediaStreamDevices();
content::MediaStreamDevices devices;
switch (request_.request_type) {
case content::MEDIA_OPEN_DEVICE: {
const content::MediaStreamDevice* device = NULL;
// For open device request, when requested device_id is empty, pick
// the first available of the given type. If requested device_id is
// not empty, return the desired device if it's available. Otherwise,
// return no device.
if (audio_allowed &&
request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) {
DCHECK_EQ(content::MEDIA_NO_SERVICE, request_.video_type);
if (!request_.requested_audio_device_id.empty()) {
device =
MediaCaptureDevicesDispatcher::GetInstance()
->GetRequestedAudioDevice(request_.requested_audio_device_id);
} else {
device = MediaCaptureDevicesDispatcher::GetInstance()
->GetFirstAvailableAudioDevice();
}
} else if (video_allowed &&
request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) {
DCHECK_EQ(content::MEDIA_NO_SERVICE, request_.audio_type);
// Pepper API opens only one device at a time.
if (!request_.requested_video_device_id.empty()) {
device =
MediaCaptureDevicesDispatcher::GetInstance()
->GetRequestedVideoDevice(request_.requested_video_device_id);
} else {
device = MediaCaptureDevicesDispatcher::GetInstance()
->GetFirstAvailableVideoDevice();
}
}
if (device)
devices.push_back(*device);
break;
}
case content::MEDIA_GENERATE_STREAM: {
bool get_default_audio_device = audio_allowed;
bool get_default_video_device = video_allowed;
// Get the exact audio or video device if an id is specified.
if (audio_allowed && !request_.requested_audio_device_id.empty()) {
const content::MediaStreamDevice* audio_device =
MediaCaptureDevicesDispatcher::GetInstance()
->GetRequestedAudioDevice(request_.requested_audio_device_id);
if (audio_device) {
devices.push_back(*audio_device);
get_default_audio_device = false;
}
}
if (video_allowed && !request_.requested_video_device_id.empty()) {
const content::MediaStreamDevice* video_device =
MediaCaptureDevicesDispatcher::GetInstance()
->GetRequestedVideoDevice(request_.requested_video_device_id);
if (video_device) {
devices.push_back(*video_device);
get_default_video_device = false;
}
}
// If either or both audio and video devices were requested but not
// specified by id, get the default devices.
if (get_default_audio_device || get_default_video_device) {
MediaCaptureDevicesDispatcher::GetInstance()
->GetDefaultDevicesForProfile(profile_, get_default_audio_device,
get_default_video_device, &devices);
}
break;
}
case content::MEDIA_DEVICE_ACCESS: {
// Get the default devices for the request.
MediaCaptureDevicesDispatcher::GetInstance()->GetDefaultDevicesForProfile(
profile_, audio_allowed, video_allowed, &devices);
break;
}
case content::MEDIA_ENUMERATE_DEVICES: {
// Do nothing.
NOTREACHED();
break;
}
} // switch
if (audio_allowed) {
profile_->GetHostContentSettingsMap()->UpdateLastUsageByPattern(
ContentSettingsPattern::FromURLNoWildcard(request_.security_origin),
ContentSettingsPattern::Wildcard(),
CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
}
if (video_allowed) {
profile_->GetHostContentSettingsMap()->UpdateLastUsageByPattern(
ContentSettingsPattern::FromURLNoWildcard(request_.security_origin),
ContentSettingsPattern::Wildcard(),
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
}
return devices;
}
void MediaStreamDevicesController::RunCallback(
ContentSetting audio_setting,
ContentSetting video_setting,
content::MediaStreamRequestResult denial_reason) {
StorePermission(audio_setting, video_setting);
UpdateTabSpecificContentSettings(audio_setting, video_setting);
content::MediaStreamDevices devices =
GetDevices(audio_setting, video_setting);
// If either audio or video are allowed then the callback should report
// success, otherwise we report |denial_reason|.
content::MediaStreamRequestResult request_result = content::MEDIA_DEVICE_OK;
if (audio_setting == CONTENT_SETTING_BLOCK &&
video_setting == CONTENT_SETTING_BLOCK) {
DCHECK_NE(content::MEDIA_DEVICE_OK, denial_reason);
request_result = denial_reason;
} else if (devices.empty()) {
// Even if one of the content settings was allowed, if there are no devices
// at this point we still report a failure.
request_result = content::MEDIA_DEVICE_NO_HARDWARE;
}
scoped_ptr<content::MediaStreamUI> ui;
if (!devices.empty()) {
ui = MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator()
->RegisterMediaStream(web_contents_, devices);
}
content::MediaResponseCallback cb = callback_;
callback_.Reset();
cb.Run(devices, request_result, ui.Pass());
}
void MediaStreamDevicesController::StorePermission(
ContentSetting new_audio_setting,
ContentSetting new_video_setting) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ContentSettingsPattern primary_pattern =
ContentSettingsPattern::FromURLNoWildcard(request_.security_origin);
if (IsAskingForAudio() && new_audio_setting != CONTENT_SETTING_ASK) {
if (ShouldPersistContentSetting(new_audio_setting, request_.security_origin,
request_.request_type)) {
profile_->GetHostContentSettingsMap()->SetContentSetting(
primary_pattern, primary_pattern,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, std::string(),
new_audio_setting);
}
}
if (IsAskingForVideo() && new_video_setting != CONTENT_SETTING_ASK) {
if (ShouldPersistContentSetting(new_video_setting, request_.security_origin,
request_.request_type)) {
profile_->GetHostContentSettingsMap()->SetContentSetting(
primary_pattern, primary_pattern,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, std::string(),
new_video_setting);
}
}
}
void MediaStreamDevicesController::UpdateTabSpecificContentSettings(
ContentSetting audio_setting,
ContentSetting video_setting) const {
if (!content_settings_)
return;
TabSpecificContentSettings::MicrophoneCameraState microphone_camera_state =
TabSpecificContentSettings::MICROPHONE_CAMERA_NOT_ACCESSED;
std::string selected_audio_device;
std::string selected_video_device;
std::string requested_audio_device = request_.requested_audio_device_id;
std::string requested_video_device = request_.requested_video_device_id;
// TODO(raymes): Why do we use the defaults here for the selected devices?
// Shouldn't we just use the devices that were actually selected?
PrefService* prefs = Profile::FromBrowserContext(
web_contents_->GetBrowserContext())->GetPrefs();
if (audio_setting != CONTENT_SETTING_DEFAULT) {
selected_audio_device =
requested_audio_device.empty()
? prefs->GetString(prefs::kDefaultAudioCaptureDevice)
: requested_audio_device;
microphone_camera_state |=
TabSpecificContentSettings::MICROPHONE_ACCESSED |
(audio_setting == CONTENT_SETTING_ALLOW
? 0
: TabSpecificContentSettings::MICROPHONE_BLOCKED);
}
if (video_setting != CONTENT_SETTING_DEFAULT) {
selected_video_device =
requested_video_device.empty()
? prefs->GetString(prefs::kDefaultVideoCaptureDevice)
: requested_video_device;
microphone_camera_state |=
TabSpecificContentSettings::CAMERA_ACCESSED |
(video_setting == CONTENT_SETTING_ALLOW
? 0
: TabSpecificContentSettings::CAMERA_BLOCKED);
}
content_settings_->OnMediaStreamPermissionSet(
request_.security_origin, microphone_camera_state, selected_audio_device,
selected_video_device, requested_audio_device, requested_video_device);
}
ContentSetting MediaStreamDevicesController::GetContentSetting(
ContentSettingsType content_type,
const content::MediaStreamRequest& request,
content::MediaStreamRequestResult* denial_reason) const {
DCHECK(content_type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC ||
content_type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
std::string requested_device_id;
if (content_type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC)
requested_device_id = request.requested_audio_device_id;
else if (content_type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA)
requested_device_id = request.requested_video_device_id;
if (!IsUserAcceptAllowed(content_type)) {
*denial_reason = content::MEDIA_DEVICE_PERMISSION_DENIED;
return CONTENT_SETTING_BLOCK;
}
if (ContentTypeIsRequested(content_type, request)) {
MediaPermission permission(content_type, request.request_type,
request.security_origin, profile_);
return permission.GetPermissionStatusWithDeviceRequired(requested_device_id,
denial_reason);
}
// Return the default content setting if the device is not requested.
return CONTENT_SETTING_DEFAULT;
}
ContentSetting MediaStreamDevicesController::GetNewSetting(
ContentSettingsType content_type,
ContentSetting old_setting,
ContentSetting user_decision) const {
DCHECK(user_decision == CONTENT_SETTING_ALLOW ||
user_decision == CONTENT_SETTING_BLOCK ||
user_decision == CONTENT_SETTING_ALLOW_24H ||
user_decision == CONTENT_SETTING_SESSION_ONLY);
ContentSetting result = old_setting;
if (old_setting == CONTENT_SETTING_ASK) {
if (user_decision == CONTENT_SETTING_ALLOW &&
IsUserAcceptAllowed(content_type)) {
result = CONTENT_SETTING_ALLOW;
} else if (user_decision == CONTENT_SETTING_ALLOW_24H &&
IsUserAcceptAllowed(content_type)) {
result = CONTENT_SETTING_ALLOW_24H;
} else if (user_decision == CONTENT_SETTING_SESSION_ONLY &&
IsUserAcceptAllowed(content_type)) {
result = CONTENT_SETTING_SESSION_ONLY;
} else if (user_decision == CONTENT_SETTING_BLOCK) {
result = CONTENT_SETTING_BLOCK;
}
}
return result;
}
bool MediaStreamDevicesController::IsUserAcceptAllowed(
ContentSettingsType content_type) const {
#if defined(OS_ANDROID)
content::ContentViewCore* cvc =
content::ContentViewCore::FromWebContents(web_contents_);
if (!cvc)
return false;
ui::WindowAndroid* window_android = cvc->GetWindowAndroid();
if (!window_android)
return false;
std::string android_permission =
PrefServiceBridge::GetAndroidPermissionForContentSetting(content_type);
bool android_permission_blocked = false;
if (!android_permission.empty()) {
android_permission_blocked =
!window_android->HasPermission(android_permission) &&
!window_android->CanRequestPermission(android_permission);
}
if (android_permission_blocked)
return false;
// Don't approve device requests if the tab was hidden.
// TODO(qinmin): Add a test for this. http://crbug.com/396869.
// TODO(raymes): Shouldn't this apply to all permissions not just audio/video?
return web_contents_->GetRenderWidgetHostView()->IsShowing();
#endif
return true;
}
bool MediaStreamDevicesController::IsPermissionAllowed(
ContentSetting content_setting) {
if (content_setting == CONTENT_SETTING_ALLOW ||
content_setting == CONTENT_SETTING_ALLOW_24H ||
content_setting == CONTENT_SETTING_SESSION_ONLY) {
return true;
} else {
return false;
}
}
|
vadimtk/chrome4sdp
|
chrome/browser/media/media_stream_devices_controller.cc
|
C++
|
bsd-3-clause
| 21,467 |
{% extends 'forum/base.html' %}
{% load forum_extras %}
{% load i18n %}
{% block content %}
<div id="profile" class="block2col">
{% include 'forum/profile/profile_menu.html' %}
<div class="blockform">
<h2><span>{{ profile.username }} - {% trans "Personal" %}</span></h2>
<div class="box">
<form id="profile2" method="post">
{% csrf_token %}
<div class="inform">
<fieldset>
<legend>{% trans "Enter your personal details" %}</legend>
<div class="infldset">
{{ form.name.errors }}
<label>{{ form.name.label }}<br>{{ form.name }}<br></label>
{% if request.user.is_superuser %}
{{ form.status.errros }}
<label>{{ form.status.label }} (<em>{% trans "Leave blank to use forum default." %}</em>)<br>{{ form.status }}<br></label>
{% endif %}
{{ form.location.errors }}
<label>{{ form.location.label }}<br>{{ form.location }}<br></label>
{{ form.site.errors }}
<label>{{ form.site.label }}<br>{{ form.site }}<br></label>
{{ form.birthday.errors }}
<label>{{ form.birthday.label }}<br>{{ form.birthday }}<br></label>
</div>
</fieldset>
</div>
<p><input name="update" value="{% trans "Submit" %}" type="submit">{% trans "When you update your profile, you will be redirected back to this page." %}</p>
</form>
</div>
</div>
<div class="clearer"></div>
</div>
{% endblock %}
{% block controls %}
{% endblock %}
|
jokey2k/ShockGsite
|
djangobb_forum/templates/forum/profile/profile_personal.html
|
HTML
|
bsd-3-clause
| 1,457 |
<?php
Yii::setAlias('@tests', dirname(__DIR__) . '/tests');
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
return [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'gii'],
'controllerNamespace' => 'app\commands',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];
|
danilomeneghel/prova_reserva_salas
|
config/console.php
|
PHP
|
bsd-3-clause
| 671 |
$(function(){
var logoPosition = 0;
var logos = [-8,-115,-222,-323,-431,-540,-647,-754,-866,-970,-1079,-1184,-1288,-1400,-1512,-1618,-1726]
$('#logo').click(function(e){
e.preventDefault();
logoPosition ++;
if(logoPosition == 14){
logoPosition = 0;
};
$(this).css(
{'background-position': '-80px '+logos[logoPosition].toString()+'px'}
);
});
});
|
blorenz/indie-film-rentals
|
static/initial/js/diapo.js
|
JavaScript
|
bsd-3-clause
| 368 |
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from sentry.models import (
Activity, Group, GroupResolution, GroupResolutionStatus, GroupStatus,
Release
)
from sentry.tasks.clear_expired_resolutions import clear_expired_resolutions
from sentry.testutils import TestCase
class ClearExpiredResolutionsTest(TestCase):
def test_task_persistent_name(self):
assert clear_expired_resolutions.name == 'sentry.tasks.clear_expired_resolutions'
def test_simple(self):
project = self.create_project()
old_release = Release.objects.create(
project=project,
organization_id=project.organization_id,
version='a',
)
old_release.add_project(project)
group1 = self.create_group(
project=project,
status=GroupStatus.RESOLVED,
active_at=timezone.now(),
)
resolution1 = GroupResolution.objects.create(
group=group1,
release=old_release,
)
activity1 = Activity.objects.create(
group=group1,
project=project,
type=Activity.SET_RESOLVED_IN_RELEASE,
ident=resolution1.id,
data={'version': ''},
)
new_release = Release.objects.create(
project=project,
organization_id=project.organization_id,
version='b',
date_added=timezone.now() + timedelta(minutes=1),
)
new_release.add_project(project)
group2 = self.create_group(
status=GroupStatus.UNRESOLVED,
active_at=timezone.now(),
)
resolution2 = GroupResolution.objects.create(
group=group2,
release=new_release,
)
activity2 = Activity.objects.create(
group=group2,
project=project,
type=Activity.SET_RESOLVED_IN_RELEASE,
ident=resolution2.id,
data={'version': ''},
)
clear_expired_resolutions(new_release.id)
assert Group.objects.get(
id=group1.id,
).status == GroupStatus.RESOLVED
assert Group.objects.get(
id=group2.id,
).status == GroupStatus.UNRESOLVED
# rows should not get removed as it breaks regression behavior
resolution1 = GroupResolution.objects.get(id=resolution1.id)
assert resolution1.status == GroupResolutionStatus.RESOLVED
resolution2 = GroupResolution.objects.get(id=resolution2.id)
assert resolution2.status == GroupResolutionStatus.PENDING
activity1 = Activity.objects.get(id=activity1.id)
assert activity1.data['version'] == new_release.version
activity2 = Activity.objects.get(id=activity2.id)
assert activity2.data['version'] == ''
|
zenefits/sentry
|
tests/sentry/tasks/test_clear_expired_resolutions.py
|
Python
|
bsd-3-clause
| 2,874 |
<?php
namespace app\modules\authclient\clients;
class Twitter extends \yii\authclient\clients\Twitter
{
}
|
roman444uk/adverts
|
modules/authclient/clients/Twitter.php
|
PHP
|
bsd-3-clause
| 108 |
package org.cagrid.gme.domain;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Lob;
@Embeddable
public class XMLSchemaDocument {
// TODO: I would like for this to be non nullable, but then hibernate makes
// it a primary key, which doesn't work when it is an unbounded size CLOB
// @Column(nullable = false)
@Lob
@Column(length=16777215)
private java.lang.String schemaText;
// TODO: is there a way to check unique=true within the containing schema?
// right now if you pass the same system id into the set, one will replace
// the other
@Column(nullable = false)
private java.lang.String systemID;
public XMLSchemaDocument() {
}
public XMLSchemaDocument(String schemaText, String systemID) {
super();
this.schemaText = schemaText;
this.systemID = systemID;
}
public java.lang.String getSchemaText() {
return schemaText;
}
public void setSchemaText(java.lang.String schemaText) {
this.schemaText = schemaText;
}
public java.lang.String getSystemID() {
return systemID;
}
public void setSystemID(java.lang.String systemID) {
this.systemID = systemID;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((systemID == null) ? 0 : systemID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final XMLSchemaDocument other = (XMLSchemaDocument) obj;
if (systemID == null) {
if (other.getSystemID() != null)
return false;
} else if (!systemID.equals(other.getSystemID()))
return false;
return true;
}
}
|
NCIP/cagrid
|
cagrid/Software/core/caGrid/projects/globalModelExchange/domain/src/org/cagrid/gme/domain/XMLSchemaDocument.java
|
Java
|
bsd-3-clause
| 2,066 |
<?php
return array(
'service_manager' => array(
'factories' => array(
'service-email' => '\Toemaar\Email\EmailServiceFactory',
),
),
'service-email' => array(
'transport' => 'smtp', //Set Transport options: Sendmail, Smtp, File
'smtp' => array(
// Config options can be found here: http://framework.zend.com/manual/current/en/modules/zend.mail.smtp.options.html
'name' => '',
'host' => '',
),
'file' => array(
// Config options can be found here: http://framework.zend.com/manual/current/en/modules/zend.mail.file.options.html
'path' => 'data/mail/',
'callback' => function (FileTransport $transport) {
return 'Message_' . microtime(true) . '_' . mt_rand() . '.txt';
},
),
),
);
|
gutopia/toemaar-service-email
|
src/config/module.config.php
|
PHP
|
bsd-3-clause
| 916 |
<?php
namespace RcmAdmin\Controller;
use Rcm\Entity\Site;
use Rcm\Http\Response;
use Rcm\View\Model\ApiJsonModel;
use RcmAdmin\Entity\SitePageApiResponse;
use RcmAdmin\InputFilter\SitePageCreateInputFilter;
use RcmAdmin\InputFilter\SitePageUpdateInputFilter;
/**
* Class ApiAdminSitePageController
*
* PHP version 5
*
* @category Reliv
* @package RcmAdmin\Controller
* @author James Jervis <[email protected]>
* @copyright 2014 Reliv International
* @license License.txt New BSD License
* @version Release: <package_version>
* @link https://github.com/reliv
*/
class ApiAdminSitePageController extends ApiAdminBaseController
{
/**
* getPageRepo
*
* @return \Rcm\Repository\Page
*/
protected function getPageRepo()
{
return $this->getEntityManager()->getRepository('\Rcm\Entity\Page');
}
/**
* getSiteRepo
*
* @return \Rcm\Repository\Site
*/
protected function getSiteRepo()
{
return $this->getEntityManager()->getRepository('\Rcm\Entity\Site');
}
/**
* getSite
*
* @param $siteId
*
* @return \Rcm\Entity\Site|null
*/
protected function getSite($siteId)
{
try {
$site = $this->getSiteRepo()->findOneBy(['siteId' => $siteId]);
} catch (\Exception $e) {
$site = null;
}
return $site;
}
/**
* getSite
*
* @param Site $site
*
* @return \Rcm\Entity\Page|null
*/
protected function getPage(Site $site, $pageId)
{
try {
$page = $this->getPageRepo()->findOneBy(
[
'site' => $site,
'pageId' => $pageId
]
);
} catch (\Exception $e) {
$page = null;
}
return $page;
}
/**
* hasPage
*
* @param Site $site
* @param string $pageName
* @param string $pageType
*
* @return bool
*/
protected function hasPage(
$site,
$pageName,
$pageType
) {
try {
$page = $this->getPageRepo()->getPageByName(
$site,
$pageName,
$pageType
);
} catch (\Exception $e) {
$page = null;
}
return !empty($page);
}
/**
* getRequestSiteId
*
* @return mixed
*/
protected function getRequestSiteId()
{
$siteId = $this->getEvent()
->getRouteMatch()
->getParam(
'siteId',
'current'
);
if ($siteId == 'current') {
$siteId = $this->getCurrentSite()->getSiteId();
}
return (int) $siteId;
}
/**
* getList
*
* @return mixed|ApiJsonModel
*/
public function getList()
{
//ACCESS CHECK
if (!$this->rcmIsAllowed(
'sites',
'admin'
)
) {
$this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
return $this->getResponse();
}
$siteId = $this->getRequestSiteId();
$site = $this->getSite($siteId);
if (empty($site)) {
return new ApiJsonModel(
null,
1,
"Site was not found with id {$siteId}."
);
}
$pages = $site->getPages();
foreach ($pages as $key => $value) {
$apiResponse = new SitePageApiResponse();
$apiResponse->populate($value->toArray());
$pages[$key] = $apiResponse;
}
return new ApiJsonModel(
$pages,
0,
'Success'
);
}
/**\
* get
*
* @param mixed $id
*
* @return mixed|ApiJsonModel|\Zend\Stdlib\ResponseInterface
*/
public function get($id)
{
//ACCESS CHECK
if (!$this->rcmIsAllowed('sites', 'admin')) {
$this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
return $this->getResponse();
}
$siteId = $this->getRequestSiteId();
$site = $this->getSite($siteId);
if (empty($site)) {
return new ApiJsonModel(
null,
1,
"Site was not found with id {$siteId}."
);
}
$page = $this->getPage($site, $id);
if (empty($page)) {
return new ApiJsonModel(
null,
404,
"Page was not found with id {$id}."
);
}
$apiResponse = new SitePageApiResponse();
$apiResponse->populate($page->toArray());
return new ApiJsonModel($apiResponse, 0, 'Success');
}
/**
* update
*
* @todo Needs input filter and data prepare for site and exception message needs scrubbed
*
* @param mixed $id
* @param mixed $data
*
* @return mixed|ApiJsonModel|\Zend\Stdlib\ResponseInterface
*/
public function update($id, $data)
{
//ACCESS CHECK
if (!$this->rcmIsAllowed('sites', 'admin')) {
$this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
return $this->getResponse();
}
$inputFilter = new SitePageUpdateInputFilter();
$inputFilter->setData($data);
if (!$inputFilter->isValid()) {
return new ApiJsonModel(
[],
1,
'Some values are missing or invalid for page update.',
$inputFilter->getMessages()
);
}
$data = $inputFilter->getValues();
$siteId = $this->getRequestSiteId();
$site = $this->getSite($siteId);
if (empty($site)) {
return new ApiJsonModel(
null,
1,
"Site was not found with id {$siteId}."
);
}
$page = $this->getPage($site, $id);
try {
$this->getPageRepo()->updatePage(
$page,
$data
);
} catch (\Exception $e) {
return new ApiJsonModel(
null,
1,
$e->getMessage()
);
}
$apiResponse = new SitePageApiResponse();
$apiResponse->populate($page->toArray());
return new ApiJsonModel($apiResponse, 0, 'Success: Page updated.');
}
/**
* create
*
* @param mixed $data
*
* @return mixed|ApiJsonModel|\Zend\Stdlib\ResponseInterface
*/
public function create($data)
{
//ACCESS CHECK
if (!$this->rcmIsAllowed('sites', 'admin')) {
$this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
return $this->getResponse();
}
$siteId = $this->getRequestSiteId();
$site = $this->getSite($siteId);
if (empty($site)) {
return new ApiJsonModel(
null,
1,
"Site was not found with id {$siteId}."
);
}
// // //
$inputFilter = new SitePageCreateInputFilter();
$inputFilter->setData($data);
if (!$inputFilter->isValid()) {
return new ApiJsonModel(
[],
1,
'Some values are missing or invalid for page creation.',
$inputFilter->getMessages()
);
}
$data = $inputFilter->getValues();
if ($this->hasPage($site, $data['name'], $data['pageType'])) {
return new ApiJsonModel(
null,
1,
'Page already exists, duplicates cannot be created'
);
}
$data['author'] = $this->getCurrentAuthor();
try {
$page = $this->getPageRepo()->createPage(
$site,
$data
);
} catch (\Exception $e) {
return new ApiJsonModel(
null,
1,
$e->getMessage()
);
}
$apiResponse = new SitePageApiResponse();
$apiResponse->populate($page->toArray());
return new ApiJsonModel($apiResponse, 0, 'Success: Page created');
}
}
|
bjanish/rcm-admin
|
src/Controller/ApiAdminSitePageController.php
|
PHP
|
bsd-3-clause
| 8,394 |
<?php
namespace app\modules\user\models;
use yii\base\Model;
use Yii;
/**
* Signup form
*/
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public $verifyCode;
public $role;
public $active = 'performer';
/**
* @inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'match', 'pattern' => '#^[\w_-]+$#i'],
['username', 'unique', 'targetClass' => User::className(), 'message' => Yii::t('app', 'ERROR_USERNAME_EXISTS')],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => User::className(), 'message' => Yii::t('app', 'ERROR_EMAIL_EXISTS')],
['password', 'required'],
['password', 'string', 'min' => 6],
['verifyCode', 'captcha', 'captchaAction' => '/user/default/captcha'],
['role', 'string'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'username' => Yii::t('app', 'USER_USERNAME'),
'email' => Yii::t('app', 'USER_EMAIL'),
'password' => Yii::t('app', 'USER_PASSWORD'),
'verifyCode' => Yii::t('app', 'USER_VERIFY_CODE'),
'role' => Yii::t('app', 'USER_ROLE'),
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->status = User::STATUS_WAIT;
$user->generateAuthKey();
$user->generateEmailConfirmToken();
$user->role = $this->role;
$auth = Yii::$app->authManager;
$authRole = $auth->getRole($this->role);
if ($user->save()) {
$auth->assign($authRole, $user->getId());
Yii::$app->mailer->compose('confirmEmail', ['user' => $user])
->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])
->setTo($this->email)
->setSubject('Email confirmation for ' . Yii::$app->name)
->send();
}
return $user;
}
return null;
}
}
|
kdes70/base-pro.lok
|
modules/user/models/SignupForm.php
|
PHP
|
bsd-3-clause
| 2,660 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\assets;
use yii\web\AssetBundle;
/**
* @author Qiang Xue <[email protected]>
* @since 2.0
*/
class LightboxAsset extends AssetBundle
{
public $sourcePath = '@bower';
public $baseUrl = '@web';
public $css = [
'lightbox2/css/lightbox.css'
];
public $js = [
'lightbox2/js/lightbox.js'
];
public $depends = [
];
}
|
affka/tonar24
|
assets/LightboxAsset.php
|
PHP
|
bsd-3-clause
| 531 |
/**
*
*/
package edu.kit.iti.formal.pse.worthwhile.interpreter;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Statement;
/**
* The Class DivisionByZeroInterpreterError.
*/
public class DivisionByZeroInterpreterError extends StatementInterpreterError {
/**
* Sets the name of the error as it appears in the UI.
*
* @param statement
* the statement which produced the error
*/
public DivisionByZeroInterpreterError(final Statement statement) {
super(statement, "Division by zero");
}
}
|
team-worthwhile/worthwhile
|
implementierung/src/worthwhile.interpreter/src/edu/kit/iti/formal/pse/worthwhile/interpreter/DivisionByZeroInterpreterError.java
|
Java
|
bsd-3-clause
| 523 |
// Generated on 2015-07-07 using generator-nodejs 2.1.0
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
complexity: {
generic: {
src: ['app/**/*.js'],
options: {
errorsOnly: false,
cyclometric: 6, // default is 3
halstead: 16, // default is 8
maintainability: 100 // default is 100
}
}
},
jshint: {
all: [
'Gruntfile.js',
'app/**/*.js',
'test/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
watch: {
js: {
files: ['**/*.js', '!node_modules/**/*.js'],
tasks: ['default'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-complexity');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.registerTask('test', ['complexity', 'jshint', 'mochacli', 'watch']);
grunt.registerTask('ci', ['complexity', 'jshint', 'mochacli']);
grunt.registerTask('default', ['test']);
};
|
savelee/ladysignapis
|
libs/trakt-help/Gruntfile.js
|
JavaScript
|
bsd-3-clause
| 1,275 |
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBlurMask.h"
#include "SkCanvas.h"
#include "SkColorFilter.h"
#include "SkLayerDrawLooper.h"
#include "SkMaskFilter.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkRRect.h"
#include "SkString.h"
// This GM mimics a blurred RR seen in the wild.
class BlurRoundRectGM : public skiagm::GM {
public:
BlurRoundRectGM(int width, int height)
: fName("blurroundrect"), fWidth(width), fHeight(height) {
fName.appendf("-WH-%ix%i-unevenCorners", width, height);
}
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(fWidth, fHeight);
}
void onOnceBeforeDraw() override {
SkVector radii[4];
radii[0].set(SkIntToScalar(30), SkIntToScalar(30));
radii[1].set(SkIntToScalar(10), SkIntToScalar(10));
radii[2].set(SkIntToScalar(30), SkIntToScalar(30));
radii[3].set(SkIntToScalar(10), SkIntToScalar(10));
SkRect r = SkRect::MakeWH(SkIntToScalar(fWidth), SkIntToScalar(fHeight));
fRRect.setRectRadii(r, radii);
}
void onDraw(SkCanvas* canvas) override {
SkLayerDrawLooper::Builder looperBuilder;
{
SkLayerDrawLooper::LayerInfo info;
info.fPaintBits = SkLayerDrawLooper::kMaskFilter_Bit
| SkLayerDrawLooper::kColorFilter_Bit;
info.fColorMode = SkBlendMode::kSrc;
info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0));
info.fPostTranslate = false;
SkPaint* paint = looperBuilder.addLayerOnTop(info);
paint->setMaskFilter(SkMaskFilter::MakeBlur(
kNormal_SkBlurStyle,
SkBlurMask::ConvertRadiusToSigma(SK_ScalarHalf)));
paint->setColorFilter(SkColorFilters::Blend(SK_ColorLTGRAY, SkBlendMode::kSrcIn));
paint->setColor(SK_ColorGRAY);
}
{
SkLayerDrawLooper::LayerInfo info;
looperBuilder.addLayerOnTop(info);
}
SkPaint paint;
canvas->drawRect(fRRect.rect(), paint);
paint.setLooper(looperBuilder.detach());
paint.setColor(SK_ColorCYAN);
paint.setAntiAlias(true);
canvas->drawRRect(fRRect, paint);
}
private:
SkString fName;
SkRRect fRRect;
int fWidth, fHeight;
typedef skiagm::GM INHERITED;
};
#include "SkGradientShader.h"
/*
* Spits out a dummy gradient to test blur with shader on paint
*/
static sk_sp<SkShader> MakeRadial() {
SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) }
};
SkTileMode tm = SkTileMode::kClamp;
const SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, };
const SkScalar pos[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
SkMatrix scale;
scale.setScale(0.5f, 0.5f);
scale.postTranslate(5.f, 5.f);
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::MakeTwoPointConical(center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
colors, pos, SK_ARRAY_COUNT(colors), tm,
0, &scale);
}
// Simpler blurred RR test cases where all the radii are the same.
class SimpleBlurRoundRectGM : public skiagm::GM {
public:
SimpleBlurRoundRectGM()
: fName("simpleblurroundrect") {
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(1000, 500);
}
void onDraw(SkCanvas* canvas) override {
canvas->scale(1.5f, 1.5f);
canvas->translate(50,50);
const float blurRadii[] = { 1,5,10,20 };
const int cornerRadii[] = { 1,5,10,20 };
const SkRect r = SkRect::MakeWH(SkIntToScalar(25), SkIntToScalar(25));
for (size_t i = 0; i < SK_ARRAY_COUNT(blurRadii); ++i) {
SkAutoCanvasRestore autoRestore(canvas, true);
canvas->translate(0, (r.height() + SkIntToScalar(50)) * i);
for (size_t j = 0; j < SK_ARRAY_COUNT(cornerRadii); ++j) {
for (int k = 0; k <= 1; k++) {
SkPaint paint;
paint.setColor(SK_ColorBLACK);
paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle,
SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(blurRadii[i]))));
bool useRadial = SkToBool(k);
if (useRadial) {
paint.setShader(MakeRadial());
}
SkRRect rrect;
rrect.setRectXY(r, SkIntToScalar(cornerRadii[j]),
SkIntToScalar(cornerRadii[j]));
canvas->drawRRect(rrect, paint);
canvas->translate(r.width() + SkIntToScalar(50), 0);
}
}
}
}
private:
const SkString fName;
typedef skiagm::GM INHERITED;
};
// Create one with dimensions/rounded corners based on the skp
//
// TODO(scroggo): Disabled in an attempt to rememdy
// https://code.google.com/p/skia/issues/detail?id=1801 ('Win7 Test bots all failing GenerateGMs:
// ran wrong number of tests')
//DEF_GM(return new BlurRoundRectGM(600, 5514, 6);)
// Rounded rect with two opposite corners with large radii, the other two
// small.
DEF_GM(return new BlurRoundRectGM(100, 100);)
DEF_GM(return new SimpleBlurRoundRectGM();)
|
rubenvb/skia
|
gm/blurroundrect.cpp
|
C++
|
bsd-3-clause
| 6,023 |
class ErrorsMixin:
"""Test for errors in corner case situations
"""
async def test_bad_authentication(self):
request = await self.client.get(
self.api_url('user'),
headers=[('Authorization', 'bjchdbjshbcjd')]
)
self.json(request.response, 400)
|
quantmind/lux
|
tests/auth/errors.py
|
Python
|
bsd-3-clause
| 306 |
Installation
------------
Python 3.6 or later is required.
A recent Jenkins is required.
Hudson may be supported, but it is not longer tested.
1. The easy way:
Install python-devel (required by the psutil dependency of the script_api)
E.g on fedora:
sudo dnf install python-devel
pip install --user -U .
To uninstall:
pip uninstall jenkinsflow
Read the file demo/demo_security.py if you have security enabled your Jenkins.
Jenkinsflow uses it's own specialized 'jenkins_api' python module to access Jenkins, using the Jenkins rest api.
2. Manually:
2.1. Install dependencies:
pip install requests click atomicfile
optional: pip install tenjin (if you want to use the template based job loader)
2.2. Install dependencies for experimental features:
To use the experimental script api:
Install python-devel (see above)
pip install psutil setproctitle
To use the experimental visualisation feature:
pip install bottle
2.3. Read the file demo/demo_security.py for notes about security, if you have enabled security on your Jenkins
2.4. All set! You can now create jobs that have a shell execution step, which will a use this library to control the running of other jobs.
See the demo directory for example flows. The demo jobs can be loaded by running tests, see below.
Note: I think jenkinsflow should work on Windows, but it has not been tested.
I'm SURE the test/run.py script will fail on Windows. There are a few Linux/Unix bits in the test setup. Check test/framework/config.py and
test/tmp_install.sh. Patches are welcome:)
Test
----
0. The mocked and script_api test can be run using 'tox'
pip install tox
1. The tests which actually run Jenkins jobs currently do not run under tox.
Install pytest and tenjin template engine:
pip install --user -U -r test/requirements.txt
# The test will also test the generation of documentation, for this you need:
pip install --user -U -r doc/requirements.txt
2. Important Jenkins setup and test preparation:
Configure security -
Some of the tests requires security to be enabled.
You need to create two users in Jenkins:
Read the file demo/demo_security.py and create the user specified.
Create a user called 'jenkinsflow_authtest1', password 'abcæøåÆØÅ'. ( u'\u00e6\u00f8\u00e5\u00c6\u00d8\u00c5' )
Set the number of executers -
Jenkins is default configured with only two executors on master. To avoid timeouts in the test cases this must be raised to at least 32.
This is necessary because some of the test cases will execute a large amount of jobs in parallel.
Change the 'Quite period' -
Jenkins is default configured with a 'Quiet period' of 5 seconds. To avoid timeouts in the test cases this must be set to 0.
Set Jenkins URL -
Jenkins: Manage Jenkins -> Configure System -> Jenkins Location -> Jenkins URL
The url should not use 'localhost'
Your Jenkins needs to be on the host where you are running the test. If it is not, you will need to make jenkinsflow available to Jenkins. See
test/tmp_install.sh
3. Run the tests:
Use tox
or
Use ./test/run.py to run the all tests.
JENKINS_URL=<your Jenkins> python ./test/run.py --mock-speedup=100 --direct-url <non proxied url different from JENKINS_URL>
Note: you may omit JENKINS_URL if your Jenkins is on http://localhost:8080.
Note: you may omit --direct-url if your Jenkins is on http://localhost:8080
The test script will run the test suite with mocked jenkins api, script_api and jenkins_api in parallel. The mocked api is a very fast test of the flow logic.
Mocked tests and script_api tests do not require Jenkins.
The test jobs are automatically created in Jenkins.
It is possible to select a subset of the apis using the --apis option.
The value given to --mock-speedup is the time speedup for the mocked tests. If you have a reasonably fast computer, try 2000.
If you get FlowTimeoutException try a lower value.
If you get "<job> is expected to be running, but state is IDLE" try a lower value.
By default tests are run in parallel using xdist and jobs are not deleted (but will be updated) before each run.
You should have 32 executors or more for this, the cpu/disk load will be small, as the test jobs don't really do anything except sleep.
To disable the use of xdist use --job-delete.
All jobs created by the test script are prefixed with 'jenkinsflow_', so they can easily be removed.
The test suite creates jobs called ..._0flow. These jobs are not executed by the test suite, by you can run them to see what the flows look like in a Jenkins job.
If your Jenkins is not secured, you must set username and password to '' in demo_security, in order to be able to run all the ..._0flow jobs.
To see more test options, run ./test/run.py ---help
Demos
----
1. Run tests as described above to load jobs into Jenkins
2. Demo scripts can be executed from command line:
python ./demo/<demo>.py
3. Demo scripts can be executed from the loaded 'jenkinsflow_demo__<demo-name>__0flow' Jenkins jobs.
Jenkins needs to be able to find the scripts, the run.py script creates a test installation.
Flow Graph Visualisation
-----------------------
1. To see a flow graph of the basic demo in your browser:
Start 'python ./visual/server.py' --json-dir '/tmp/jenkinsflow-test/graphs/jenkinsflow_demo__basic' before running ./demo/basic.py
Open localhost:9090 in your browser.
The test suite also puts some other graps in subdirectories under '/tmp/jenkinsflow-test/graphs'.
The 'visual' feature is still experimental and does not yet show live info about the running flow/jobs.
If you run ...0flow jobs that generate graphs from Jenkins the json graph file will be put in the workspace.
Documentation
----
1. Install sphinx and extensions:
pip install 'sphinx>=1.6' sphinxcontrib-programoutput
2. Build documentation:
cd doc/source
make html (or some other format supported by sphinx)
|
lhupfeldt/jenkinsflow
|
INSTALL.md
|
Markdown
|
bsd-3-clause
| 6,065 |
<?php
namespace backend\assets;
use yii\web\AssetBundle;
/**
* Main backend application asset bundle.
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/form.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
|
Nacho2126/php20162
|
backend/assets/AppAsset.php
|
PHP
|
bsd-3-clause
| 412 |
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/vector.hpp"
#include "wrap_osganimation.h"
#include "_UniqVertexSetToBoneSet__value_traits.pypp.hpp"
#include "uniqvertexsettobonesetlist.pypp.hpp"
namespace bp = boost::python;
void register_UniqVertexSetToBoneSetList_class(){
{ //::std::vector< osgAnimation::VertexInfluenceSet::UniqVertexSetToBoneSet >
typedef bp::class_< std::vector< osgAnimation::VertexInfluenceSet::UniqVertexSetToBoneSet > > UniqVertexSetToBoneSetList_exposer_t;
UniqVertexSetToBoneSetList_exposer_t UniqVertexSetToBoneSetList_exposer = UniqVertexSetToBoneSetList_exposer_t( "UniqVertexSetToBoneSetList" );
bp::scope UniqVertexSetToBoneSetList_scope( UniqVertexSetToBoneSetList_exposer );
UniqVertexSetToBoneSetList_exposer.def( bp::indexing::vector_suite< std::vector< osgAnimation::VertexInfluenceSet::UniqVertexSetToBoneSet > >() );
}
}
|
JaneliaSciComp/osgpyplusplus
|
src/modules/osgAnimation/generated_code/UniqVertexSetToBoneSetList.pypp.cpp
|
C++
|
bsd-3-clause
| 1,000 |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/phonehub/phone_hub_recent_apps_view.h"
#include "ash/system/phonehub/phone_hub_recent_app_button.h"
#include "ash/test/ash_test_base.h"
#include "chromeos/components/phonehub/fake_recent_apps_interaction_handler.h"
#include "chromeos/components/phonehub/notification.h"
#include "ui/gfx/image/image.h"
#include "ui/views/test/button_test_api.h"
namespace ash {
const char16_t kAppName[] = u"Test App";
const char kPackageName[] = "com.google.testapp";
const int64_t kUserId = 0;
namespace {
class FakeEvent : public ui::Event {
public:
FakeEvent() : Event(ui::ET_UNKNOWN, base::TimeTicks(), 0) {}
};
} // namespace
class RecentAppButtonsViewTest : public AshTestBase {
public:
RecentAppButtonsViewTest() = default;
~RecentAppButtonsViewTest() override = default;
// AshTestBase:
void SetUp() override {
AshTestBase::SetUp();
phone_hub_recent_apps_view_ = std::make_unique<PhoneHubRecentAppsView>(
&fake_recent_apps_interaction_handler_);
}
void TearDown() override {
phone_hub_recent_apps_view_.reset();
AshTestBase::TearDown();
}
protected:
PhoneHubRecentAppsView* recent_apps_view() {
return phone_hub_recent_apps_view_.get();
}
void NotifyRecentAppAddedOrUpdated() {
fake_recent_apps_interaction_handler_.NotifyRecentAppAddedOrUpdated(
chromeos::phonehub::Notification::AppMetadata(kAppName, kPackageName,
/*icon=*/gfx::Image(),
kUserId),
base::Time::Now());
}
size_t PackageNameToClickCount(const std::string& package_name) {
return fake_recent_apps_interaction_handler_.HandledRecentAppsCount(
package_name);
}
private:
std::unique_ptr<PhoneHubRecentAppsView> phone_hub_recent_apps_view_;
chromeos::phonehub::FakeRecentAppsInteractionHandler
fake_recent_apps_interaction_handler_;
};
TEST_F(RecentAppButtonsViewTest, TaskViewVisibility) {
// The recent app view is not visible if the NotifyRecentAppAddedOrUpdated
// function never be called, e.g. device boot.
EXPECT_FALSE(recent_apps_view()->recent_app_buttons_view_->GetVisible());
NotifyRecentAppAddedOrUpdated();
recent_apps_view()->Update();
EXPECT_TRUE(recent_apps_view()->GetVisible());
}
TEST_F(RecentAppButtonsViewTest, SingleRecentAppButtonsView) {
NotifyRecentAppAddedOrUpdated();
recent_apps_view()->Update();
size_t expected_recent_app_button = 1;
EXPECT_EQ(expected_recent_app_button,
recent_apps_view()->recent_app_buttons_view_->children().size());
}
TEST_F(RecentAppButtonsViewTest, MultipleRecentAppButtonsView) {
NotifyRecentAppAddedOrUpdated();
NotifyRecentAppAddedOrUpdated();
NotifyRecentAppAddedOrUpdated();
recent_apps_view()->Update();
size_t expected_recent_app_button = 3;
EXPECT_EQ(expected_recent_app_button,
recent_apps_view()->recent_app_buttons_view_->children().size());
for (auto* child : recent_apps_view()->recent_app_buttons_view_->children()) {
PhoneHubRecentAppButton* recent_app =
static_cast<PhoneHubRecentAppButton*>(child);
// Simulate clicking button using placeholder event.
views::test::ButtonTestApi(recent_app).NotifyClick(FakeEvent());
}
size_t expected_number_of_button_be_clicked = 3;
EXPECT_EQ(expected_number_of_button_be_clicked,
PackageNameToClickCount(kPackageName));
}
} // namespace ash
|
nwjs/chromium.src
|
ash/system/phonehub/phone_hub_recent_apps_view_unittest.cc
|
C++
|
bsd-3-clause
| 3,619 |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKIMAGEPERMUTEWRAP_H
#define NATIVE_EXTENSION_VTK_VTKIMAGEPERMUTEWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkImagePermute.h>
#include "vtkImageResliceWrap.h"
#include "../../plus/plus.h"
class VtkImagePermuteWrap : public VtkImageResliceWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkImagePermuteWrap(vtkSmartPointer<vtkImagePermute>);
VtkImagePermuteWrap();
~VtkImagePermuteWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetFilteredAxes(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetFilteredAxes(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKIMAGEPERMUTEWRAP_CLASSDEF
VTK_NODE_PLUS_VTKIMAGEPERMUTEWRAP_CLASSDEF
#endif
};
#endif
|
axkibe/node-vtk
|
wrappers/7.0.0/vtkImagePermuteWrap.h
|
C
|
bsd-3-clause
| 1,456 |
"""
Module containing the task handler for Evennia deferred tasks, persistent or not.
"""
from datetime import datetime, timedelta
from twisted.internet import reactor, task
from evennia.server.models import ServerConfig
from evennia.utils.logger import log_err
from evennia.utils.dbserialize import dbserialize, dbunserialize
TASK_HANDLER = None
class TaskHandler(object):
"""
A light singleton wrapper allowing to access permanent tasks.
When `utils.delay` is called, the task handler is used to create
the task. If `utils.delay` is called with `persistent=True`, the
task handler stores the new task and saves.
It's easier to access these tasks (should it be necessary) using
`evennia.scripts.taskhandler.TASK_HANDLER`, which contains one
instance of this class, and use its `add` and `remove` methods.
"""
def __init__(self):
self.tasks = {}
self.to_save = {}
def load(self):
"""Load from the ServerConfig.
Note:
This should be automatically called when Evennia starts.
It populates `self.tasks` according to the ServerConfig.
"""
to_save = False
value = ServerConfig.objects.conf("delayed_tasks", default={})
if isinstance(value, basestring):
tasks = dbunserialize(value)
else:
tasks = value
# At this point, `tasks` contains a dictionary of still-serialized tasks
for task_id, value in tasks.items():
date, callback, args, kwargs = dbunserialize(value)
if isinstance(callback, tuple):
# `callback` can be an object and name for instance methods
obj, method = callback
if obj is None:
to_save = True
continue
callback = getattr(obj, method)
self.tasks[task_id] = (date, callback, args, kwargs)
if to_save:
self.save()
def save(self):
"""Save the tasks in ServerConfig."""
for task_id, (date, callback, args, kwargs) in self.tasks.items():
if task_id in self.to_save:
continue
if getattr(callback, "__self__", None):
# `callback` is an instance method
obj = callback.__self__
name = callback.__name__
callback = (obj, name)
# Check if callback can be pickled. args and kwargs have been checked
safe_callback = None
try:
dbserialize(callback)
except (TypeError, AttributeError):
raise ValueError("the specified callback {} cannot be pickled. "
"It must be a top-level function in a module or an "
"instance method.".format(callback))
else:
safe_callback = callback
self.to_save[task_id] = dbserialize((date, safe_callback, args, kwargs))
ServerConfig.objects.conf("delayed_tasks", self.to_save)
def add(self, timedelay, callback, *args, **kwargs):
"""Add a new persistent task in the configuration.
Args:
timedelay (int or float): time in sedconds before calling the callback.
callback (function or instance method): the callback itself
any (any): any additional positional arguments to send to the callback
Kwargs:
persistent (bool, optional): persist the task (store it).
any (any): additional keyword arguments to send to the callback
"""
persistent = kwargs.get("persistent", False)
if persistent:
del kwargs["persistent"]
now = datetime.now()
delta = timedelta(seconds=timedelay)
# Choose a free task_id
safe_args = []
safe_kwargs = {}
used_ids = self.tasks.keys()
task_id = 1
while task_id in used_ids:
task_id += 1
# Check that args and kwargs contain picklable information
for arg in args:
try:
dbserialize(arg)
except (TypeError, AttributeError):
log_err("The positional argument {} cannot be "
"pickled and will not be present in the arguments "
"fed to the callback {}".format(arg, callback))
else:
safe_args.append(arg)
for key, value in kwargs.items():
try:
dbserialize(value)
except (TypeError, AttributeError):
log_err("The {} keyword argument {} cannot be "
"pickled and will not be present in the arguments "
"fed to the callback {}".format(key, value, callback))
else:
safe_kwargs[key] = value
self.tasks[task_id] = (now + delta, callback, safe_args, safe_kwargs)
self.save()
callback = self.do_task
args = [task_id]
kwargs = {}
return task.deferLater(reactor, timedelay, callback, *args, **kwargs)
def remove(self, task_id):
"""Remove a persistent task without executing it.
Args:
task_id (int): an existing task ID.
Note:
A non-persistent task doesn't have a task_id, it is not stored
in the TaskHandler.
"""
del self.tasks[task_id]
if task_id in self.to_save:
del self.to_save[task_id]
self.save()
def do_task(self, task_id):
"""Execute the task (call its callback).
Args:
task_id (int): a valid task ID.
Note:
This will also remove it from the list of current tasks.
"""
date, callback, args, kwargs = self.tasks.pop(task_id)
if task_id in self.to_save:
del self.to_save[task_id]
self.save()
callback(*args, **kwargs)
def create_delays(self):
"""Create the delayed tasks for the persistent tasks.
Note:
This method should be automatically called when Evennia starts.
"""
now = datetime.now()
for task_id, (date, callbac, args, kwargs) in self.tasks.items():
seconds = max(0, (date - now).total_seconds())
task.deferLater(reactor, seconds, self.do_task, task_id)
# Create the soft singleton
TASK_HANDLER = TaskHandler()
|
feend78/evennia
|
evennia/scripts/taskhandler.py
|
Python
|
bsd-3-clause
| 6,609 |
Adafruit_ADS1x15
================
Library for ADS1x15 series of 12-bit and 16-bit Analog to Digital converter breakout boards
<!-- START COMPATIBILITY TABLE -->
## Compatibility
Board | Tested Works | Doesn't Work | Not Tested | Notes
----------------- | :----------: | :----------: | :---------: | -----
Particle Photon | X | | | Use SDA/SCL on pins D1 and D0, ALERT on D2 for samples.
* Particle Photon : Particle Photon 3.3V (https://docs.particle.io/datasheets/kits/photon)
<!-- END COMPATIBILITY TABLE -->
|
kdupreez/Adafruit_ADS1X15
|
README.md
|
Markdown
|
bsd-3-clause
| 572 |
/*
* Copyright (c) 2007, intarsys consulting GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of intarsys nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.intarsys.tools.monitor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import de.intarsys.tools.infoset.ElementTools;
import de.intarsys.tools.infoset.IElement;
import de.intarsys.tools.reflect.ObjectCreationException;
/**
*
*/
public class MonitorFactory {
public static IMonitor[] createMonitors(IElement element, Object context)
throws ObjectCreationException {
List<IMonitor> monitors = new ArrayList<IMonitor>();
IElement eMonitors = element.element("monitors");
if (eMonitors != null) {
Iterator<IElement> it = element.elementIterator("monitor");
while (it.hasNext()) {
IElement eMonitor = it.next();
IMonitor monitor = ElementTools.createObject(eMonitor,
IMonitor.class, context);
monitors.add(monitor);
MonitorRegistry.get().registerMonitor(monitor);
}
}
return monitors.toArray(new IMonitor[monitors.size()]);
}
private MonitorFactory() {
}
}
|
intarsys/runtime
|
src/de/intarsys/tools/monitor/MonitorFactory.java
|
Java
|
bsd-3-clause
| 2,502 |
{-# OPTIONS_GHC -Wno-missing-signatures #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TypeApplications #-}
module Cm.RGA where
import Prelude hiding (fail)
import Control.Monad.State.Strict (execStateT, runStateT)
import Data.Foldable (toList)
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust)
import Test.QuickCheck (Property, conjoin, counterexample, (.&&.),
(===))
import CRDT.Arbitrary (NoNul (..))
import CRDT.Cm (apply, initial, makeAndApplyOp, makeOp)
import CRDT.Cm.RGA (RGA (OpAddAfter, OpRemove), RgaIntent (AddAfter),
RgaPayload (RgaPayload), fromString, load,
toString)
import CRDT.LamportClock (LamportTime (LamportTime), Pid (Pid),
advance)
import CRDT.LamportClock.Simulation (ProcessSim, runLamportClockSim,
runProcessSim)
import CRDT.Laws (cmrdtLaw)
import GHC.Exts (fromList)
import Util (pattern (:-), expectRightK, fail, ok)
prop_makeOp = isJust $ makeOp @(RGA Char) @ProcessSim
(AddAfter Nothing 'a')
(initial @(RGA Char))
prop_makeAndApplyOp = conjoin
[ counterexample "result3" $ expectRightK result3 $ \(op, payload) ->
counterexample ("op = " ++ show op) (opsEqWoTime op op3)
.&&. counterexample "payload" (payloadsEqWoTime payload payload3)
, counterexample "result2" $ expectRightK result2 $ \(op, payload) ->
counterexample ("op = " ++ show op) (opsEqWoTime op op2)
.&&. counterexample "payload" (payloadsEqWoTime payload payload2)
, counterexample "result1" $ expectRightK result1 $ \(op, payload) ->
counterexample ("op = " ++ show op) (opsEqWoTime op op1)
.&&. counterexample "payload" (payloadsEqWoTime payload payload1)
, counterexample "result12" $ result12 === payload12
, counterexample "results=" $ result21 === result12
]
where
time1 = LamportTime 4 $ Pid 1 -- TODO(cblp, 2018-02-11) arbitrary pids
time2 = LamportTime 4 $ Pid 2
time3 = LamportTime 3 $ Pid 3
op1 = OpAddAfter Nothing '1' time1
op2 = OpAddAfter Nothing '2' time2
op3 = OpAddAfter Nothing '3' time3
payload3 = load $ fromList [time3 :- '3']
payload1 = load $ fromList [time1 :- '1', time3 :- '3']
payload2 = load $ fromList [time2 :- '2', time3 :- '3']
payload12 = load $ fromList [time2 :- '2', time1 :- '1', time3 :- '3']
result3 =
runLamportClockSim
. runProcessSim (Pid 3)
. (`runStateT` initial @(RGA Char))
$ do
advance 2
makeAndApplyOp @(RGA Char) (AddAfter Nothing '3')
result2 =
runLamportClockSim . runProcessSim (Pid 2) . (`runStateT` payload3) $ do
advance 1
makeAndApplyOp @(RGA Char) (AddAfter Nothing '2')
result1 =
runLamportClockSim
. runProcessSim (Pid 1)
. (`runStateT` payload3)
$ makeAndApplyOp @(RGA Char) (AddAfter Nothing '1')
result12 = apply op2 payload1
result21 = apply op1 payload2
prop_fromString (NoNul s) pid =
expectRightK result $ payloadsEqWoTime $ load $ fromList
[ LamportTime t pid :- c | t <- [1..] | c <- s ]
where
result =
runLamportClockSim
. runProcessSim pid
. (`execStateT` initial @(RGA Char))
$ fromString s
prop_fromString_toString (NoNul s) pid = expectRightK result
$ \s' -> toString s' === s
where
result =
runLamportClockSim
. runProcessSim pid
. (`execStateT` initial @(RGA Char))
$ fromString s
prop_Cm = cmrdtLaw @(RGA Char)
-- | Ops equal without local times
opsEqWoTime (OpAddAfter parent1 atom1 id1) (OpAddAfter parent2 atom2 id2) =
conjoin
[ counterexample "parent" $ pidsMaybeEq parent1 parent2
, counterexample "atom" $ atom1 === atom2
, counterexample "id" $ pidsEqWoTime id1 id2
]
opsEqWoTime (OpRemove parent1) (OpRemove parent2) =
counterexample "parent" $ pidsEqWoTime parent1 parent2
opsEqWoTime x y = fail $ show x ++ " /= " ++ show y
pidsEqWoTime (LamportTime _ pid1) (LamportTime _ pid2) = pid1 === pid2
pidsMaybeEq Nothing Nothing = ok
pidsMaybeEq (Just x) (Just y) = pidsEqWoTime x y
pidsMaybeEq x y = fail $ show x ++ " /= " ++ show y
payloadsEqWoTime :: (Eq a, Show a) => RgaPayload a -> RgaPayload a -> Property
payloadsEqWoTime (RgaPayload vertices1 vertexIxs1) (RgaPayload vertices2 vertexIxs2)
= conjoin
[ counterexample "vertices" $ conjoin
[ counterexample ("[" ++ show i ++ "]")
$ counterexample "id" (pidsEqWoTime id1 id2)
.&&. counterexample "atom" (a1 === a2)
| i <- [0 :: Int ..] | (id1, a1) <- toList vertices1 | (id2, a2) <- toList vertices2
]
, counterexample "vertexIxs" $ conjoin
[ counterexample "id" (pidsEqWoTime id1 id2)
.&&. counterexample "ix" (ix1 === ix2)
| (id1, ix1) <- Map.assocs vertexIxs1 | (id2, ix2) <- Map.assocs vertexIxs2
]
]
|
cblp/crdt
|
crdt-test/test/Cm/RGA.hs
|
Haskell
|
bsd-3-clause
| 5,380 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel common\models\search\CategorySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="category-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Category', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'attribute' => 'parent_id',
'value' => function ($data) {
return $data->category['name'] ? $data->category['name'] : 'Самостоятельная категория';
}
],
'name',
'keywords',
'description',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
|
hovhannesabovyan/e-shopper
|
backend/views/category/index.php
|
PHP
|
bsd-3-clause
| 1,150 |
<?php
/**
* Contains class LeMike_DevMode_Block_Catalog_Tabs.
*
* @category LeMike_DevMode
* @package LeMike\DevMode\Block\Catalog
* @author Mike Pretzlaw <[email protected]>
* @copyright 2013 Mike Pretzlaw
* @license http://github.com/sourcerer-mike/mage_devmode/blob/master/License.md BSD 3-Clause ("BSD New")
* @link http://github.com/sourcerer-mike/mage_devmode LeMike_DevMode on GitHub
* @since 0.1.0
*/
/**
* LeMike_DevMode Catalog page left menu
*
* @category LeMike_DevMode
* @package LeMike\DevMode\Block\Catalog
* @author Mike Pretzlaw <[email protected]>
*/
class LeMike_DevMode_Block_Catalog_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
/**
* New catalog Tab.
*/
public function __construct()
{
parent::__construct();
$this->setId('catalog_tabs');
$this->setDestElementId('devmode_catalog');
$this->setData('title', Mage::helper('lemike_devmode')->__('Catalog Tools'));
}
/**
* Add tab before transformed to HTML.
*
* @return Mage_Core_Block_Abstract
*/
protected function _beforeToHtml()
{
/** @var LeMike_DevMode_Block_Catalog_Products $mainSection */
$mainSection = $this->getLayout()->createBlock('lemike_devmode/catalog_products', 'catalog.products');
$this->addTab(
'main_section',
array(
'label' => Mage::helper('lemike_devmode')->__('Products'),
'title' => Mage::helper('lemike_devmode')->__('Products'),
'content' => $mainSection->toHtml(),
'active' => true
)
);
return parent::_beforeToHtml();
}
}
|
sourcerer-mike/magento-devMode
|
app/code/community/LeMike/DevMode/Block/Catalog/Tabs.php
|
PHP
|
bsd-3-clause
| 1,713 |
echo "======================================================================="
echo "Fixing access to datasets and ck-experiments ..."
echo ""
time sudo chmod -R 777 datasets
time sudo chmod -R 777 ck-experiments
echo "====================================================================="
echo "Adding external ck-experiments repository ..."
echo ""
ck add repo:ck-experiments --path=/home/ckuser/ck-experiments --quiet
ck ls repo
pwd
ls
ck detect soft:dataset.imagenet.val --force_version=2012 \
--extra_tags=full --search_dir=$HOME/datasets
time ck install package --dep_add_tags.dataset-source=full \
--tags=dataset,imagenet,val,full,preprocessed,using-opencv,side.224 \
--version=2012
time ck install package --tags=model,tflite,resnet50,no-argmax
# Run 500 though can run 50000 if the full dataset
time ck benchmark program:image-classification-tflite-loadgen \
--env.CK_LOADGEN_MODE=AccuracyOnly \
--env.CK_LOADGEN_SCENARIO=SingleStream \
--env.CK_LOADGEN_DATASET_SIZE=500 \
--dep_add_tags.weights=resnet50 \
--dep_add_tags.images=preprocessed,using-opencv \
--env.CK_LOADGEN_BUFFER_SIZE=1024 \
--repetitions=1 \
--skip_print_timers \
--skip_print_stats \
--record \
--record_repo=local \
--record_uoa=mlperf-closed-image-classification2-amd-tflite-v2.4.1-ruy-resnet-50-singlestream-performance-target-latency-75 \
--tags=mlperf,division.closed,task.image-classification2,platform.amd,inference_engine.tflite,inference_engine_version.v2.4.1,inference_engine_backend.ruy,scenario.singlestream,mode.performance,workload \
--print_files=accuracy.txt
|
ctuning/ck
|
docs/mlperf-automation/reproduce/ck-image-classification-x86-64-docker-external-imagenet-helper.sh
|
Shell
|
bsd-3-clause
| 1,668 |
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace CodeOrders\V1\Rest\Orders;
/**
* Description of OrderItemEntity
*
* @author PedroHenrique
*/
class OrderItemEntity {
protected $id;
protected $order_id;
protected $product_id;
protected $quantity;
protected $price;
protected $total;
public function getId() {
return $this->id;
}
public function getOrderId() {
return $this->order_id;
}
public function getProductId() {
return $this->product_id;
}
public function getQuantity() {
return $this->quantity;
}
public function getPrice() {
return $this->price;
}
public function getTotal() {
return $this->total;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function setOrderId($order_id) {
$this->order_id = $order_id;
return $this;
}
public function setProductId($product_id) {
$this->product_id = $product_id;
return $this;
}
public function setQuantity($quantity) {
$this->quantity = $quantity;
return $this;
}
public function setPrice($price) {
$this->price = $price;
return $this;
}
public function setTotal($total) {
$this->total = $total;
return $this;
}
}
|
pedrohglobo/apicodeedu
|
module/CodeOrders/src/CodeOrders/V1/Rest/Orders/OrderItemEntity.php
|
PHP
|
bsd-3-clause
| 1,527 |
/** \addtogroup share */
/*@{*/
/**
* \file include/avr-halib/share/delegate.h
* \brief Defines class Delegate and macros setDelegateMethod and setDelegateFunction
*
* This file is part of avr-halib. See COPYING for copyright details.
*/
#pragma once
/**
* \class Delegate delegate.h "avr-halib/share/delegate.h"
* \brief A class which represents a method or function and implements anonymous callback functionality
**/
extern "C" void emptyFunction(){}
template < typename parameter = void >
class Delegate {
typedef void (*invoke_stub)(void const *, parameter);
void const *obj_ptr_;
volatile invoke_stub stub_ptr_;
template < typename T, void (T::*Fxn)(parameter) >
struct mem_fn_stub {
static void invoke(void const * obj_ptr, parameter a0) {
T * obj = static_cast<T *>(const_cast<void *>(obj_ptr));
(obj->*Fxn)(a0);
}
};
template < typename T, void (T::*Fxn)(parameter) const >
struct mem_fn_const_stub {
static void invoke(void const * obj_ptr, parameter a0) {
T const * obj = static_cast<T const *>(obj_ptr);
(obj->*Fxn)(a0);
}
};
template < void (*Fxn)(parameter) >
struct function_stub {
static void invoke(void const *, parameter a0) {
(*Fxn)(a0);
}
};
public:
Delegate() : obj_ptr_(0), stub_ptr_(reinterpret_cast<invoke_stub>(&emptyFunction)) { }
void reset() {
stub_ptr_ = reinterpret_cast<invoke_stub>(&emptyFunction);
}
bool isEmpty() {
return stub_ptr_ == reinterpret_cast<invoke_stub>(&emptyFunction);
}
/**
* \brief Assigns a method to this delegate object
* \tparam T Class which contains the method
* \tparam T::*Fxn Method pointer
* \param obj Pointer to the instance of \c T
*
* \see setDelegateMethod
*/
template < typename T, void (T::*Fxn)(parameter) >
void bind(T * obj) {
obj_ptr_ = const_cast<T const *>(obj);
stub_ptr_ = &mem_fn_stub<T, Fxn>::invoke;
}
template < typename T, void (T::*Fxn)(parameter) const >
void bind(T const * obj) {
obj_ptr_ = obj;
stub_ptr_ = &mem_fn_const_stub<T, Fxn>::invoke;
}
/**
* \brief Assigns a function to this delegate object
* \tparam Fxn Function pointer
*
* \see setDelegateFunction
*/
template < void (*Fxn)(parameter) >
void bind() {
obj_ptr_ = 0;
stub_ptr_ = &function_stub<Fxn>::invoke;
}
/**
* \brief Calls associated function or method
* \pre \ref bind,
* \ref setDelegateMethod or
* \ref setDelegateFunction have to be called before
*/
void operator()(parameter a0) const {
(*stub_ptr_)(obj_ptr_, a0);
}
operator bool() const {
return stub_ptr_;
}
};
template<>
class Delegate<void> {
typedef void (*invoke_stub)(void const *);
void const *obj_ptr_;
volatile invoke_stub stub_ptr_;
template < typename T, void (T::*Fxn)() >
struct mem_fn_stub {
static void invoke(void const * obj_ptr) {
T * obj = static_cast<T *>(const_cast<void *>(obj_ptr));
(obj->*Fxn)();
}
};
template < typename T, void (T::*Fxn)() const >
struct mem_fn_const_stub {
static void invoke(void const * obj_ptr) {
T const * obj = static_cast<T const *>(obj_ptr);
(obj->*Fxn)();
}
};
template < void (*Fxn)() >
struct function_stub {
static void invoke(void const *) {
(*Fxn)();
}
};
public:
Delegate() : obj_ptr_(0), stub_ptr_(reinterpret_cast<invoke_stub>(&emptyFunction)) { }
void reset() {
stub_ptr_ = reinterpret_cast<invoke_stub>(&emptyFunction);
}
bool isEmpty() {
return stub_ptr_ == reinterpret_cast<invoke_stub>(&emptyFunction);
}
/**
* \brief Assigns a method to this delegate object
* \tparam T Class which contains the method
* \tparam T::*Fxn Method pointer
* \param obj Pointer to the instance of \c T
*
* \see setDelegateMethod
*/
template < typename T, void (T::*Fxn)() >
void bind(T * obj) {
obj_ptr_ = const_cast<T const *>(obj);
stub_ptr_ = &mem_fn_stub<T, Fxn>::invoke;
}
template < typename T, void (T::*Fxn)() const >
void bind(T const * obj) {
obj_ptr_ = obj;
stub_ptr_ = &mem_fn_const_stub<T, Fxn>::invoke;
}
/**
* \brief Assigns a function to this delegate object
* \tparam Fxn Function pointer
*
* \see setDelegateFunction
*/
template < void (*Fxn)() >
void bind() {
obj_ptr_ = 0;
stub_ptr_ = &function_stub<Fxn>::invoke;
}
/**
* \brief Calls associated function or method
* \pre \ref bind,
* \ref setDelegateMethod or
* \ref setDelegateFunction have to be called before
*/
void operator()() const {
(*stub_ptr_)(obj_ptr_);
}
operator bool() const {
return stub_ptr_;
}
};
/**
* \brief Assigns a method to a delegate object
* \param delegate Delegate object
* \param objType Class which contains the method
* \param func Method
* \param obj Object, instance of \c objType
*
* \see Delegate
*/
#define setDelegateMethod(delegate, objType, func, obj) __setDelegateMethod(delegate, objType, func, obj)
#define __setDelegateMethod(delegate, objType, func, obj) \
delegate.bind<objType, & func>(& obj)
/**
* \brief Assigns a function to a delegate object
* \param delegate Delegate object
* \param func Function
*
* \see Delegate
*/
#define setDelegateFunction(delegate, func) __setDelegateFunction(delegate, func)
#define __setDelegateFunction(delegate, func) \
delegate.bind< & func>();
/*@}*/
|
steup/Linux-HaLib
|
include/linux-halib/common/delegate.h
|
C
|
bsd-3-clause
| 6,429 |
'use strict';
var logging = require('log4js');
var Promise = require('bluebird');
var util = require('util');
var events = require('events');
var events2 = require('./events2.js')
var EventEmitter2 = events2.EventEmitter2;
var GpioPort = require('./gpio.js').GpioPort;
var log = logging.getLogger('buttons');
util._extend(exports, {
Button: Button,
VButton: VButton,
});
util.inherits(RawButton, EventEmitter2);
function RawButton(pin) {
EventEmitter2.call(this);
this.init = init;
this.pin = pin;
this.poll = poll;
var port = new GpioPort(pin, 'input');
var self = this;
function init() {
return port.init()
.tap(function() {
self.value = port.initialValue;
});
}
function poll() {
return port.read()
.then(function(value) {
if (value !== self.value) {
self.value = value;
log.trace(' gpio[%s] -->', self.pin, value);
var event = value ? 'up' : 'down';
return self.emit(event)
.tap(function(anyListeners) {
if (!anyListeners) {
log.warn('WARNING: No listeners for input event; pin: %s, event: %s', self.pin, event);
}
});
}
});
}
}
util.inherits(Button, RawButton);
function Button(pin) {
RawButton.call(this, pin);
var debouncing = false;
var downTime;
var pending = [];
var self = this;
this.press = press;
this.longpress = longpress;
this.on('down', function() {
if (!debouncing) {
downTime = new Date()
.getTime();
}
});
this.on('up', function() {
if (!debouncing) {
var elapsed = new Date()
.getTime() - downTime;
downTime = undefined;
var event = elapsed > 250 ? 'longpress' : 'press';
return self.emit(event)
.tap(function(anyListeners) {
if (!anyListeners) {
log.warn('WARNING: No listeners for input event; pin: %s, event: %s', self.pin, event);
}
})
.then(function(anyListeners) {
debouncing = true;
return Promise.delay(100)
.finally(function() {
debouncing = false;
})
.return(anyListeners);
});
}
});
function press() {
return self.emit('down')
.then(function() {
Promise.delay(110)
.then(function() {
return self.emit('up');
})
.done();
});
}
function longpress() {
return self.emit('down')
.then(function() {
Promise.delay(260)
.then(function() {
return self.emit('up');
})
.done();
});
}
}
util.inherits(Button2, events.EventEmitter);
function Button2(id) {
events.EventEmitter.call(this);
var wpi = require('wiring-pi');
wpi.pinMode(id, wpi.INPUT);
wpi.pullUpDnControl(id, wpi.PUD_UP);
wpi.wiringPiISR(id, wpi.INT_EDGE_BOTH, onInterrupt);
var me = this;
var state = { value: 1 };
var transient = null;
var timeout = null;
function onInterrupt() {
setImmediate(function() {
var value = wpi.digitalRead(id);
if (value === state.value && value === transient) {
return;
}
transient = value;
if (transient === state.value) {
return;
}
clearTimeout(timeout);
timeout = setTimeout(function() {
state = { value: transient };
timeout = null;
me.emit(value ? 'up' : 'down');
}, 25);
});
}
}
util.inherits(VButton, EventEmitter2);
function VButton() {
EventEmitter2.call(this);
var self = this;
util._extend(this, {
init: init,
press: press,
longpress: longpress,
});
function init() {
}
function press() {
return self.emit('down')
.then(function() {
Promise.delay(110)
.then(function() {
return self.emit('up');
})
.then(function() {
return self.emit('press');
})
.done();
});
}
function longpress() {
return self.emit('down')
.then(function() {
Promise.delay(260)
.then(function() {
return self.emit('up');
})
.then(function() {
return self.emit('longpress');
})
.done();
});
}
}
|
fwestrom/hapili
|
lib/buttons.js
|
JavaScript
|
bsd-3-clause
| 5,185 |
module Authorization
module Base
VALID_PREPOSITIONS = ['of', 'for', 'in', 'on', 'to', 'at', 'by']
BOOLEAN_OPS = ['not', 'or', 'and']
VALID_PREPOSITIONS_PATTERN = VALID_PREPOSITIONS.join('|')
module EvalParser
# Parses and evaluates an authorization expression and returns <tt>true</tt> or <tt>false</tt>.
#
# The authorization expression is defined by the following grammar:
# <expr> ::= (<expr>) | not <expr> | <term> or <expr> | <term> and <expr> | <term>
# <term> ::= <role> | <role> <preposition> <model>
# <preposition> ::= of | for | in | on | to | at | by
# <model> ::= /:*\w+/
# <role> ::= /\w+/ | /'.*'/
#
# Instead of doing recursive descent parsing (not so fun when we support nested parentheses, etc),
# we let Ruby do the work for us by inserting the appropriate permission calls and using eval.
# This would not be a good idea if you were getting authorization expressions from the outside,
# so in that case (e.g. somehow letting users literally type in permission expressions) you'd
# be better off using the recursive descent parser in Module RecursiveDescentParser.
#
# We search for parts of our authorization evaluation that match <role> or <role> <preposition> <model>
# and we ignore anything terminal in our grammar.
#
# 1) Replace all <role> <preposition> <model> matches.
# 2) Replace all <role> matches that aren't one of our other terminals ('not', 'or', 'and', or preposition)
# 3) Eval
def parse_authorization_expression( str )
if str =~ /[^A-Za-z0-9_:'\(\)\s]/
raise AuthorizationExpressionInvalid, "Invalid authorization expression (#{str})"
return false
end
@replacements = []
expr = replace_temporarily_role_of_model( str )
expr = replace_role( expr )
expr = replace_role_of_model( expr )
begin
instance_eval( expr )
rescue
raise AuthorizationExpressionInvalid, "Cannot parse authorization (#{str})"
end
end
def replace_temporarily_role_of_model( str )
role_regex = '\s*(\'\s*(.+?)\s*\'|(\w+))\s+'
model_regex = '\s+(:*\w+)'
parse_regex = Regexp.new(role_regex + '(' + VALID_PREPOSITIONS.join('|') + ')' + model_regex)
str.gsub(parse_regex) do |match|
@replacements.push " process_role_of_model('#{$2 || $3}', '#{$5}') "
" <#{@replacements.length-1}> "
end
end
def replace_role( str )
role_regex = '\s*(\'\s*(.+?)\s*\'|([A-Za-z]\w*))\s*'
parse_regex = Regexp.new(role_regex)
str.gsub(parse_regex) do |match|
if BOOLEAN_OPS.include?($3)
" #{match} "
else
" process_role('#{$2 || $3}') "
end
end
end
def replace_role_of_model( str )
str.gsub(/<(\d+)>/) do |match|
@replacements[$1.to_i]
end
end
def process_role_of_model( role_name, model_name )
model = get_model( model_name )
raise( ModelDoesntImplementRoles, "Model (#{model_name}) doesn't implement #accepts_role?" ) if not model.respond_to? :accepts_role?
model.send( :accepts_role?, role_name, @current_user )
end
def process_role( role_name )
return false if @current_user.nil? || @current_user == :false
raise( UserDoesntImplementRoles, "User doesn't implement #has_role?" ) if not @current_user.respond_to? :has_role?
@current_user.has_role?( role_name )
end
end
# Parses and evaluates an authorization expression and returns <tt>true</tt> or <tt>false</tt>.
# This recursive descent parses uses two instance variables:
# @stack --> a stack with the top holding the boolean expression resulting from the parsing
#
# The authorization expression is defined by the following grammar:
# <expr> ::= (<expr>) | not <expr> | <term> or <expr> | <term> and <expr> | <term>
# <term> ::= <role> | <role> <preposition> <model>
# <preposition> ::= of | for | in | on | to | at | by
# <model> ::= /:*\w+/
# <role> ::= /\w+/ | /'.*'/
#
# There are really two values we must track:
# (1) whether the expression is valid according to the grammar
# (2) the evaluated results --> true/false on the permission queries
# The first is embedded in the control logic because we want short-circuiting. If an expression
# has been parsed and the permission is false, we don't want to try different ways of parsing.
# Note that this implementation of a recursive descent parser is meant to be simple
# and doesn't allow arbitrary nesting of parentheses. It supports up to 5 levels of nesting.
# It also won't handle some types of expressions (A or B) and C, which has to be rewritten as
# C and (A or B) so the parenthetical expressions are in the tail.
module RecursiveDescentParser
OPT_PARENTHESES_PATTERN = '(([^()]|\(([^()]|\(([^()]|\(([^()]|\(([^()]|\(([^()])*\))*\))*\))*\))*\))*)'
PARENTHESES_PATTERN = '\(' + OPT_PARENTHESES_PATTERN + '\)'
NOT_PATTERN = '^\s*not\s+' + OPT_PARENTHESES_PATTERN + '$'
AND_PATTERN = '^\s*' + OPT_PARENTHESES_PATTERN + '\s+and\s+' + OPT_PARENTHESES_PATTERN + '\s*$'
OR_PATTERN = '^\s*' + OPT_PARENTHESES_PATTERN + '\s+or\s+' + OPT_PARENTHESES_PATTERN + '\s*$'
ROLE_PATTERN = '(\'\s*(.+)\s*\'|(\w+))'
MODEL_PATTERN = '(:*\w+)'
PARENTHESES_REGEX = Regexp.new('^\s*' + PARENTHESES_PATTERN + '\s*$')
NOT_REGEX = Regexp.new(NOT_PATTERN)
AND_REGEX = Regexp.new(AND_PATTERN)
OR_REGEX = Regexp.new(OR_PATTERN)
ROLE_REGEX = Regexp.new('^\s*' + ROLE_PATTERN + '\s*$')
ROLE_OF_MODEL_REGEX = Regexp.new('^\s*' + ROLE_PATTERN + '\s+(' + VALID_PREPOSITIONS_PATTERN + ')\s+' + MODEL_PATTERN + '\s*$')
def parse_authorization_expression( str )
@stack = []
raise AuthorizationExpressionInvalid, "Cannot parse authorization (#{str})" if not parse_expr( str )
return @stack.pop
end
def parse_expr( str )
parse_parenthesis( str ) or
parse_not( str ) or
parse_or( str ) or
parse_and( str ) or
parse_term( str )
end
def parse_not( str )
if str =~ NOT_REGEX
can_parse = parse_expr( $1 )
@stack.push( [email protected] ) if can_parse
end
false
end
def parse_or( str )
if str =~ OR_REGEX
can_parse = parse_expr( $1 ) and parse_expr( $8 )
@stack.push( @stack.pop | @stack.pop ) if can_parse
return can_parse
end
false
end
def parse_and( str )
if str =~ AND_REGEX
can_parse = parse_expr( $1 ) and parse_expr( $8 )
@stack.push(@stack.pop & @stack.pop) if can_parse
return can_parse
end
false
end
# Descend down parenthesis (allow up to 5 levels of nesting)
def parse_parenthesis( str )
str =~ PARENTHESES_REGEX ? parse_expr( $1 ) : false
end
def parse_term( str )
parse_role_of_model( str ) or
parse_role( str )
end
# Parse <role> of <model>
def parse_role_of_model( str )
if str =~ ROLE_OF_MODEL_REGEX
role_name = $2 || $3
model_name = $5
model_obj = get_model( model_name )
raise( ModelDoesntImplementRoles, "Model (#{model_name}) doesn't implement #accepts_role?" ) if not model_obj.respond_to? :accepts_role?
has_permission = model_obj.send( :accepts_role?, role_name, @current_user )
@stack.push( has_permission )
true
else
false
end
end
# Parse <role> of the User-like object
def parse_role( str )
if str =~ ROLE_REGEX
role_name = $1
if @current_user.nil? || @current_user == :false
@stack.push(false)
else
raise( UserDoesntImplementRoles, "User doesn't implement #has_role?" ) if not @current_user.respond_to? :has_role?
@stack.push( @current_user.has_role?(role_name) )
end
true
else
false
end
end
end
end
end
|
knewter/ansuz
|
vendor/plugins/rails-authorization-plugin/lib/publishare/parser.rb
|
Ruby
|
bsd-3-clause
| 8,383 |
## Abalone
### Characteristics
<table>
<tr> <td>Number of observations</td> <td>4177</td> </tr>
<tr> <td>Number of features</td> <td>8</td> </tr>
<tr> <td>Sparsity</td> <td>96%</td> </tr>
<tr> <td>label mean</td> <td>9.93</td> </tr>
<tr> <td>label std</td> <td>3.22</td> </tr>
<tr> <td>label min</td> <td>1</td> </tr>
<tr> <td>label max</td> <td>29</td> </tr>
</table>
### Description
Predict the age of abalone from physical measurements
[https://archive.ics.uci.edu/ml/datasets/Abalone](https://archive.ics.uci.edu/ml/datasets/Abalone)
### Preprocessing
None
### Original download link
[http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone_scale](http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone_scale)
|
X-DataInitiative/tick-datasets
|
regression/abalone/README.md
|
Markdown
|
bsd-3-clause
| 785 |
function resize_news() {
$h = $('.city_news li').height();
$('.city_news li a').each(function() {
$(this).height($h);
});
}
$(document).ready(function() {
setTimeout(resize_news(), 100);
$('.city_news p.text').dotdotdot();
});
$(document).ready(function() {
$('p').each(function() {
if (($(this).find('img').css('float') != 'left') && ($(this).find('img').css('float') != 'right')) {
$(this).find('img').addClass('big_news_img');
}
});
});
|
tatia-kom/gde_v_donetske
|
js/news.js
|
JavaScript
|
bsd-3-clause
| 507 |
var path = require('path');
module.exports = {
entry: path.join(__dirname, 'src', 'index.js'),
output: {
filename: 'react-autosuggest-geocoder.js',
path: path.join(__dirname, 'lib'),
library: 'ReactAutosuggestGeocoder',
libraryTarget: 'umd'
},
devtool: 'source-map',
resolve: {
extensions: ['.js', '.scss', '.json']
},
module: {
rules: [{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/
}, {
test: /\.json$/,
use: ['json-loader']
}, {
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: /node_modules/
}]
},
node: {
global: false
}
};
|
abec/react-autosuggest-geocoder
|
webpack.config.js
|
JavaScript
|
bsd-3-clause
| 684 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_05) on Tue Jul 16 16:29:20 CEST 2013 -->
<title>Uses of Class de.intarsys.security.smartcard.smartcardio.ListReaders</title>
<meta name="date" content="2013-07-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class de.intarsys.security.smartcard.smartcardio.ListReaders";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../de/intarsys/security/smartcard/smartcardio/ListReaders.html" title="class in de.intarsys.security.smartcard.smartcardio">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?de/intarsys/security/smartcard/smartcardio/class-use/ListReaders.html" target="_top">Frames</a></li>
<li><a href="ListReaders.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class de.intarsys.security.smartcard.smartcardio.ListReaders" class="title">Uses of Class<br>de.intarsys.security.smartcard.smartcardio.ListReaders</h2>
</div>
<div class="classUseContainer">No usage of de.intarsys.security.smartcard.smartcardio.ListReaders</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../de/intarsys/security/smartcard/smartcardio/ListReaders.html" title="class in de.intarsys.security.smartcard.smartcardio">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?de/intarsys/security/smartcard/smartcardio/class-use/ListReaders.html" target="_top">Frames</a></li>
<li><a href="ListReaders.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
intarsys/smartcard-io
|
doc/javadoc/de/intarsys/security/smartcard/smartcardio/class-use/ListReaders.html
|
HTML
|
bsd-3-clause
| 4,385 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/version.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/pending_extension_manager.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace {
// Install predicate used by AddFromExternalUpdateUrl().
bool AlwaysInstall(const Extension& extension) {
return true;
}
} // namespace
PendingExtensionManager::PendingExtensionManager(
const ExtensionServiceInterface& service)
: service_(service) {
}
PendingExtensionManager::~PendingExtensionManager() {}
bool PendingExtensionManager::GetById(
const std::string& id,
PendingExtensionInfo* out_pending_extension_info) const {
PendingExtensionMap::const_iterator it = pending_extension_map_.find(id);
if (it != pending_extension_map_.end()) {
*out_pending_extension_info = it->second;
return true;
}
return false;
}
void PendingExtensionManager::Remove(const std::string& id) {
pending_extension_map_.erase(id);
}
bool PendingExtensionManager::IsIdPending(const std::string& id) const {
return ContainsKey(pending_extension_map_, id);
}
bool PendingExtensionManager::AddFromSync(
const std::string& id,
const GURL& update_url,
PendingExtensionInfo::ShouldAllowInstallPredicate should_allow_install,
bool install_silently) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (service_.GetInstalledExtension(id)) {
LOG(ERROR) << "Trying to add pending extension " << id
<< " which already exists";
return false;
}
// Make sure we don't ever try to install the CWS app, because even though
// it is listed as a syncable app (because its values need to be synced) it
// should already be installed on every instance.
if (id == extension_misc::kWebStoreAppId) {
NOTREACHED();
return false;
}
const bool kIsFromSync = true;
const Extension::Location kSyncLocation = Extension::INTERNAL;
return AddExtensionImpl(id, update_url, Version(), should_allow_install,
kIsFromSync, install_silently, kSyncLocation);
}
bool PendingExtensionManager::AddFromExternalUpdateUrl(
const std::string& id, const GURL& update_url,
Extension::Location location) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const bool kIsFromSync = false;
const bool kInstallSilently = true;
const Extension* extension = service_.GetInstalledExtension(id);
if (extension &&
location == Extension::GetHigherPriorityLocation(location,
extension->location())) {
// If the new location has higher priority than the location of an existing
// extension, let the update process overwrite the existing extension.
} else {
if (service_.IsExternalExtensionUninstalled(id))
return false;
if (extension) {
LOG(DFATAL) << "Trying to add extension " << id
<< " by external update, but it is already installed.";
return false;
}
}
return AddExtensionImpl(id, update_url, Version(), &AlwaysInstall,
kIsFromSync, kInstallSilently,
location);
}
bool PendingExtensionManager::AddFromExternalFile(
const std::string& id,
Extension::Location install_source,
const Version& version) {
// TODO(skerner): AddFromSync() checks to see if the extension is
// installed, but this method assumes that the caller already
// made sure it is not installed. Make all AddFrom*() methods
// consistent.
GURL kUpdateUrl = GURL();
bool kIsFromSync = false;
bool kInstallSilently = true;
return AddExtensionImpl(
id,
kUpdateUrl,
version,
&AlwaysInstall,
kIsFromSync,
kInstallSilently,
install_source);
}
void PendingExtensionManager::GetPendingIdsForUpdateCheck(
std::set<std::string>* out_ids_for_update_check) const {
PendingExtensionMap::const_iterator iter;
for (iter = pending_extension_map_.begin();
iter != pending_extension_map_.end();
++iter) {
Extension::Location install_source = iter->second.install_source();
// Some install sources read a CRX from the filesystem. They can
// not be fetched from an update URL, so don't include them in the
// set of ids.
if (install_source == Extension::EXTERNAL_PREF ||
install_source == Extension::EXTERNAL_REGISTRY)
continue;
out_ids_for_update_check->insert(iter->first);
}
}
bool PendingExtensionManager::AddExtensionImpl(
const std::string& id,
const GURL& update_url,
const Version& version,
PendingExtensionInfo::ShouldAllowInstallPredicate should_allow_install,
bool is_from_sync,
bool install_silently,
Extension::Location install_source) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PendingExtensionInfo pending;
if (GetById(id, &pending)) {
// Bugs in this code will manifest as sporadic incorrect extension
// locations in situations where multiple install sources run at the
// same time. For example, on first login to a chrome os machine, an
// extension may be requested by sync and the default extension set.
// The following logging will help diagnose such issues.
VLOG(1) << "Extension id " << id
<< " was entered for update more than once."
<< " old location: " << pending.install_source()
<< " new location: " << install_source;
// Never override an existing extension with an older version. Only
// extensions from local CRX files have a known version; extensions from an
// update URL will get the latest version.
if (version.IsValid() &&
pending.version().IsValid() &&
pending.version().CompareTo(version) == 1) {
VLOG(1) << "Keep existing record (has a newer version).";
return false;
}
Extension::Location higher_priority_location =
Extension::GetHigherPriorityLocation(
install_source, pending.install_source());
if (higher_priority_location != install_source) {
VLOG(1) << "Keep existing record (has a higher priority location).";
return false;
}
VLOG(1) << "Overwrite existing record.";
}
pending_extension_map_[id] = PendingExtensionInfo(
update_url,
version,
should_allow_install,
is_from_sync,
install_silently,
install_source);
return true;
}
void PendingExtensionManager::AddForTesting(
const std::string& id,
const PendingExtensionInfo& pending_extension_info) {
pending_extension_map_[id] = pending_extension_info;
}
|
robclark/chromium
|
chrome/browser/extensions/pending_extension_manager.cc
|
C++
|
bsd-3-clause
| 6,903 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_91) on Tue Dec 29 12:43:37 AEDT 2015 -->
<title>Flags (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Flags (Bouncy Castle Library 1.54 API Specification)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/asn1/eac/ECDSAPublicKey.html" title="class in org.bouncycastle.asn1.eac"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/asn1/eac/PackedDate.html" title="class in org.bouncycastle.asn1.eac"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/asn1/eac/Flags.html" target="_top">Frames</a></li>
<li><a href="Flags.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.bouncycastle.asn1.eac</div>
<h2 title="Class Flags" class="title">Class Flags</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.bouncycastle.asn1.eac.Flags</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">Flags</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/bouncycastle/asn1/eac/Flags.html#Flags()">Flags</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../org/bouncycastle/asn1/eac/Flags.html#Flags(int)">Flags</a></strong>(int v)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/asn1/eac/Flags.html#getFlags()">getFlags</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/asn1/eac/Flags.html#isSet(int)">isSet</a></strong>(int flag)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/asn1/eac/Flags.html#set(int)">set</a></strong>(int flag)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Flags()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>Flags</h4>
<pre>public Flags()</pre>
</li>
</ul>
<a name="Flags(int)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Flags</h4>
<pre>public Flags(int v)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="set(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>set</h4>
<pre>public void set(int flag)</pre>
</li>
</ul>
<a name="isSet(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isSet</h4>
<pre>public boolean isSet(int flag)</pre>
</li>
</ul>
<a name="getFlags()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getFlags</h4>
<pre>public int getFlags()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/asn1/eac/ECDSAPublicKey.html" title="class in org.bouncycastle.asn1.eac"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/asn1/eac/PackedDate.html" title="class in org.bouncycastle.asn1.eac"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/asn1/eac/Flags.html" target="_top">Frames</a></li>
<li><a href="Flags.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
GaloisInc/hacrypto
|
src/Java/BouncyCastle/BouncyCastle-1.54/bcprov-jdk15on-154/javadoc/org/bouncycastle/asn1/eac/Flags.html
|
HTML
|
bsd-3-clause
| 9,370 |
/*!
* FullCalendar v2.6.1 Print Stylesheet
* Docs & License: http://fullcalendar.io/
* (c) 2015 Adam Shaw
*/
/*
* Include this stylesheet on your page to get a more printer-friendly calendar.
* When including this stylesheet, use the media='print' attribute of the <link> tag.
* Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css.
*/
.fc {
max-width: 100% !important;
}
/* Global Event Restyling
--------------------------------------------------------------------------------------------------*/
.fc-event {
background: #fff !important;
color: #000 !important;
page-break-inside: avoid;
}
.fc-event .fc-resizer {
display: none;
}
/* Table & Day-Row Restyling
--------------------------------------------------------------------------------------------------*/
th,
td,
hr,
thead,
tbody,
.fc-row {
border-color: #ccc !important;
background: #fff !important;
}
/* kill the overlaid, absolutely-positioned components */
/* common... */
.fc-bg,
.fc-bgevent-skeleton,
.fc-highlight-skeleton,
.fc-helper-skeleton,
/* for timegrid. within cells within table skeletons... */
.fc-bgevent-container,
.fc-business-container,
.fc-highlight-container,
.fc-helper-container {
display: none;
}
/* don't force a min-height on rows (for DayGrid) */
.fc tbody .fc-row {
height: auto !important; /* undo height that JS set in distributeHeight */
min-height: 0 !important; /* undo the min-height from each view's specific stylesheet */
}
.fc tbody .fc-row .fc-content-skeleton {
position: static; /* undo .fc-rigid */
padding-bottom: 0 !important; /* use a more border-friendly method for this... */
}
.fc tbody .fc-row .fc-content-skeleton tbody tr:last-child td { /* only works in newer browsers */
padding-bottom: 1em; /* ...gives space within the skeleton. also ensures min height in a way */
}
.fc tbody .fc-row .fc-content-skeleton table {
/* provides a min-height for the row, but only effective for IE, which exaggerates this value,
making it look more like 3em. for other browers, it will already be this tall */
height: 1em;
}
/* Undo month-view event limiting. Display all events and hide the "more" links
--------------------------------------------------------------------------------------------------*/
.fc-more-cell,
.fc-more {
display: none !important;
}
.fc tr.fc-limited {
display: table-row !important;
}
.fc td.fc-limited {
display: table-cell !important;
}
.fc-popover {
display: none; /* never display the "more.." popover in print mode */
}
/* TimeGrid Restyling
--------------------------------------------------------------------------------------------------*/
/* undo the min-height 100% trick used to fill the container's height */
.fc-time-grid {
min-height: 0 !important;
}
/* don't display the side axis at all ("all-day" and time cells) */
.fc-agenda-view .fc-axis {
display: none;
}
/* don't display the horizontal lines */
.fc-slats,
.fc-time-grid hr { /* this hr is used when height is underused and needs to be filled */
display: none !important; /* important overrides inline declaration */
}
/* let the container that holds the events be naturally positioned and create real height */
.fc-time-grid .fc-content-skeleton {
position: static;
}
/* in case there are no events, we still want some height */
.fc-time-grid .fc-content-skeleton table {
height: 4em;
}
/* kill the horizontal spacing made by the event container. event margins will be done below */
.fc-time-grid .fc-event-container {
margin: 0 !important;
}
/* TimeGrid *Event* Restyling
--------------------------------------------------------------------------------------------------*/
/* naturally position events, vertically stacking them */
.fc-time-grid .fc-event {
position: static !important;
margin: 3px 2px !important;
}
/* for events that continue to a future day, give the bottom border back */
.fc-time-grid .fc-event.fc-not-end {
border-bottom-width: 1px !important;
}
/* indicate the event continues via "..." text */
.fc-time-grid .fc-event.fc-not-end:after {
content: "...";
}
/* for events that are continuations from previous days, give the top border back */
.fc-time-grid .fc-event.fc-not-start {
border-top-width: 1px !important;
}
/* indicate the event is a continuation via "..." text */
.fc-time-grid .fc-event.fc-not-start:before {
content: "...";
}
/* time */
/* undo a previous declaration and let the time text span to a second line */
.fc-time-grid .fc-event .fc-time {
white-space: normal !important;
}
/* hide the the time that is normally displayed... */
.fc-time-grid .fc-event .fc-time span {
display: none;
}
/* ...replace it with a more verbose version (includes AM/PM) stored in an html attribute */
.fc-time-grid .fc-event .fc-time:after {
content: attr(data-full);
}
/* Vertical Scroller & Containers
--------------------------------------------------------------------------------------------------*/
/* kill the scrollbars and allow natural height */
.fc-scroller,
.fc-day-grid-container, /* these divs might be assigned height, which we need to cleared */
.fc-time-grid-container { /* */
overflow: visible !important;
height: auto !important;
}
/* kill the horizontal border/padding used to compensate for scrollbars */
.fc-row {
border: 0 !important;
margin: 0 !important;
}
/* Button Controls
--------------------------------------------------------------------------------------------------*/
.fc-button-group,
.fc button {
display: none; /* don't display any button-related controls */
}
|
nwaxiomatic/django-scheduler
|
schedule/static/schedule/css/fullcalendar.print.css
|
CSS
|
bsd-3-clause
| 5,544 |
//NEWCODE
/* -------------------------------------------------------------------
* LHOTSE: Toolbox for adaptive statistical models
* -------------------------------------------------------------------
* Library source file
* Module: GLOBAL
* Desc.: Definition class IntVal
* ------------------------------------------------------------------- */
#include "lhotse/global.h"
const int IntVal::ivOpen;
const int IntVal::ivClosed;
const int IntVal::ivInf;
const int IntVal::ivLast;
|
mseeger/apbsint
|
lhotse/IntVal.cc
|
C++
|
bsd-3-clause
| 487 |
<?php
namespace DeLois\Raml\Generator\Model\Resource;
class Response {
private $_code;
private $_description;
private $_bodies = [];
private $_headers = [];
public function __construct( $code, $description = null ) {
if ( !\Improv\Http\Response\Code::isValid( $code ) ) {
// TODO: Raise Exception
}
$this->_code = $code;
$this->_description = $description;
}
public function getCode() {
return $this->_code;
}
public function addBody( Body $body ) {
$this->_bodies[ $body->getMediaType() ] = $body;
return $this;
}
public function getBodies() {
return $this->_bodies;
}
public function describeAs( $description ) {
$this->_description = $description;
return $this;
}
public function getDescription() {
return $this->_description;
}
}
|
jimdelois/raml-generator
|
src/Raml/Generator/Model/Resource/Response.php
|
PHP
|
bsd-3-clause
| 843 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h"
#include <set>
#include <utility>
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/values_test_util.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h"
#include "chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/scoped_group_bookmark_actions.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace extensions {
namespace {
scoped_refptr<Extension> CreateExtensionWithBookmarksPermission(
bool include_bookmarks) {
ListBuilder permissions;
permissions.Append("declarativeContent");
if (include_bookmarks)
permissions.Append("bookmarks");
return ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Test extension")
.Set("version", "1.0")
.Set("manifest_version", 2)
.Set("permissions", permissions))
.Build();
}
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> CreatePredicate(
ContentPredicateEvaluator* evaluator,
const Extension* extension,
bool is_bookmarked) {
std::string error;
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> predicate =
DeclarativeContentIsBookmarkedPredicate::Create(
evaluator,
extension,
*base::test::ParseJson(is_bookmarked ? "true" : "false"),
&error);
EXPECT_EQ("", error);
EXPECT_TRUE(predicate);
EXPECT_EQ(is_bookmarked, predicate->is_bookmarked());
return predicate;
}
} // namespace
using testing::HasSubstr;
using testing::UnorderedElementsAre;
using testing::UnorderedElementsAreArray;
class DeclarativeContentIsBookmarkedConditionTrackerTest
: public DeclarativeContentConditionTrackerTest {
protected:
class Delegate : public ContentPredicateEvaluator::Delegate {
public:
Delegate() {}
std::set<content::WebContents*>& evaluation_requests() {
return evaluation_requests_;
}
// ContentPredicateEvaluator::Delegate:
void RequestEvaluation(content::WebContents* contents) override {
EXPECT_FALSE(ContainsKey(evaluation_requests_, contents));
evaluation_requests_.insert(contents);
}
bool ShouldManageConditionsForBrowserContext(
content::BrowserContext* context) override {
return true;
}
private:
std::set<content::WebContents*> evaluation_requests_;
DISALLOW_COPY_AND_ASSIGN(Delegate);
};
DeclarativeContentIsBookmarkedConditionTrackerTest() {
profile()->CreateBookmarkModel(true);
bookmarks::test::WaitForBookmarkModelToLoad(
BookmarkModelFactory::GetForProfile(profile()));
bookmark_model_ = BookmarkModelFactory::GetForProfile(profile());
tracker_.reset(new DeclarativeContentIsBookmarkedConditionTracker(
profile(),
&delegate_));
extension_ = CreateExtensionWithBookmarksPermission(true);
is_bookmarked_predicate_ = CreatePredicate(tracker_.get(), extension_.get(),
true);
is_not_bookmarked_predicate_ = CreatePredicate(tracker_.get(),
extension_.get(), false);
}
void LoadURL(content::WebContents* tab, const GURL& url) {
tab->GetController().LoadURL(url, content::Referrer(),
ui::PAGE_TRANSITION_LINK, std::string());
}
testing::AssertionResult CheckPredicates(content::WebContents* tab,
bool page_is_bookmarked) {
const bool is_bookmarked_predicate_success =
page_is_bookmarked ==
tracker_->EvaluatePredicate(is_bookmarked_predicate_.get(), tab);
const bool is_not_bookmarked_predicate_success =
page_is_bookmarked !=
tracker_->EvaluatePredicate(is_not_bookmarked_predicate_.get(), tab);
if (is_bookmarked_predicate_success && is_not_bookmarked_predicate_success)
return testing::AssertionSuccess();
testing::AssertionResult result = testing::AssertionFailure();
if (!is_bookmarked_predicate_success) {
result << "IsBookmarkedPredicate(true): expected "
<< (page_is_bookmarked ? "true" : "false") << " got "
<< (page_is_bookmarked ? "false" : "true");
}
if (!is_not_bookmarked_predicate_success) {
if (!is_bookmarked_predicate_success)
result << "; ";
result << "IsBookmarkedPredicate(false): expected "
<< (page_is_bookmarked ? "false" : "true") << " got "
<< (page_is_bookmarked ? "true" : "false");
}
return result;
}
Delegate delegate_;
bookmarks::BookmarkModel* bookmark_model_;
scoped_ptr<DeclarativeContentIsBookmarkedConditionTracker> tracker_;
scoped_refptr<Extension> extension_;
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> is_bookmarked_predicate_;
scoped_ptr<DeclarativeContentIsBookmarkedPredicate>
is_not_bookmarked_predicate_;
private:
DISALLOW_COPY_AND_ASSIGN(DeclarativeContentIsBookmarkedConditionTrackerTest);
};
// Tests that condition with isBookmarked requires "bookmarks" permission.
TEST(DeclarativeContentIsBookmarkedPredicateTest,
IsBookmarkedPredicateRequiresBookmarkPermissionPermission) {
scoped_refptr<Extension> extension =
CreateExtensionWithBookmarksPermission(false);
std::string error;
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> predicate =
DeclarativeContentIsBookmarkedPredicate::Create(
nullptr,
extension.get(),
*base::test::ParseJson("true"),
&error);
EXPECT_THAT(error, HasSubstr("requires 'bookmarks' permission"));
EXPECT_FALSE(predicate);
}
// Tests an invalid isBookmarked value type.
TEST(DeclarativeContentIsBookmarkedPredicateTest,
WrongIsBookmarkedPredicateDatatype) {
scoped_refptr<Extension> extension =
CreateExtensionWithBookmarksPermission(true);
std::string error;
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> predicate =
DeclarativeContentIsBookmarkedPredicate::Create(
nullptr,
extension.get(),
*base::test::ParseJson("[]"),
&error);
EXPECT_THAT(error, HasSubstr("invalid type"));
EXPECT_FALSE(predicate);
}
// Tests isBookmark: true. Predicate state is checked in CreatePredicate().
TEST(DeclarativeContentIsBookmarkedPredicateTest, IsBookmarkedPredicateTrue) {
scoped_refptr<Extension> extension =
CreateExtensionWithBookmarksPermission(true);
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> predicate =
CreatePredicate(nullptr, extension.get(), true);
}
// Tests isBookmark: false. Predicate state is checked in CreatePredicate().
TEST(DeclarativeContentIsBookmarkedPredicateTest, IsBookmarkedPredicateFalse) {
scoped_refptr<Extension> extension =
CreateExtensionWithBookmarksPermission(true);
scoped_ptr<DeclarativeContentIsBookmarkedPredicate> predicate =
CreatePredicate(nullptr, extension.get(), false);
}
// Tests that starting tracking for a WebContents that has a bookmarked URL
// results in the proper IsUrlBookmarked state.
TEST_F(DeclarativeContentIsBookmarkedConditionTrackerTest,
BookmarkedAtStartOfTracking) {
scoped_ptr<content::WebContents> tab = MakeTab();
LoadURL(tab.get(), GURL("http://bookmarked/"));
EXPECT_TRUE(delegate_.evaluation_requests().empty());
bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked/"));
tracker_->TrackForWebContents(tab.get());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tab.get()));
EXPECT_TRUE(CheckPredicates(tab.get(), true));
}
// Tests that adding and removing bookmarks triggers evaluation requests for the
// matching WebContents.
TEST_F(DeclarativeContentIsBookmarkedConditionTrackerTest,
AddAndRemoveBookmark) {
// Create two tabs.
ScopedVector<content::WebContents> tabs;
for (int i = 0; i < 2; ++i) {
tabs.push_back(MakeTab());
delegate_.evaluation_requests().clear();
tracker_->TrackForWebContents(tabs.back());
EXPECT_THAT(delegate_.evaluation_requests(),
UnorderedElementsAre(tabs.back()));
EXPECT_TRUE(CheckPredicates(tabs.back(), false));
}
// Navigate the first tab to a URL that we will bookmark.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://bookmarked/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Bookmark the first tab's URL.
delegate_.evaluation_requests().clear();
const bookmarks::BookmarkNode* node =
bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked/"));
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Remove the bookmark.
delegate_.evaluation_requests().clear();
bookmark_model_->Remove(node);
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
// Tests that adding and removing bookmarks triggers evaluation requests for the
// matching WebContents.
TEST_F(DeclarativeContentIsBookmarkedConditionTrackerTest, ExtensiveChanges) {
// Create two tabs.
ScopedVector<content::WebContents> tabs;
for (int i = 0; i < 2; ++i) {
tabs.push_back(MakeTab());
delegate_.evaluation_requests().clear();
tracker_->TrackForWebContents(tabs.back());
EXPECT_THAT(delegate_.evaluation_requests(),
UnorderedElementsAre(tabs.back()));
EXPECT_TRUE(CheckPredicates(tabs.back(), false));
}
// Navigate the first tab to a URL that we will bookmark.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://bookmarked/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
{
// Check that evaluation requests occur outside ExtensiveBookmarkChanges for
// added nodes.
delegate_.evaluation_requests().clear();
bookmark_model_->BeginExtensiveChanges();
const bookmarks::BookmarkNode* node =
bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked/"));
EXPECT_TRUE(delegate_.evaluation_requests().empty());
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
bookmark_model_->EndExtensiveChanges();
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Check that evaluation requests occur outside ExtensiveBookmarkChanges for
// removed nodes.
delegate_.evaluation_requests().clear();
bookmark_model_->BeginExtensiveChanges();
bookmark_model_->Remove(node);
EXPECT_TRUE(delegate_.evaluation_requests().empty());
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
bookmark_model_->EndExtensiveChanges();
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
{
// Check that evaluation requests occur outside ScopedGroupBookmarkActions
// for added nodes.
delegate_.evaluation_requests().clear();
const bookmarks::BookmarkNode* node = nullptr;
{
bookmarks::ScopedGroupBookmarkActions scoped_group(bookmark_model_);
node = bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked/"));
EXPECT_TRUE(delegate_.evaluation_requests().empty());
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Check that evaluation requests occur outside ScopedGroupBookmarkActions
// for removed nodes.
delegate_.evaluation_requests().clear();
{
bookmarks::ScopedGroupBookmarkActions scoped_group(bookmark_model_);
bookmark_model_->Remove(node);
EXPECT_TRUE(delegate_.evaluation_requests().empty());
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
}
// Tests that navigation to bookmarked and non-bookmarked URLs triggers
// evaluation requests for the relevant WebContents.
TEST_F(DeclarativeContentIsBookmarkedConditionTrackerTest, Navigation) {
// Bookmark two URLs.
delegate_.evaluation_requests().clear();
bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked1/"));
bookmark_model_->AddURL(bookmark_model_->other_node(), 0,
base::ASCIIToUTF16("title"),
GURL("http://bookmarked2/"));
// Create two tabs.
ScopedVector<content::WebContents> tabs;
for (int i = 0; i < 2; ++i) {
tabs.push_back(MakeTab());
delegate_.evaluation_requests().clear();
tracker_->TrackForWebContents(tabs.back());
EXPECT_THAT(delegate_.evaluation_requests(),
UnorderedElementsAre(tabs.back()));
EXPECT_TRUE(CheckPredicates(tabs.back(), false));
}
// Navigate the first tab to one bookmarked URL.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://bookmarked1/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Navigate the first tab to another bookmarked URL. The contents have
// changed, so we should receive a new evaluation request even though the
// bookmarked state hasn't.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://bookmarked2/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], true));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Navigate the first tab to a non-bookmarked URL.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://not-bookmarked1/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
// Navigate the first tab to another non-bookmarked URL. The contents have
// changed, so we should receive a new evaluation request even though the
// bookmarked state hasn't.
delegate_.evaluation_requests().clear();
LoadURL(tabs[0], GURL("http://not-bookmarked2/"));
tracker_->OnWebContentsNavigation(tabs[0], content::LoadCommittedDetails(),
content::FrameNavigateParams());
EXPECT_THAT(delegate_.evaluation_requests(), UnorderedElementsAre(tabs[0]));
EXPECT_TRUE(CheckPredicates(tabs[0], false));
EXPECT_TRUE(CheckPredicates(tabs[1], false));
}
} // namespace extensions
|
Bysmyyr/chromium-crosswalk
|
chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc
|
C++
|
bsd-3-clause
| 17,494 |
"""
SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple as
possible in order to be comprehensible and easily extensible. SymPy is written
entirely in Python and does not require any external libraries, except
optionally for plotting support.
See the webpage for more information and documentation:
http://code.google.com/p/sympy/"""
__version__ = "0.7.0-git"
def __sympy_debug():
# helper function so we don't import os globally
import os
return eval(os.getenv('SYMPY_DEBUG', 'False'))
SYMPY_DEBUG = __sympy_debug()
import symbol as stdlib_symbol
from sympy.core import *
from assumptions import *
from polys import *
from series import *
from functions import *
from logic import *
from ntheory import *
from concrete import *
from simplify import *
from solvers import *
from matrices import *
from geometry import *
from utilities import *
from integrals import *
# This module is slow to import:
#from physics import units
from plotting import Plot, textplot
from printing import pretty, pretty_print, pprint, pprint_use_unicode, \
pprint_try_use_unicode, print_gtk, print_tree
from printing import ccode, latex, preview
from printing import python, print_python, srepr, sstr, sstrrepr
evalf._create_evalf_table()
# This is slow to import:
#import abc
|
fperez/sympy
|
sympy/__init__.py
|
Python
|
bsd-3-clause
| 1,382 |
module P008 where
import Arrays (window)
run :: IO ()
run = print result
where
input = "73167176531330624919225119674426574742355349194934\
\96983520312774506326239578318016984801869478851843\
\85861560789112949495459501737958331952853208805511\
\12540698747158523863050715693290963295227443043557\
\66896648950445244523161731856403098711121722383113\
\62229893423380308135336276614282806444486645238749\
\30358907296290491560440772390713810515859307960866\
\70172427121883998797908792274921901699720888093776\
\65727333001053367881220235421809751254540594752243\
\52584907711670556013604839586446706324415722155397\
\53697817977846174064955149290862569321978468622482\
\83972241375657056057490261407972968652414535100474\
\82166370484403199890008895243450658541227588666881\
\16427171479924442928230863465674813919123162824586\
\17866458359124566529476545682848912883142607690042\
\24219022671055626321111109370544217506941658960408\
\07198403850962455444362981230987879927244284909188\
\84580156166097919133875499200524063689912560717606\
\05886116467109405077541002256983155200055935729725\
\71636269561882670428252483600823257530420752963450"
digits = map (read . pure) input :: [Integer]
result = maximum . map product . window 13 $ digits
|
tyehle/euler-haskell
|
src/P008.hs
|
Haskell
|
bsd-3-clause
| 1,489 |
import logging
from typing import Any, Callable
from urllib.parse import urljoin, urlparse
from flask import current_app, request
from flask_babel import gettext
from flask_babel.speaklater import LazyString
log = logging.getLogger(__name__)
def is_safe_redirect_url(url: str) -> bool:
host_url = urlparse(request.host_url)
redirect_url = urlparse(urljoin(request.host_url, url))
return (
redirect_url.scheme in ("http", "https")
and host_url.netloc == redirect_url.netloc
)
def get_safe_redirect(url):
if url and is_safe_redirect_url(url):
return url
log.warning("Invalid redirect detected, falling back to index")
return current_app.appbuilder.get_url_for_index
def get_column_root_relation(column: str) -> str:
if "." in column:
return column.split(".")[0]
return column
def get_column_leaf(column: str) -> str:
if "." in column:
return column.split(".")[1]
return column
def is_column_dotted(column: str) -> bool:
return "." in column
def _wrap_lazy_formatter_gettext(
string: str, lazy_formater: Callable[[str], str], **variables: Any
) -> str:
return gettext(lazy_formater(string), **variables)
def lazy_formatter_gettext(
string: str, lazy_formatter: Callable[[str], str], **variables: Any
) -> LazyString:
"""Formats a lazy_gettext string with a custom function
Example::
def custom_formatter(string: str) -> str:
if current_app.config["CONDITIONAL_KEY"]:
string += " . Condition key is on"
return string
hello = lazy_formatter_gettext(u'Hello World', custom_formatter)
@app.route('/')
def index():
return unicode(hello)
"""
return LazyString(_wrap_lazy_formatter_gettext, string, lazy_formatter, **variables)
|
dpgaspar/Flask-AppBuilder
|
flask_appbuilder/utils/base.py
|
Python
|
bsd-3-clause
| 1,839 |
from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand
from codebase.actions import start_eclipse
class Command(NoArgsCommand):
help = "Start Eclipse"
def handle_noargs(self, **options):
start_eclipse()
|
bartdag/recodoc2
|
recodoc2/apps/codebase/management/commands/starteclipse.py
|
Python
|
bsd-3-clause
| 264 |
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "fiddle/examples.h"
// HASH=319f6b124458dcc0f9ce4d7bbde65810
REG_FIDDLE(Path_ConvertToNonInverseFillType, 256, 256, true, 0) {
#define nameValue(fill) { SkPath::fill, #fill }
void draw(SkCanvas* canvas) {
struct {
SkPath::FillType fill;
const char* name;
} fills[] = {
nameValue(kWinding_FillType),
nameValue(kEvenOdd_FillType),
nameValue(kInverseWinding_FillType),
nameValue(kInverseEvenOdd_FillType),
};
for (unsigned i = 0; i < SK_ARRAY_COUNT(fills); ++i) {
if (fills[i].fill != (SkPath::FillType) i) {
SkDebugf("fills array order does not match FillType enum order");
break;
}
SkDebugf("ConvertToNonInverseFillType(%s) == %s\n", fills[i].name,
fills[(int) SkPath::ConvertToNonInverseFillType(fills[i].fill)].name);
}
}
} // END FIDDLE
|
rubenvb/skia
|
docs/examples/Path_ConvertToNonInverseFillType.cpp
|
C++
|
bsd-3-clause
| 1,013 |
<?php
/**
* NOTE: Nama Class harus diawali Hurup Besar
* Server Linux : hurup besar/kecil bermasalah -case sensitif-
* Server Windows : hurup besar/kecil tidak bermasalah
* Author: -ptr.nov-
*/
namespace frontend\controllers;
/* VARIABLE BASE YII2 Author: -YII2- */
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/* VARIABLE PRIMARY JOIN/SEARCH/FILTER/SORT Author: -ptr.nov- */
//use app\models\hrd\Dept; /* TABLE CLASS JOIN */
//use app\models\hrd\DeptSearch; /* TABLE CLASS SEARCH */
/**
* HRD | CONTROLLER EMPLOYE .
*
*/
class OrderController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(['order']),
'actions' => [
//'delete' => ['post'],
'save' => ['post'],
],
],
];
}
/**
* ACTION INDEX
*/
public function actionIndex()
{
/* variable content View Employe Author: -ptr.nov- */
// $searchModel_Dept = new DeptSearch();
//$dataProvider_Dept = $searchModel_Dept->search(Yii::$app->request->queryParams);
return $this->render('index');
}
}
|
C12D/api
|
frontend/controllers/OrderController.php
|
PHP
|
bsd-3-clause
| 1,238 |
<?php
/**
* Created by PhpStorm.
* User: xiaoqiu
* Date: 15/6/15
* Time: 下午2:54
*/
namespace Blog\Controller\Admin;
use Zend\Cache\Storage\Adapter\Session;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\SessionManager;
use Zend\Session\Storage\ArrayStorage;
class IndexController extends AbstractActionController{
public function indexAction(){
$smarty = $this->getServiceLocator()->get('Smarty');
$smarty->display('admin/index.tpl');
exit;
}
public function loginAction(){
$request = $this->getRequest();
$smarty = $this->getServiceLocator()->get('Smarty');
if ($request->isGet()) {
$smarty->assign('error', null);
$smarty->display('admin/login.tpl');
}else{
$success = true;
$error = null;
$name = $request->getPost('name');
$password = $request->getPost('password');
$success = false;
if (!$name || !$password) {
$error = '用户名和密码不能为空';
} else {
$tableGateway = $this->getServiceLocator()->get('UserTable');
$users = $tableGateway->findByName($name);
if ($users->count() != 1) {
$error = '用户名或密码不正确';
} else {
$password_additional = $this->getServiceLocator()->get('config')['password_additional'];
$realPassword = md5($password . $password_additional);
if ($users->current()->getPassword() === $realPassword) {
$session = new SessionManager();
$user = $users->current();
$storage = new ArrayStorage(['user' => $user]);
if ($session->setStorage($storage)) {
$success = true;
} else {
$error = '写入session失败';
}
} else {
$error = '密码不正确';
}
}
}
if ($success) {
$this->redirect()->toUrl('/admin');
} else {
$smarty->assign('error', $error);
$smarty->display('admin/login.tpl');
}
}
}
}
|
329379172/zfblog
|
module/Blog/src/Blog/Controller/Admin/IndexController.php
|
PHP
|
bsd-3-clause
| 2,401 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.WaitCommand;
/**
*
* @author Admin
*/
public class SpinnerToggleWithWait extends CommandGroup
{
public SpinnerToggleWithWait()
{
addSequential(new SpinnerToggle());
addSequential(new WaitCommand(1.5));
}
}
|
FIRSTTeam102/chewie
|
src/edu/wpi/first/wpilibj/templates/commands/SpinnerToggleWithWait.java
|
Java
|
bsd-3-clause
| 498 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_
#define UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_
#include <windows.h>
#include <d3d11.h>
#include <dcomp.h>
#include <wrl/client.h>
#include "ui/gl/gl_export.h"
#include "ui/gl/gl_surface_egl.h"
namespace gl {
class GL_EXPORT DirectCompositionChildSurfaceWin : public GLSurfaceEGL {
public:
explicit DirectCompositionChildSurfaceWin(bool use_angle_texture_offset);
// GLSurfaceEGL implementation.
bool Initialize(GLSurfaceFormat format) override;
void Destroy() override;
gfx::Size GetSize() override;
bool IsOffscreen() override;
void* GetHandle() override;
gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
gfx::SurfaceOrigin GetOrigin() const override;
bool SupportsPostSubBuffer() override;
bool OnMakeCurrent(GLContext* context) override;
bool SupportsDCLayers() const override;
bool SetDrawRectangle(const gfx::Rect& rect) override;
gfx::Vector2d GetDrawOffset() const override;
void SetVSyncEnabled(bool enabled) override;
bool Resize(const gfx::Size& size,
float scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha) override;
bool SetEnableDCLayers(bool enable) override;
const Microsoft::WRL::ComPtr<IDCompositionSurface>& dcomp_surface() const {
return dcomp_surface_;
}
const Microsoft::WRL::ComPtr<IDXGISwapChain1>& swap_chain() const {
return swap_chain_;
}
uint64_t dcomp_surface_serial() const { return dcomp_surface_serial_; }
void SetDCompSurfaceForTesting(
Microsoft::WRL::ComPtr<IDCompositionSurface> surface);
protected:
~DirectCompositionChildSurfaceWin() override;
private:
// Release the texture that's currently being drawn to. If will_discard is
// true then the surface should be discarded without swapping any contents
// to it. Returns false if this fails.
bool ReleaseDrawTexture(bool will_discard);
const bool use_angle_texture_offset_;
gfx::Size size_ = gfx::Size(1, 1);
bool enable_dc_layers_ = false;
bool has_alpha_ = true;
bool vsync_enabled_ = true;
gfx::ColorSpace color_space_;
// This is a placeholder surface used when not rendering to the
// DirectComposition surface.
EGLSurface default_surface_ = 0;
// This is the real surface representing the backbuffer. It may be null
// outside of a BeginDraw/EndDraw pair.
EGLSurface real_surface_ = 0;
bool first_swap_ = true;
gfx::Rect swap_rect_;
gfx::Vector2d draw_offset_;
// This is a number that increments once for every EndDraw on a surface, and
// is used to determine when the contents have changed so Commit() needs to
// be called on the device.
uint64_t dcomp_surface_serial_ = 0;
Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_;
Microsoft::WRL::ComPtr<IDCompositionDevice2> dcomp_device_;
Microsoft::WRL::ComPtr<IDCompositionSurface> dcomp_surface_;
Microsoft::WRL::ComPtr<IDXGISwapChain1> swap_chain_;
Microsoft::WRL::ComPtr<ID3D11Texture2D> draw_texture_;
DISALLOW_COPY_AND_ASSIGN(DirectCompositionChildSurfaceWin);
};
} // namespace gl
#endif // UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_
|
endlessm/chromium-browser
|
ui/gl/direct_composition_child_surface_win.h
|
C
|
bsd-3-clause
| 3,339 |
<?php
namespace Test\Controller;
use Zend\Crypt\Password\Bcrypt;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel,
Test\Model\Test,
Test\Form\TestForm;
class TestController extends AbstractActionController
{
protected $testTable;
public function __autoload(){
$this->sessionControle();
}
public function sessionControle(){
if (!$this->zfcUserAuthentication()->hasIdentity()) {
return $this->redirect()->toRoute('zfcuser/login');
}
}
public function indexAction()
{
$this->sessionControle();
return new ViewModel(array(
'tests' => $this->getTestTable()->fetchAll() ));
}
public function addAction()
{
$this->sessionControle();
$form = new TestForm();
$form->get('submit')->setValue('Ajouter');
$request = $this->getRequest();
if ($request->isPost()) {
$test = new Test();
$form->setInputFilter($test->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$test->exchangeArray($form->getData());
$this->getTestTable()->saveTest($test);
// Redirect to list of tests
return $this->redirect()->toRoute('test');
}
}
return array('form' => $form,'menu' => 'test');
}
public function editAction()
{
$this->sessionControle();
$request = $this->getRequest();
if ($request->isPost()) {
$id=$_POST['idtest'];
}else{
$id = (int) $this->params()->fromRoute('id', 0);
}
if (!$id) {
return $this->redirect()->toRoute('test/add');
}
$test = $this->getTestTable()->getTest($id);
$form = new TestForm();
$form->bind($test);
$form->get('submit')->setAttribute('value','Enregistrer');
if ($request->isPost()) {
$form->setInputFilter($test->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getTestTable()->saveTest($form->getData());
// Redirect to list of tests
return $this->redirect()->toRoute('test');
}
}
return array(
'idtest' => $id,
'form' => $form
);
}
public function deleteAction()
{
$this->sessionControle();
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('test');
}
$request = $this->getRequest();
$this->getTestTable()->deleteTest($id);
return $this->redirect()->toRoute('test');
}
public function getTestTable()
{
if (!$this->testTable) {
$sm = $this->getServiceLocator();
$this->testTable = $sm->get('Test\Model\TestTable');
}
return $this->testTable;
}
}
|
haouach/SBS-ZF2
|
module/Test/src/Test/Controller/TestController.php
|
PHP
|
bsd-3-clause
| 2,710 |
from sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("SVR_linear" , "boston" , "mssql")
|
antoinecarme/sklearn2sql_heroku
|
tests/regression/boston/ws_boston_SVR_linear_mssql_code_gen.py
|
Python
|
bsd-3-clause
| 123 |
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file includes the platform-specific initializers.
*/
#include "alarm_qorvo.h"
#include "platform_qorvo.h"
#include "radio_qorvo.h"
#include "random_qorvo.h"
#include "uart_qorvo.h"
#include <openthread/tasklet.h>
#include <openthread/platform/uart.h>
#include "stdio.h"
#include "stdlib.h"
static otInstance *localInstance = NULL;
#ifdef QORVO_USE_ROM
extern void flash_jump_gpJumpTables_GetRomVersion(void);
#endif // QORVO_USE_ROM
uint8_t qorvoPlatGotoSleepCheck(void)
{
if (localInstance)
{
return !otTaskletsArePending(localInstance);
}
else
{
return true;
}
}
void otSysInit(int argc, char *argv[])
{
OT_UNUSED_VARIABLE(argc);
OT_UNUSED_VARIABLE(argv);
#ifdef QORVO_USE_ROM
flash_jump_gpJumpTables_GetRomVersion();
#endif // QORVO_USE_ROM
qorvoPlatInit((qorvoPlatGotoSleepCheckCallback_t)qorvoPlatGotoSleepCheck);
qorvoUartInit();
qorvoAlarmInit();
qorvoRandomInit();
qorvoRadioInit();
}
bool otSysPseudoResetWasRequested(void)
{
return false;
}
void otSysProcessDrivers(otInstance *aInstance)
{
if (localInstance == NULL)
{
// local copy in case we need to perform a callback.
localInstance = aInstance;
}
qorvoPlatMainLoop(!otTaskletsArePending(aInstance));
}
|
abtink/openthread
|
examples/platforms/qpg6095/platform.c
|
C
|
bsd-3-clause
| 2,928 |
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <grpc/support/port_platform.h>
#ifdef GPR_WINDOWS
#include "rb_grpc_imports.generated.h"
grpc_raw_byte_buffer_create_type grpc_raw_byte_buffer_create_import;
grpc_raw_compressed_byte_buffer_create_type grpc_raw_compressed_byte_buffer_create_import;
grpc_byte_buffer_copy_type grpc_byte_buffer_copy_import;
grpc_byte_buffer_length_type grpc_byte_buffer_length_import;
grpc_byte_buffer_destroy_type grpc_byte_buffer_destroy_import;
grpc_byte_buffer_reader_init_type grpc_byte_buffer_reader_init_import;
grpc_byte_buffer_reader_destroy_type grpc_byte_buffer_reader_destroy_import;
grpc_byte_buffer_reader_next_type grpc_byte_buffer_reader_next_import;
grpc_byte_buffer_reader_readall_type grpc_byte_buffer_reader_readall_import;
grpc_raw_byte_buffer_from_reader_type grpc_raw_byte_buffer_from_reader_import;
census_initialize_type census_initialize_import;
census_shutdown_type census_shutdown_import;
census_supported_type census_supported_import;
census_enabled_type census_enabled_import;
census_context_create_type census_context_create_import;
census_context_destroy_type census_context_destroy_import;
census_context_get_status_type census_context_get_status_import;
census_context_initialize_iterator_type census_context_initialize_iterator_import;
census_context_next_tag_type census_context_next_tag_import;
census_context_get_tag_type census_context_get_tag_import;
census_context_encode_type census_context_encode_import;
census_context_decode_type census_context_decode_import;
census_trace_mask_type census_trace_mask_import;
census_set_trace_mask_type census_set_trace_mask_import;
census_start_rpc_op_timestamp_type census_start_rpc_op_timestamp_import;
census_start_client_rpc_op_type census_start_client_rpc_op_import;
census_set_rpc_client_peer_type census_set_rpc_client_peer_import;
census_start_server_rpc_op_type census_start_server_rpc_op_import;
census_start_op_type census_start_op_import;
census_end_op_type census_end_op_import;
census_trace_print_type census_trace_print_import;
census_trace_scan_start_type census_trace_scan_start_import;
census_get_trace_record_type census_get_trace_record_import;
census_trace_scan_end_type census_trace_scan_end_import;
census_define_resource_type census_define_resource_import;
census_delete_resource_type census_delete_resource_import;
census_resource_id_type census_resource_id_import;
census_record_values_type census_record_values_import;
grpc_compression_algorithm_parse_type grpc_compression_algorithm_parse_import;
grpc_compression_algorithm_name_type grpc_compression_algorithm_name_import;
grpc_compression_algorithm_for_level_type grpc_compression_algorithm_for_level_import;
grpc_compression_options_init_type grpc_compression_options_init_import;
grpc_compression_options_enable_algorithm_type grpc_compression_options_enable_algorithm_import;
grpc_compression_options_disable_algorithm_type grpc_compression_options_disable_algorithm_import;
grpc_compression_options_is_algorithm_enabled_type grpc_compression_options_is_algorithm_enabled_import;
grpc_metadata_array_init_type grpc_metadata_array_init_import;
grpc_metadata_array_destroy_type grpc_metadata_array_destroy_import;
grpc_call_details_init_type grpc_call_details_init_import;
grpc_call_details_destroy_type grpc_call_details_destroy_import;
grpc_register_plugin_type grpc_register_plugin_import;
grpc_init_type grpc_init_import;
grpc_shutdown_type grpc_shutdown_import;
grpc_version_string_type grpc_version_string_import;
grpc_g_stands_for_type grpc_g_stands_for_import;
grpc_completion_queue_create_type grpc_completion_queue_create_import;
grpc_completion_queue_next_type grpc_completion_queue_next_import;
grpc_completion_queue_pluck_type grpc_completion_queue_pluck_import;
grpc_completion_queue_shutdown_type grpc_completion_queue_shutdown_import;
grpc_completion_queue_destroy_type grpc_completion_queue_destroy_import;
grpc_alarm_create_type grpc_alarm_create_import;
grpc_alarm_cancel_type grpc_alarm_cancel_import;
grpc_alarm_destroy_type grpc_alarm_destroy_import;
grpc_channel_check_connectivity_state_type grpc_channel_check_connectivity_state_import;
grpc_channel_watch_connectivity_state_type grpc_channel_watch_connectivity_state_import;
grpc_channel_create_call_type grpc_channel_create_call_import;
grpc_channel_ping_type grpc_channel_ping_import;
grpc_channel_register_call_type grpc_channel_register_call_import;
grpc_channel_create_registered_call_type grpc_channel_create_registered_call_import;
grpc_call_start_batch_type grpc_call_start_batch_import;
grpc_call_get_peer_type grpc_call_get_peer_import;
grpc_call_set_load_reporting_cost_context_type grpc_call_set_load_reporting_cost_context_import;
grpc_census_call_set_context_type grpc_census_call_set_context_import;
grpc_census_call_get_context_type grpc_census_call_get_context_import;
grpc_channel_get_target_type grpc_channel_get_target_import;
grpc_channel_get_info_type grpc_channel_get_info_import;
grpc_insecure_channel_create_type grpc_insecure_channel_create_import;
grpc_lame_client_channel_create_type grpc_lame_client_channel_create_import;
grpc_channel_destroy_type grpc_channel_destroy_import;
grpc_call_cancel_type grpc_call_cancel_import;
grpc_call_cancel_with_status_type grpc_call_cancel_with_status_import;
grpc_call_destroy_type grpc_call_destroy_import;
grpc_server_request_call_type grpc_server_request_call_import;
grpc_server_register_method_type grpc_server_register_method_import;
grpc_server_request_registered_call_type grpc_server_request_registered_call_import;
grpc_server_create_type grpc_server_create_import;
grpc_server_register_completion_queue_type grpc_server_register_completion_queue_import;
grpc_server_register_non_listening_completion_queue_type grpc_server_register_non_listening_completion_queue_import;
grpc_server_add_insecure_http2_port_type grpc_server_add_insecure_http2_port_import;
grpc_server_start_type grpc_server_start_import;
grpc_server_shutdown_and_notify_type grpc_server_shutdown_and_notify_import;
grpc_server_cancel_all_calls_type grpc_server_cancel_all_calls_import;
grpc_server_destroy_type grpc_server_destroy_import;
grpc_tracer_set_enabled_type grpc_tracer_set_enabled_import;
grpc_header_key_is_legal_type grpc_header_key_is_legal_import;
grpc_header_nonbin_value_is_legal_type grpc_header_nonbin_value_is_legal_import;
grpc_is_binary_header_type grpc_is_binary_header_import;
grpc_call_error_to_string_type grpc_call_error_to_string_import;
grpc_resource_quota_create_type grpc_resource_quota_create_import;
grpc_resource_quota_ref_type grpc_resource_quota_ref_import;
grpc_resource_quota_unref_type grpc_resource_quota_unref_import;
grpc_resource_quota_resize_type grpc_resource_quota_resize_import;
grpc_resource_quota_arg_vtable_type grpc_resource_quota_arg_vtable_import;
grpc_insecure_channel_create_from_fd_type grpc_insecure_channel_create_from_fd_import;
grpc_server_add_insecure_channel_from_fd_type grpc_server_add_insecure_channel_from_fd_import;
grpc_use_signal_type grpc_use_signal_import;
grpc_auth_property_iterator_next_type grpc_auth_property_iterator_next_import;
grpc_auth_context_property_iterator_type grpc_auth_context_property_iterator_import;
grpc_auth_context_peer_identity_type grpc_auth_context_peer_identity_import;
grpc_auth_context_find_properties_by_name_type grpc_auth_context_find_properties_by_name_import;
grpc_auth_context_peer_identity_property_name_type grpc_auth_context_peer_identity_property_name_import;
grpc_auth_context_peer_is_authenticated_type grpc_auth_context_peer_is_authenticated_import;
grpc_call_auth_context_type grpc_call_auth_context_import;
grpc_auth_context_release_type grpc_auth_context_release_import;
grpc_auth_context_add_property_type grpc_auth_context_add_property_import;
grpc_auth_context_add_cstring_property_type grpc_auth_context_add_cstring_property_import;
grpc_auth_context_set_peer_identity_property_name_type grpc_auth_context_set_peer_identity_property_name_import;
grpc_channel_credentials_release_type grpc_channel_credentials_release_import;
grpc_google_default_credentials_create_type grpc_google_default_credentials_create_import;
grpc_set_ssl_roots_override_callback_type grpc_set_ssl_roots_override_callback_import;
grpc_ssl_credentials_create_type grpc_ssl_credentials_create_import;
grpc_call_credentials_release_type grpc_call_credentials_release_import;
grpc_composite_channel_credentials_create_type grpc_composite_channel_credentials_create_import;
grpc_composite_call_credentials_create_type grpc_composite_call_credentials_create_import;
grpc_google_compute_engine_credentials_create_type grpc_google_compute_engine_credentials_create_import;
grpc_max_auth_token_lifetime_type grpc_max_auth_token_lifetime_import;
grpc_service_account_jwt_access_credentials_create_type grpc_service_account_jwt_access_credentials_create_import;
grpc_google_refresh_token_credentials_create_type grpc_google_refresh_token_credentials_create_import;
grpc_access_token_credentials_create_type grpc_access_token_credentials_create_import;
grpc_google_iam_credentials_create_type grpc_google_iam_credentials_create_import;
grpc_metadata_credentials_create_from_plugin_type grpc_metadata_credentials_create_from_plugin_import;
grpc_secure_channel_create_type grpc_secure_channel_create_import;
grpc_server_credentials_release_type grpc_server_credentials_release_import;
grpc_ssl_server_credentials_create_type grpc_ssl_server_credentials_create_import;
grpc_ssl_server_credentials_create_ex_type grpc_ssl_server_credentials_create_ex_import;
grpc_server_add_secure_http2_port_type grpc_server_add_secure_http2_port_import;
grpc_call_set_credentials_type grpc_call_set_credentials_import;
grpc_server_credentials_set_auth_metadata_processor_type grpc_server_credentials_set_auth_metadata_processor_import;
grpc_slice_ref_type grpc_slice_ref_import;
grpc_slice_unref_type grpc_slice_unref_import;
grpc_slice_new_type grpc_slice_new_import;
grpc_slice_new_with_user_data_type grpc_slice_new_with_user_data_import;
grpc_slice_new_with_len_type grpc_slice_new_with_len_import;
grpc_slice_malloc_type grpc_slice_malloc_import;
grpc_slice_intern_type grpc_slice_intern_import;
grpc_slice_from_copied_string_type grpc_slice_from_copied_string_import;
grpc_slice_from_copied_buffer_type grpc_slice_from_copied_buffer_import;
grpc_slice_from_static_string_type grpc_slice_from_static_string_import;
grpc_slice_from_static_buffer_type grpc_slice_from_static_buffer_import;
grpc_slice_sub_type grpc_slice_sub_import;
grpc_slice_sub_no_ref_type grpc_slice_sub_no_ref_import;
grpc_slice_split_tail_type grpc_slice_split_tail_import;
grpc_slice_split_head_type grpc_slice_split_head_import;
grpc_empty_slice_type grpc_empty_slice_import;
grpc_slice_default_hash_impl_type grpc_slice_default_hash_impl_import;
grpc_slice_default_eq_impl_type grpc_slice_default_eq_impl_import;
grpc_slice_eq_type grpc_slice_eq_import;
grpc_slice_cmp_type grpc_slice_cmp_import;
grpc_slice_str_cmp_type grpc_slice_str_cmp_import;
grpc_slice_buf_cmp_type grpc_slice_buf_cmp_import;
grpc_slice_buf_start_eq_type grpc_slice_buf_start_eq_import;
grpc_slice_rchr_type grpc_slice_rchr_import;
grpc_slice_chr_type grpc_slice_chr_import;
grpc_slice_slice_type grpc_slice_slice_import;
grpc_slice_hash_type grpc_slice_hash_import;
grpc_slice_is_equivalent_type grpc_slice_is_equivalent_import;
grpc_slice_dup_type grpc_slice_dup_import;
grpc_slice_to_c_string_type grpc_slice_to_c_string_import;
grpc_slice_buffer_init_type grpc_slice_buffer_init_import;
grpc_slice_buffer_destroy_type grpc_slice_buffer_destroy_import;
grpc_slice_buffer_add_type grpc_slice_buffer_add_import;
grpc_slice_buffer_add_indexed_type grpc_slice_buffer_add_indexed_import;
grpc_slice_buffer_addn_type grpc_slice_buffer_addn_import;
grpc_slice_buffer_tiny_add_type grpc_slice_buffer_tiny_add_import;
grpc_slice_buffer_pop_type grpc_slice_buffer_pop_import;
grpc_slice_buffer_reset_and_unref_type grpc_slice_buffer_reset_and_unref_import;
grpc_slice_buffer_swap_type grpc_slice_buffer_swap_import;
grpc_slice_buffer_move_into_type grpc_slice_buffer_move_into_import;
grpc_slice_buffer_trim_end_type grpc_slice_buffer_trim_end_import;
grpc_slice_buffer_move_first_type grpc_slice_buffer_move_first_import;
grpc_slice_buffer_move_first_into_buffer_type grpc_slice_buffer_move_first_into_buffer_import;
grpc_slice_buffer_take_first_type grpc_slice_buffer_take_first_import;
grpc_slice_buffer_undo_take_first_type grpc_slice_buffer_undo_take_first_import;
gpr_malloc_type gpr_malloc_import;
gpr_zalloc_type gpr_zalloc_import;
gpr_free_type gpr_free_import;
gpr_realloc_type gpr_realloc_import;
gpr_malloc_aligned_type gpr_malloc_aligned_import;
gpr_free_aligned_type gpr_free_aligned_import;
gpr_set_allocation_functions_type gpr_set_allocation_functions_import;
gpr_get_allocation_functions_type gpr_get_allocation_functions_import;
gpr_avl_create_type gpr_avl_create_import;
gpr_avl_ref_type gpr_avl_ref_import;
gpr_avl_unref_type gpr_avl_unref_import;
gpr_avl_add_type gpr_avl_add_import;
gpr_avl_remove_type gpr_avl_remove_import;
gpr_avl_get_type gpr_avl_get_import;
gpr_avl_maybe_get_type gpr_avl_maybe_get_import;
gpr_avl_is_empty_type gpr_avl_is_empty_import;
gpr_cmdline_create_type gpr_cmdline_create_import;
gpr_cmdline_add_int_type gpr_cmdline_add_int_import;
gpr_cmdline_add_flag_type gpr_cmdline_add_flag_import;
gpr_cmdline_add_string_type gpr_cmdline_add_string_import;
gpr_cmdline_on_extra_arg_type gpr_cmdline_on_extra_arg_import;
gpr_cmdline_set_survive_failure_type gpr_cmdline_set_survive_failure_import;
gpr_cmdline_parse_type gpr_cmdline_parse_import;
gpr_cmdline_destroy_type gpr_cmdline_destroy_import;
gpr_cmdline_usage_string_type gpr_cmdline_usage_string_import;
gpr_cpu_num_cores_type gpr_cpu_num_cores_import;
gpr_cpu_current_cpu_type gpr_cpu_current_cpu_import;
gpr_histogram_create_type gpr_histogram_create_import;
gpr_histogram_destroy_type gpr_histogram_destroy_import;
gpr_histogram_add_type gpr_histogram_add_import;
gpr_histogram_merge_type gpr_histogram_merge_import;
gpr_histogram_percentile_type gpr_histogram_percentile_import;
gpr_histogram_mean_type gpr_histogram_mean_import;
gpr_histogram_stddev_type gpr_histogram_stddev_import;
gpr_histogram_variance_type gpr_histogram_variance_import;
gpr_histogram_maximum_type gpr_histogram_maximum_import;
gpr_histogram_minimum_type gpr_histogram_minimum_import;
gpr_histogram_count_type gpr_histogram_count_import;
gpr_histogram_sum_type gpr_histogram_sum_import;
gpr_histogram_sum_of_squares_type gpr_histogram_sum_of_squares_import;
gpr_histogram_get_contents_type gpr_histogram_get_contents_import;
gpr_histogram_merge_contents_type gpr_histogram_merge_contents_import;
gpr_join_host_port_type gpr_join_host_port_import;
gpr_split_host_port_type gpr_split_host_port_import;
gpr_log_type gpr_log_import;
gpr_log_message_type gpr_log_message_import;
gpr_set_log_verbosity_type gpr_set_log_verbosity_import;
gpr_log_verbosity_init_type gpr_log_verbosity_init_import;
gpr_set_log_function_type gpr_set_log_function_import;
gpr_format_message_type gpr_format_message_import;
gpr_strdup_type gpr_strdup_import;
gpr_asprintf_type gpr_asprintf_import;
gpr_subprocess_binary_extension_type gpr_subprocess_binary_extension_import;
gpr_subprocess_create_type gpr_subprocess_create_import;
gpr_subprocess_destroy_type gpr_subprocess_destroy_import;
gpr_subprocess_join_type gpr_subprocess_join_import;
gpr_subprocess_interrupt_type gpr_subprocess_interrupt_import;
gpr_mu_init_type gpr_mu_init_import;
gpr_mu_destroy_type gpr_mu_destroy_import;
gpr_mu_lock_type gpr_mu_lock_import;
gpr_mu_unlock_type gpr_mu_unlock_import;
gpr_mu_trylock_type gpr_mu_trylock_import;
gpr_cv_init_type gpr_cv_init_import;
gpr_cv_destroy_type gpr_cv_destroy_import;
gpr_cv_wait_type gpr_cv_wait_import;
gpr_cv_signal_type gpr_cv_signal_import;
gpr_cv_broadcast_type gpr_cv_broadcast_import;
gpr_once_init_type gpr_once_init_import;
gpr_event_init_type gpr_event_init_import;
gpr_event_set_type gpr_event_set_import;
gpr_event_get_type gpr_event_get_import;
gpr_event_wait_type gpr_event_wait_import;
gpr_ref_init_type gpr_ref_init_import;
gpr_ref_type gpr_ref_import;
gpr_ref_non_zero_type gpr_ref_non_zero_import;
gpr_refn_type gpr_refn_import;
gpr_unref_type gpr_unref_import;
gpr_stats_init_type gpr_stats_init_import;
gpr_stats_inc_type gpr_stats_inc_import;
gpr_stats_read_type gpr_stats_read_import;
gpr_thd_new_type gpr_thd_new_import;
gpr_thd_options_default_type gpr_thd_options_default_import;
gpr_thd_options_set_detached_type gpr_thd_options_set_detached_import;
gpr_thd_options_set_joinable_type gpr_thd_options_set_joinable_import;
gpr_thd_options_is_detached_type gpr_thd_options_is_detached_import;
gpr_thd_options_is_joinable_type gpr_thd_options_is_joinable_import;
gpr_thd_currentid_type gpr_thd_currentid_import;
gpr_thd_join_type gpr_thd_join_import;
gpr_time_0_type gpr_time_0_import;
gpr_inf_future_type gpr_inf_future_import;
gpr_inf_past_type gpr_inf_past_import;
gpr_time_init_type gpr_time_init_import;
gpr_now_type gpr_now_import;
gpr_convert_clock_type_type gpr_convert_clock_type_import;
gpr_time_cmp_type gpr_time_cmp_import;
gpr_time_max_type gpr_time_max_import;
gpr_time_min_type gpr_time_min_import;
gpr_time_add_type gpr_time_add_import;
gpr_time_sub_type gpr_time_sub_import;
gpr_time_from_micros_type gpr_time_from_micros_import;
gpr_time_from_nanos_type gpr_time_from_nanos_import;
gpr_time_from_millis_type gpr_time_from_millis_import;
gpr_time_from_seconds_type gpr_time_from_seconds_import;
gpr_time_from_minutes_type gpr_time_from_minutes_import;
gpr_time_from_hours_type gpr_time_from_hours_import;
gpr_time_to_millis_type gpr_time_to_millis_import;
gpr_time_similar_type gpr_time_similar_import;
gpr_sleep_until_type gpr_sleep_until_import;
gpr_timespec_to_micros_type gpr_timespec_to_micros_import;
void grpc_rb_load_imports(HMODULE library) {
grpc_raw_byte_buffer_create_import = (grpc_raw_byte_buffer_create_type) GetProcAddress(library, "grpc_raw_byte_buffer_create");
grpc_raw_compressed_byte_buffer_create_import = (grpc_raw_compressed_byte_buffer_create_type) GetProcAddress(library, "grpc_raw_compressed_byte_buffer_create");
grpc_byte_buffer_copy_import = (grpc_byte_buffer_copy_type) GetProcAddress(library, "grpc_byte_buffer_copy");
grpc_byte_buffer_length_import = (grpc_byte_buffer_length_type) GetProcAddress(library, "grpc_byte_buffer_length");
grpc_byte_buffer_destroy_import = (grpc_byte_buffer_destroy_type) GetProcAddress(library, "grpc_byte_buffer_destroy");
grpc_byte_buffer_reader_init_import = (grpc_byte_buffer_reader_init_type) GetProcAddress(library, "grpc_byte_buffer_reader_init");
grpc_byte_buffer_reader_destroy_import = (grpc_byte_buffer_reader_destroy_type) GetProcAddress(library, "grpc_byte_buffer_reader_destroy");
grpc_byte_buffer_reader_next_import = (grpc_byte_buffer_reader_next_type) GetProcAddress(library, "grpc_byte_buffer_reader_next");
grpc_byte_buffer_reader_readall_import = (grpc_byte_buffer_reader_readall_type) GetProcAddress(library, "grpc_byte_buffer_reader_readall");
grpc_raw_byte_buffer_from_reader_import = (grpc_raw_byte_buffer_from_reader_type) GetProcAddress(library, "grpc_raw_byte_buffer_from_reader");
census_initialize_import = (census_initialize_type) GetProcAddress(library, "census_initialize");
census_shutdown_import = (census_shutdown_type) GetProcAddress(library, "census_shutdown");
census_supported_import = (census_supported_type) GetProcAddress(library, "census_supported");
census_enabled_import = (census_enabled_type) GetProcAddress(library, "census_enabled");
census_context_create_import = (census_context_create_type) GetProcAddress(library, "census_context_create");
census_context_destroy_import = (census_context_destroy_type) GetProcAddress(library, "census_context_destroy");
census_context_get_status_import = (census_context_get_status_type) GetProcAddress(library, "census_context_get_status");
census_context_initialize_iterator_import = (census_context_initialize_iterator_type) GetProcAddress(library, "census_context_initialize_iterator");
census_context_next_tag_import = (census_context_next_tag_type) GetProcAddress(library, "census_context_next_tag");
census_context_get_tag_import = (census_context_get_tag_type) GetProcAddress(library, "census_context_get_tag");
census_context_encode_import = (census_context_encode_type) GetProcAddress(library, "census_context_encode");
census_context_decode_import = (census_context_decode_type) GetProcAddress(library, "census_context_decode");
census_trace_mask_import = (census_trace_mask_type) GetProcAddress(library, "census_trace_mask");
census_set_trace_mask_import = (census_set_trace_mask_type) GetProcAddress(library, "census_set_trace_mask");
census_start_rpc_op_timestamp_import = (census_start_rpc_op_timestamp_type) GetProcAddress(library, "census_start_rpc_op_timestamp");
census_start_client_rpc_op_import = (census_start_client_rpc_op_type) GetProcAddress(library, "census_start_client_rpc_op");
census_set_rpc_client_peer_import = (census_set_rpc_client_peer_type) GetProcAddress(library, "census_set_rpc_client_peer");
census_start_server_rpc_op_import = (census_start_server_rpc_op_type) GetProcAddress(library, "census_start_server_rpc_op");
census_start_op_import = (census_start_op_type) GetProcAddress(library, "census_start_op");
census_end_op_import = (census_end_op_type) GetProcAddress(library, "census_end_op");
census_trace_print_import = (census_trace_print_type) GetProcAddress(library, "census_trace_print");
census_trace_scan_start_import = (census_trace_scan_start_type) GetProcAddress(library, "census_trace_scan_start");
census_get_trace_record_import = (census_get_trace_record_type) GetProcAddress(library, "census_get_trace_record");
census_trace_scan_end_import = (census_trace_scan_end_type) GetProcAddress(library, "census_trace_scan_end");
census_define_resource_import = (census_define_resource_type) GetProcAddress(library, "census_define_resource");
census_delete_resource_import = (census_delete_resource_type) GetProcAddress(library, "census_delete_resource");
census_resource_id_import = (census_resource_id_type) GetProcAddress(library, "census_resource_id");
census_record_values_import = (census_record_values_type) GetProcAddress(library, "census_record_values");
grpc_compression_algorithm_parse_import = (grpc_compression_algorithm_parse_type) GetProcAddress(library, "grpc_compression_algorithm_parse");
grpc_compression_algorithm_name_import = (grpc_compression_algorithm_name_type) GetProcAddress(library, "grpc_compression_algorithm_name");
grpc_compression_algorithm_for_level_import = (grpc_compression_algorithm_for_level_type) GetProcAddress(library, "grpc_compression_algorithm_for_level");
grpc_compression_options_init_import = (grpc_compression_options_init_type) GetProcAddress(library, "grpc_compression_options_init");
grpc_compression_options_enable_algorithm_import = (grpc_compression_options_enable_algorithm_type) GetProcAddress(library, "grpc_compression_options_enable_algorithm");
grpc_compression_options_disable_algorithm_import = (grpc_compression_options_disable_algorithm_type) GetProcAddress(library, "grpc_compression_options_disable_algorithm");
grpc_compression_options_is_algorithm_enabled_import = (grpc_compression_options_is_algorithm_enabled_type) GetProcAddress(library, "grpc_compression_options_is_algorithm_enabled");
grpc_metadata_array_init_import = (grpc_metadata_array_init_type) GetProcAddress(library, "grpc_metadata_array_init");
grpc_metadata_array_destroy_import = (grpc_metadata_array_destroy_type) GetProcAddress(library, "grpc_metadata_array_destroy");
grpc_call_details_init_import = (grpc_call_details_init_type) GetProcAddress(library, "grpc_call_details_init");
grpc_call_details_destroy_import = (grpc_call_details_destroy_type) GetProcAddress(library, "grpc_call_details_destroy");
grpc_register_plugin_import = (grpc_register_plugin_type) GetProcAddress(library, "grpc_register_plugin");
grpc_init_import = (grpc_init_type) GetProcAddress(library, "grpc_init");
grpc_shutdown_import = (grpc_shutdown_type) GetProcAddress(library, "grpc_shutdown");
grpc_version_string_import = (grpc_version_string_type) GetProcAddress(library, "grpc_version_string");
grpc_g_stands_for_import = (grpc_g_stands_for_type) GetProcAddress(library, "grpc_g_stands_for");
grpc_completion_queue_create_import = (grpc_completion_queue_create_type) GetProcAddress(library, "grpc_completion_queue_create");
grpc_completion_queue_next_import = (grpc_completion_queue_next_type) GetProcAddress(library, "grpc_completion_queue_next");
grpc_completion_queue_pluck_import = (grpc_completion_queue_pluck_type) GetProcAddress(library, "grpc_completion_queue_pluck");
grpc_completion_queue_shutdown_import = (grpc_completion_queue_shutdown_type) GetProcAddress(library, "grpc_completion_queue_shutdown");
grpc_completion_queue_destroy_import = (grpc_completion_queue_destroy_type) GetProcAddress(library, "grpc_completion_queue_destroy");
grpc_alarm_create_import = (grpc_alarm_create_type) GetProcAddress(library, "grpc_alarm_create");
grpc_alarm_cancel_import = (grpc_alarm_cancel_type) GetProcAddress(library, "grpc_alarm_cancel");
grpc_alarm_destroy_import = (grpc_alarm_destroy_type) GetProcAddress(library, "grpc_alarm_destroy");
grpc_channel_check_connectivity_state_import = (grpc_channel_check_connectivity_state_type) GetProcAddress(library, "grpc_channel_check_connectivity_state");
grpc_channel_watch_connectivity_state_import = (grpc_channel_watch_connectivity_state_type) GetProcAddress(library, "grpc_channel_watch_connectivity_state");
grpc_channel_create_call_import = (grpc_channel_create_call_type) GetProcAddress(library, "grpc_channel_create_call");
grpc_channel_ping_import = (grpc_channel_ping_type) GetProcAddress(library, "grpc_channel_ping");
grpc_channel_register_call_import = (grpc_channel_register_call_type) GetProcAddress(library, "grpc_channel_register_call");
grpc_channel_create_registered_call_import = (grpc_channel_create_registered_call_type) GetProcAddress(library, "grpc_channel_create_registered_call");
grpc_call_start_batch_import = (grpc_call_start_batch_type) GetProcAddress(library, "grpc_call_start_batch");
grpc_call_get_peer_import = (grpc_call_get_peer_type) GetProcAddress(library, "grpc_call_get_peer");
grpc_call_set_load_reporting_cost_context_import = (grpc_call_set_load_reporting_cost_context_type) GetProcAddress(library, "grpc_call_set_load_reporting_cost_context");
grpc_census_call_set_context_import = (grpc_census_call_set_context_type) GetProcAddress(library, "grpc_census_call_set_context");
grpc_census_call_get_context_import = (grpc_census_call_get_context_type) GetProcAddress(library, "grpc_census_call_get_context");
grpc_channel_get_target_import = (grpc_channel_get_target_type) GetProcAddress(library, "grpc_channel_get_target");
grpc_channel_get_info_import = (grpc_channel_get_info_type) GetProcAddress(library, "grpc_channel_get_info");
grpc_insecure_channel_create_import = (grpc_insecure_channel_create_type) GetProcAddress(library, "grpc_insecure_channel_create");
grpc_lame_client_channel_create_import = (grpc_lame_client_channel_create_type) GetProcAddress(library, "grpc_lame_client_channel_create");
grpc_channel_destroy_import = (grpc_channel_destroy_type) GetProcAddress(library, "grpc_channel_destroy");
grpc_call_cancel_import = (grpc_call_cancel_type) GetProcAddress(library, "grpc_call_cancel");
grpc_call_cancel_with_status_import = (grpc_call_cancel_with_status_type) GetProcAddress(library, "grpc_call_cancel_with_status");
grpc_call_destroy_import = (grpc_call_destroy_type) GetProcAddress(library, "grpc_call_destroy");
grpc_server_request_call_import = (grpc_server_request_call_type) GetProcAddress(library, "grpc_server_request_call");
grpc_server_register_method_import = (grpc_server_register_method_type) GetProcAddress(library, "grpc_server_register_method");
grpc_server_request_registered_call_import = (grpc_server_request_registered_call_type) GetProcAddress(library, "grpc_server_request_registered_call");
grpc_server_create_import = (grpc_server_create_type) GetProcAddress(library, "grpc_server_create");
grpc_server_register_completion_queue_import = (grpc_server_register_completion_queue_type) GetProcAddress(library, "grpc_server_register_completion_queue");
grpc_server_register_non_listening_completion_queue_import = (grpc_server_register_non_listening_completion_queue_type) GetProcAddress(library, "grpc_server_register_non_listening_completion_queue");
grpc_server_add_insecure_http2_port_import = (grpc_server_add_insecure_http2_port_type) GetProcAddress(library, "grpc_server_add_insecure_http2_port");
grpc_server_start_import = (grpc_server_start_type) GetProcAddress(library, "grpc_server_start");
grpc_server_shutdown_and_notify_import = (grpc_server_shutdown_and_notify_type) GetProcAddress(library, "grpc_server_shutdown_and_notify");
grpc_server_cancel_all_calls_import = (grpc_server_cancel_all_calls_type) GetProcAddress(library, "grpc_server_cancel_all_calls");
grpc_server_destroy_import = (grpc_server_destroy_type) GetProcAddress(library, "grpc_server_destroy");
grpc_tracer_set_enabled_import = (grpc_tracer_set_enabled_type) GetProcAddress(library, "grpc_tracer_set_enabled");
grpc_header_key_is_legal_import = (grpc_header_key_is_legal_type) GetProcAddress(library, "grpc_header_key_is_legal");
grpc_header_nonbin_value_is_legal_import = (grpc_header_nonbin_value_is_legal_type) GetProcAddress(library, "grpc_header_nonbin_value_is_legal");
grpc_is_binary_header_import = (grpc_is_binary_header_type) GetProcAddress(library, "grpc_is_binary_header");
grpc_call_error_to_string_import = (grpc_call_error_to_string_type) GetProcAddress(library, "grpc_call_error_to_string");
grpc_resource_quota_create_import = (grpc_resource_quota_create_type) GetProcAddress(library, "grpc_resource_quota_create");
grpc_resource_quota_ref_import = (grpc_resource_quota_ref_type) GetProcAddress(library, "grpc_resource_quota_ref");
grpc_resource_quota_unref_import = (grpc_resource_quota_unref_type) GetProcAddress(library, "grpc_resource_quota_unref");
grpc_resource_quota_resize_import = (grpc_resource_quota_resize_type) GetProcAddress(library, "grpc_resource_quota_resize");
grpc_resource_quota_arg_vtable_import = (grpc_resource_quota_arg_vtable_type) GetProcAddress(library, "grpc_resource_quota_arg_vtable");
grpc_insecure_channel_create_from_fd_import = (grpc_insecure_channel_create_from_fd_type) GetProcAddress(library, "grpc_insecure_channel_create_from_fd");
grpc_server_add_insecure_channel_from_fd_import = (grpc_server_add_insecure_channel_from_fd_type) GetProcAddress(library, "grpc_server_add_insecure_channel_from_fd");
grpc_use_signal_import = (grpc_use_signal_type) GetProcAddress(library, "grpc_use_signal");
grpc_auth_property_iterator_next_import = (grpc_auth_property_iterator_next_type) GetProcAddress(library, "grpc_auth_property_iterator_next");
grpc_auth_context_property_iterator_import = (grpc_auth_context_property_iterator_type) GetProcAddress(library, "grpc_auth_context_property_iterator");
grpc_auth_context_peer_identity_import = (grpc_auth_context_peer_identity_type) GetProcAddress(library, "grpc_auth_context_peer_identity");
grpc_auth_context_find_properties_by_name_import = (grpc_auth_context_find_properties_by_name_type) GetProcAddress(library, "grpc_auth_context_find_properties_by_name");
grpc_auth_context_peer_identity_property_name_import = (grpc_auth_context_peer_identity_property_name_type) GetProcAddress(library, "grpc_auth_context_peer_identity_property_name");
grpc_auth_context_peer_is_authenticated_import = (grpc_auth_context_peer_is_authenticated_type) GetProcAddress(library, "grpc_auth_context_peer_is_authenticated");
grpc_call_auth_context_import = (grpc_call_auth_context_type) GetProcAddress(library, "grpc_call_auth_context");
grpc_auth_context_release_import = (grpc_auth_context_release_type) GetProcAddress(library, "grpc_auth_context_release");
grpc_auth_context_add_property_import = (grpc_auth_context_add_property_type) GetProcAddress(library, "grpc_auth_context_add_property");
grpc_auth_context_add_cstring_property_import = (grpc_auth_context_add_cstring_property_type) GetProcAddress(library, "grpc_auth_context_add_cstring_property");
grpc_auth_context_set_peer_identity_property_name_import = (grpc_auth_context_set_peer_identity_property_name_type) GetProcAddress(library, "grpc_auth_context_set_peer_identity_property_name");
grpc_channel_credentials_release_import = (grpc_channel_credentials_release_type) GetProcAddress(library, "grpc_channel_credentials_release");
grpc_google_default_credentials_create_import = (grpc_google_default_credentials_create_type) GetProcAddress(library, "grpc_google_default_credentials_create");
grpc_set_ssl_roots_override_callback_import = (grpc_set_ssl_roots_override_callback_type) GetProcAddress(library, "grpc_set_ssl_roots_override_callback");
grpc_ssl_credentials_create_import = (grpc_ssl_credentials_create_type) GetProcAddress(library, "grpc_ssl_credentials_create");
grpc_call_credentials_release_import = (grpc_call_credentials_release_type) GetProcAddress(library, "grpc_call_credentials_release");
grpc_composite_channel_credentials_create_import = (grpc_composite_channel_credentials_create_type) GetProcAddress(library, "grpc_composite_channel_credentials_create");
grpc_composite_call_credentials_create_import = (grpc_composite_call_credentials_create_type) GetProcAddress(library, "grpc_composite_call_credentials_create");
grpc_google_compute_engine_credentials_create_import = (grpc_google_compute_engine_credentials_create_type) GetProcAddress(library, "grpc_google_compute_engine_credentials_create");
grpc_max_auth_token_lifetime_import = (grpc_max_auth_token_lifetime_type) GetProcAddress(library, "grpc_max_auth_token_lifetime");
grpc_service_account_jwt_access_credentials_create_import = (grpc_service_account_jwt_access_credentials_create_type) GetProcAddress(library, "grpc_service_account_jwt_access_credentials_create");
grpc_google_refresh_token_credentials_create_import = (grpc_google_refresh_token_credentials_create_type) GetProcAddress(library, "grpc_google_refresh_token_credentials_create");
grpc_access_token_credentials_create_import = (grpc_access_token_credentials_create_type) GetProcAddress(library, "grpc_access_token_credentials_create");
grpc_google_iam_credentials_create_import = (grpc_google_iam_credentials_create_type) GetProcAddress(library, "grpc_google_iam_credentials_create");
grpc_metadata_credentials_create_from_plugin_import = (grpc_metadata_credentials_create_from_plugin_type) GetProcAddress(library, "grpc_metadata_credentials_create_from_plugin");
grpc_secure_channel_create_import = (grpc_secure_channel_create_type) GetProcAddress(library, "grpc_secure_channel_create");
grpc_server_credentials_release_import = (grpc_server_credentials_release_type) GetProcAddress(library, "grpc_server_credentials_release");
grpc_ssl_server_credentials_create_import = (grpc_ssl_server_credentials_create_type) GetProcAddress(library, "grpc_ssl_server_credentials_create");
grpc_ssl_server_credentials_create_ex_import = (grpc_ssl_server_credentials_create_ex_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_ex");
grpc_server_add_secure_http2_port_import = (grpc_server_add_secure_http2_port_type) GetProcAddress(library, "grpc_server_add_secure_http2_port");
grpc_call_set_credentials_import = (grpc_call_set_credentials_type) GetProcAddress(library, "grpc_call_set_credentials");
grpc_server_credentials_set_auth_metadata_processor_import = (grpc_server_credentials_set_auth_metadata_processor_type) GetProcAddress(library, "grpc_server_credentials_set_auth_metadata_processor");
grpc_slice_ref_import = (grpc_slice_ref_type) GetProcAddress(library, "grpc_slice_ref");
grpc_slice_unref_import = (grpc_slice_unref_type) GetProcAddress(library, "grpc_slice_unref");
grpc_slice_new_import = (grpc_slice_new_type) GetProcAddress(library, "grpc_slice_new");
grpc_slice_new_with_user_data_import = (grpc_slice_new_with_user_data_type) GetProcAddress(library, "grpc_slice_new_with_user_data");
grpc_slice_new_with_len_import = (grpc_slice_new_with_len_type) GetProcAddress(library, "grpc_slice_new_with_len");
grpc_slice_malloc_import = (grpc_slice_malloc_type) GetProcAddress(library, "grpc_slice_malloc");
grpc_slice_intern_import = (grpc_slice_intern_type) GetProcAddress(library, "grpc_slice_intern");
grpc_slice_from_copied_string_import = (grpc_slice_from_copied_string_type) GetProcAddress(library, "grpc_slice_from_copied_string");
grpc_slice_from_copied_buffer_import = (grpc_slice_from_copied_buffer_type) GetProcAddress(library, "grpc_slice_from_copied_buffer");
grpc_slice_from_static_string_import = (grpc_slice_from_static_string_type) GetProcAddress(library, "grpc_slice_from_static_string");
grpc_slice_from_static_buffer_import = (grpc_slice_from_static_buffer_type) GetProcAddress(library, "grpc_slice_from_static_buffer");
grpc_slice_sub_import = (grpc_slice_sub_type) GetProcAddress(library, "grpc_slice_sub");
grpc_slice_sub_no_ref_import = (grpc_slice_sub_no_ref_type) GetProcAddress(library, "grpc_slice_sub_no_ref");
grpc_slice_split_tail_import = (grpc_slice_split_tail_type) GetProcAddress(library, "grpc_slice_split_tail");
grpc_slice_split_head_import = (grpc_slice_split_head_type) GetProcAddress(library, "grpc_slice_split_head");
grpc_empty_slice_import = (grpc_empty_slice_type) GetProcAddress(library, "grpc_empty_slice");
grpc_slice_default_hash_impl_import = (grpc_slice_default_hash_impl_type) GetProcAddress(library, "grpc_slice_default_hash_impl");
grpc_slice_default_eq_impl_import = (grpc_slice_default_eq_impl_type) GetProcAddress(library, "grpc_slice_default_eq_impl");
grpc_slice_eq_import = (grpc_slice_eq_type) GetProcAddress(library, "grpc_slice_eq");
grpc_slice_cmp_import = (grpc_slice_cmp_type) GetProcAddress(library, "grpc_slice_cmp");
grpc_slice_str_cmp_import = (grpc_slice_str_cmp_type) GetProcAddress(library, "grpc_slice_str_cmp");
grpc_slice_buf_cmp_import = (grpc_slice_buf_cmp_type) GetProcAddress(library, "grpc_slice_buf_cmp");
grpc_slice_buf_start_eq_import = (grpc_slice_buf_start_eq_type) GetProcAddress(library, "grpc_slice_buf_start_eq");
grpc_slice_rchr_import = (grpc_slice_rchr_type) GetProcAddress(library, "grpc_slice_rchr");
grpc_slice_chr_import = (grpc_slice_chr_type) GetProcAddress(library, "grpc_slice_chr");
grpc_slice_slice_import = (grpc_slice_slice_type) GetProcAddress(library, "grpc_slice_slice");
grpc_slice_hash_import = (grpc_slice_hash_type) GetProcAddress(library, "grpc_slice_hash");
grpc_slice_is_equivalent_import = (grpc_slice_is_equivalent_type) GetProcAddress(library, "grpc_slice_is_equivalent");
grpc_slice_dup_import = (grpc_slice_dup_type) GetProcAddress(library, "grpc_slice_dup");
grpc_slice_to_c_string_import = (grpc_slice_to_c_string_type) GetProcAddress(library, "grpc_slice_to_c_string");
grpc_slice_buffer_init_import = (grpc_slice_buffer_init_type) GetProcAddress(library, "grpc_slice_buffer_init");
grpc_slice_buffer_destroy_import = (grpc_slice_buffer_destroy_type) GetProcAddress(library, "grpc_slice_buffer_destroy");
grpc_slice_buffer_add_import = (grpc_slice_buffer_add_type) GetProcAddress(library, "grpc_slice_buffer_add");
grpc_slice_buffer_add_indexed_import = (grpc_slice_buffer_add_indexed_type) GetProcAddress(library, "grpc_slice_buffer_add_indexed");
grpc_slice_buffer_addn_import = (grpc_slice_buffer_addn_type) GetProcAddress(library, "grpc_slice_buffer_addn");
grpc_slice_buffer_tiny_add_import = (grpc_slice_buffer_tiny_add_type) GetProcAddress(library, "grpc_slice_buffer_tiny_add");
grpc_slice_buffer_pop_import = (grpc_slice_buffer_pop_type) GetProcAddress(library, "grpc_slice_buffer_pop");
grpc_slice_buffer_reset_and_unref_import = (grpc_slice_buffer_reset_and_unref_type) GetProcAddress(library, "grpc_slice_buffer_reset_and_unref");
grpc_slice_buffer_swap_import = (grpc_slice_buffer_swap_type) GetProcAddress(library, "grpc_slice_buffer_swap");
grpc_slice_buffer_move_into_import = (grpc_slice_buffer_move_into_type) GetProcAddress(library, "grpc_slice_buffer_move_into");
grpc_slice_buffer_trim_end_import = (grpc_slice_buffer_trim_end_type) GetProcAddress(library, "grpc_slice_buffer_trim_end");
grpc_slice_buffer_move_first_import = (grpc_slice_buffer_move_first_type) GetProcAddress(library, "grpc_slice_buffer_move_first");
grpc_slice_buffer_move_first_into_buffer_import = (grpc_slice_buffer_move_first_into_buffer_type) GetProcAddress(library, "grpc_slice_buffer_move_first_into_buffer");
grpc_slice_buffer_take_first_import = (grpc_slice_buffer_take_first_type) GetProcAddress(library, "grpc_slice_buffer_take_first");
grpc_slice_buffer_undo_take_first_import = (grpc_slice_buffer_undo_take_first_type) GetProcAddress(library, "grpc_slice_buffer_undo_take_first");
gpr_malloc_import = (gpr_malloc_type) GetProcAddress(library, "gpr_malloc");
gpr_zalloc_import = (gpr_zalloc_type) GetProcAddress(library, "gpr_zalloc");
gpr_free_import = (gpr_free_type) GetProcAddress(library, "gpr_free");
gpr_realloc_import = (gpr_realloc_type) GetProcAddress(library, "gpr_realloc");
gpr_malloc_aligned_import = (gpr_malloc_aligned_type) GetProcAddress(library, "gpr_malloc_aligned");
gpr_free_aligned_import = (gpr_free_aligned_type) GetProcAddress(library, "gpr_free_aligned");
gpr_set_allocation_functions_import = (gpr_set_allocation_functions_type) GetProcAddress(library, "gpr_set_allocation_functions");
gpr_get_allocation_functions_import = (gpr_get_allocation_functions_type) GetProcAddress(library, "gpr_get_allocation_functions");
gpr_avl_create_import = (gpr_avl_create_type) GetProcAddress(library, "gpr_avl_create");
gpr_avl_ref_import = (gpr_avl_ref_type) GetProcAddress(library, "gpr_avl_ref");
gpr_avl_unref_import = (gpr_avl_unref_type) GetProcAddress(library, "gpr_avl_unref");
gpr_avl_add_import = (gpr_avl_add_type) GetProcAddress(library, "gpr_avl_add");
gpr_avl_remove_import = (gpr_avl_remove_type) GetProcAddress(library, "gpr_avl_remove");
gpr_avl_get_import = (gpr_avl_get_type) GetProcAddress(library, "gpr_avl_get");
gpr_avl_maybe_get_import = (gpr_avl_maybe_get_type) GetProcAddress(library, "gpr_avl_maybe_get");
gpr_avl_is_empty_import = (gpr_avl_is_empty_type) GetProcAddress(library, "gpr_avl_is_empty");
gpr_cmdline_create_import = (gpr_cmdline_create_type) GetProcAddress(library, "gpr_cmdline_create");
gpr_cmdline_add_int_import = (gpr_cmdline_add_int_type) GetProcAddress(library, "gpr_cmdline_add_int");
gpr_cmdline_add_flag_import = (gpr_cmdline_add_flag_type) GetProcAddress(library, "gpr_cmdline_add_flag");
gpr_cmdline_add_string_import = (gpr_cmdline_add_string_type) GetProcAddress(library, "gpr_cmdline_add_string");
gpr_cmdline_on_extra_arg_import = (gpr_cmdline_on_extra_arg_type) GetProcAddress(library, "gpr_cmdline_on_extra_arg");
gpr_cmdline_set_survive_failure_import = (gpr_cmdline_set_survive_failure_type) GetProcAddress(library, "gpr_cmdline_set_survive_failure");
gpr_cmdline_parse_import = (gpr_cmdline_parse_type) GetProcAddress(library, "gpr_cmdline_parse");
gpr_cmdline_destroy_import = (gpr_cmdline_destroy_type) GetProcAddress(library, "gpr_cmdline_destroy");
gpr_cmdline_usage_string_import = (gpr_cmdline_usage_string_type) GetProcAddress(library, "gpr_cmdline_usage_string");
gpr_cpu_num_cores_import = (gpr_cpu_num_cores_type) GetProcAddress(library, "gpr_cpu_num_cores");
gpr_cpu_current_cpu_import = (gpr_cpu_current_cpu_type) GetProcAddress(library, "gpr_cpu_current_cpu");
gpr_histogram_create_import = (gpr_histogram_create_type) GetProcAddress(library, "gpr_histogram_create");
gpr_histogram_destroy_import = (gpr_histogram_destroy_type) GetProcAddress(library, "gpr_histogram_destroy");
gpr_histogram_add_import = (gpr_histogram_add_type) GetProcAddress(library, "gpr_histogram_add");
gpr_histogram_merge_import = (gpr_histogram_merge_type) GetProcAddress(library, "gpr_histogram_merge");
gpr_histogram_percentile_import = (gpr_histogram_percentile_type) GetProcAddress(library, "gpr_histogram_percentile");
gpr_histogram_mean_import = (gpr_histogram_mean_type) GetProcAddress(library, "gpr_histogram_mean");
gpr_histogram_stddev_import = (gpr_histogram_stddev_type) GetProcAddress(library, "gpr_histogram_stddev");
gpr_histogram_variance_import = (gpr_histogram_variance_type) GetProcAddress(library, "gpr_histogram_variance");
gpr_histogram_maximum_import = (gpr_histogram_maximum_type) GetProcAddress(library, "gpr_histogram_maximum");
gpr_histogram_minimum_import = (gpr_histogram_minimum_type) GetProcAddress(library, "gpr_histogram_minimum");
gpr_histogram_count_import = (gpr_histogram_count_type) GetProcAddress(library, "gpr_histogram_count");
gpr_histogram_sum_import = (gpr_histogram_sum_type) GetProcAddress(library, "gpr_histogram_sum");
gpr_histogram_sum_of_squares_import = (gpr_histogram_sum_of_squares_type) GetProcAddress(library, "gpr_histogram_sum_of_squares");
gpr_histogram_get_contents_import = (gpr_histogram_get_contents_type) GetProcAddress(library, "gpr_histogram_get_contents");
gpr_histogram_merge_contents_import = (gpr_histogram_merge_contents_type) GetProcAddress(library, "gpr_histogram_merge_contents");
gpr_join_host_port_import = (gpr_join_host_port_type) GetProcAddress(library, "gpr_join_host_port");
gpr_split_host_port_import = (gpr_split_host_port_type) GetProcAddress(library, "gpr_split_host_port");
gpr_log_import = (gpr_log_type) GetProcAddress(library, "gpr_log");
gpr_log_message_import = (gpr_log_message_type) GetProcAddress(library, "gpr_log_message");
gpr_set_log_verbosity_import = (gpr_set_log_verbosity_type) GetProcAddress(library, "gpr_set_log_verbosity");
gpr_log_verbosity_init_import = (gpr_log_verbosity_init_type) GetProcAddress(library, "gpr_log_verbosity_init");
gpr_set_log_function_import = (gpr_set_log_function_type) GetProcAddress(library, "gpr_set_log_function");
gpr_format_message_import = (gpr_format_message_type) GetProcAddress(library, "gpr_format_message");
gpr_strdup_import = (gpr_strdup_type) GetProcAddress(library, "gpr_strdup");
gpr_asprintf_import = (gpr_asprintf_type) GetProcAddress(library, "gpr_asprintf");
gpr_subprocess_binary_extension_import = (gpr_subprocess_binary_extension_type) GetProcAddress(library, "gpr_subprocess_binary_extension");
gpr_subprocess_create_import = (gpr_subprocess_create_type) GetProcAddress(library, "gpr_subprocess_create");
gpr_subprocess_destroy_import = (gpr_subprocess_destroy_type) GetProcAddress(library, "gpr_subprocess_destroy");
gpr_subprocess_join_import = (gpr_subprocess_join_type) GetProcAddress(library, "gpr_subprocess_join");
gpr_subprocess_interrupt_import = (gpr_subprocess_interrupt_type) GetProcAddress(library, "gpr_subprocess_interrupt");
gpr_mu_init_import = (gpr_mu_init_type) GetProcAddress(library, "gpr_mu_init");
gpr_mu_destroy_import = (gpr_mu_destroy_type) GetProcAddress(library, "gpr_mu_destroy");
gpr_mu_lock_import = (gpr_mu_lock_type) GetProcAddress(library, "gpr_mu_lock");
gpr_mu_unlock_import = (gpr_mu_unlock_type) GetProcAddress(library, "gpr_mu_unlock");
gpr_mu_trylock_import = (gpr_mu_trylock_type) GetProcAddress(library, "gpr_mu_trylock");
gpr_cv_init_import = (gpr_cv_init_type) GetProcAddress(library, "gpr_cv_init");
gpr_cv_destroy_import = (gpr_cv_destroy_type) GetProcAddress(library, "gpr_cv_destroy");
gpr_cv_wait_import = (gpr_cv_wait_type) GetProcAddress(library, "gpr_cv_wait");
gpr_cv_signal_import = (gpr_cv_signal_type) GetProcAddress(library, "gpr_cv_signal");
gpr_cv_broadcast_import = (gpr_cv_broadcast_type) GetProcAddress(library, "gpr_cv_broadcast");
gpr_once_init_import = (gpr_once_init_type) GetProcAddress(library, "gpr_once_init");
gpr_event_init_import = (gpr_event_init_type) GetProcAddress(library, "gpr_event_init");
gpr_event_set_import = (gpr_event_set_type) GetProcAddress(library, "gpr_event_set");
gpr_event_get_import = (gpr_event_get_type) GetProcAddress(library, "gpr_event_get");
gpr_event_wait_import = (gpr_event_wait_type) GetProcAddress(library, "gpr_event_wait");
gpr_ref_init_import = (gpr_ref_init_type) GetProcAddress(library, "gpr_ref_init");
gpr_ref_import = (gpr_ref_type) GetProcAddress(library, "gpr_ref");
gpr_ref_non_zero_import = (gpr_ref_non_zero_type) GetProcAddress(library, "gpr_ref_non_zero");
gpr_refn_import = (gpr_refn_type) GetProcAddress(library, "gpr_refn");
gpr_unref_import = (gpr_unref_type) GetProcAddress(library, "gpr_unref");
gpr_stats_init_import = (gpr_stats_init_type) GetProcAddress(library, "gpr_stats_init");
gpr_stats_inc_import = (gpr_stats_inc_type) GetProcAddress(library, "gpr_stats_inc");
gpr_stats_read_import = (gpr_stats_read_type) GetProcAddress(library, "gpr_stats_read");
gpr_thd_new_import = (gpr_thd_new_type) GetProcAddress(library, "gpr_thd_new");
gpr_thd_options_default_import = (gpr_thd_options_default_type) GetProcAddress(library, "gpr_thd_options_default");
gpr_thd_options_set_detached_import = (gpr_thd_options_set_detached_type) GetProcAddress(library, "gpr_thd_options_set_detached");
gpr_thd_options_set_joinable_import = (gpr_thd_options_set_joinable_type) GetProcAddress(library, "gpr_thd_options_set_joinable");
gpr_thd_options_is_detached_import = (gpr_thd_options_is_detached_type) GetProcAddress(library, "gpr_thd_options_is_detached");
gpr_thd_options_is_joinable_import = (gpr_thd_options_is_joinable_type) GetProcAddress(library, "gpr_thd_options_is_joinable");
gpr_thd_currentid_import = (gpr_thd_currentid_type) GetProcAddress(library, "gpr_thd_currentid");
gpr_thd_join_import = (gpr_thd_join_type) GetProcAddress(library, "gpr_thd_join");
gpr_time_0_import = (gpr_time_0_type) GetProcAddress(library, "gpr_time_0");
gpr_inf_future_import = (gpr_inf_future_type) GetProcAddress(library, "gpr_inf_future");
gpr_inf_past_import = (gpr_inf_past_type) GetProcAddress(library, "gpr_inf_past");
gpr_time_init_import = (gpr_time_init_type) GetProcAddress(library, "gpr_time_init");
gpr_now_import = (gpr_now_type) GetProcAddress(library, "gpr_now");
gpr_convert_clock_type_import = (gpr_convert_clock_type_type) GetProcAddress(library, "gpr_convert_clock_type");
gpr_time_cmp_import = (gpr_time_cmp_type) GetProcAddress(library, "gpr_time_cmp");
gpr_time_max_import = (gpr_time_max_type) GetProcAddress(library, "gpr_time_max");
gpr_time_min_import = (gpr_time_min_type) GetProcAddress(library, "gpr_time_min");
gpr_time_add_import = (gpr_time_add_type) GetProcAddress(library, "gpr_time_add");
gpr_time_sub_import = (gpr_time_sub_type) GetProcAddress(library, "gpr_time_sub");
gpr_time_from_micros_import = (gpr_time_from_micros_type) GetProcAddress(library, "gpr_time_from_micros");
gpr_time_from_nanos_import = (gpr_time_from_nanos_type) GetProcAddress(library, "gpr_time_from_nanos");
gpr_time_from_millis_import = (gpr_time_from_millis_type) GetProcAddress(library, "gpr_time_from_millis");
gpr_time_from_seconds_import = (gpr_time_from_seconds_type) GetProcAddress(library, "gpr_time_from_seconds");
gpr_time_from_minutes_import = (gpr_time_from_minutes_type) GetProcAddress(library, "gpr_time_from_minutes");
gpr_time_from_hours_import = (gpr_time_from_hours_type) GetProcAddress(library, "gpr_time_from_hours");
gpr_time_to_millis_import = (gpr_time_to_millis_type) GetProcAddress(library, "gpr_time_to_millis");
gpr_time_similar_import = (gpr_time_similar_type) GetProcAddress(library, "gpr_time_similar");
gpr_sleep_until_import = (gpr_sleep_until_type) GetProcAddress(library, "gpr_sleep_until");
gpr_timespec_to_micros_import = (gpr_timespec_to_micros_type) GetProcAddress(library, "gpr_timespec_to_micros");
}
#endif /* GPR_WINDOWS */
|
grani/grpc
|
src/ruby/ext/grpc/rb_grpc_imports.generated.c
|
C
|
bsd-3-clause
| 53,704 |
/*
* Copyright (c) 2013, Alex Bedig, New BSD License: https://github.com/hydrojumbo/CUAHSI.Apps/blob/master/LICENSE.md
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace CUAHSI.Browser.Controllers
{
/// <summary>
/// Serves data visualization and decision support systems along the /Vis/ route.
/// </summary>
/// <remarks>Set the ServiceDomain values in the ServiceConfiguration file such that your Discovery app calls point to the correct API. For most users, this will be https://data.cuahsi.org/. The only time the ViewBag.ServiceDomain value should be different is when you want to use a different API for discovery and data download.</remarks>
public class VisController : Controller
{
/// <summary>
/// Serves the HTML decision support/data visualization view linked to by the Discovery page (the default view).
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
ViewBag.Message = "CUAHSI Hydrologic Data Visualization Client";
#if DEBUG
ViewBag.ServiceDomain = RoleEnvironment.GetConfigurationSettingValue("StagingServiceDomain");
#else
ViewBag.ServiceDomain = RoleEnvironment.GetConfigurationSettingValue("ProductionServiceDomain");
#endif
string sessionguid = Guid.NewGuid().ToString();
ViewBag.ThisSession = sessionguid;
return View();
}
}
}
|
hydrojumbo/CUAHSI.Apps
|
CUAHSI.Browser/Controllers/VisController.cs
|
C#
|
bsd-3-clause
| 1,560 |
<?php
namespace Evidencia;
//paola cuadros
// Add this import statement:
use Evidencia\Model\EvidenciaTable;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '\config\module.config.php';
}
// getAutoloaderConfig() and getConfig() methods here
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Evidencia\Model\EvidenciaTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new EvidenciaTable($dbAdapter);
return $table;
},
),
);
}
}
|
PaolaCuadros/ORI-BSC
|
module/Evidencia/Module.php
|
PHP
|
bsd-3-clause
| 1,126 |
<!DOCTYPE html>
<!--[if IE 7]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>Unify | Welcome...</title>
<!-- Meta -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<!-- CSS Global Compulsory-->
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/headers/header1.css" />
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="assets/css/style_responsive.css" />
<link rel="shortcut icon" href="favicon.ico" />
<!-- CSS Implementing Plugins -->
<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css" />
<!-- CSS Theme -->
<link rel="stylesheet" href="assets/css/themes/default.css" id="style_color" />
<link rel="stylesheet" href="assets/css/themes/headers/default.css" id="style_color-header-1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
<!--=== Style Switcher ===-->
<i class="style-switcher-btn icon-cogs"></i>
<div class="style-switcher">
<div class="theme-close"><i class="icon-remove"></i></div>
<div class="theme-heading">Theme Colors</div>
<ul class="unstyled">
<li class="theme-default theme-active" data-style="default" data-header="light"></li>
<li class="theme-blue" data-style="blue" data-header="light"></li>
<li class="theme-orange" data-style="orange" data-header="light"></li>
<li class="theme-red" data-style="red" data-header="light"></li>
<li class="theme-light" data-style="light" data-header="light"></li>
</ul>
</div><!--/style-switcher-->
<!--=== End Style Switcher ===-->
<!--=== Top ===-->
<div class="top">
<div class="container">
<ul class="loginbar pull-right">
<li><i class="icon-globe"></i><a>Languages <i class="icon-sort-up"></i></a>
<ul class="nav-list">
<li class="active"><a href="#">English</a> <i class="icon-ok"></i></li>
<li><a href="#">Spanish</a></li>
<li><a href="#">Russian</a></li>
<li><a href="#">German</a></li>
</ul>
</li>
<li class="devider"> </li>
<li><a href="page_faq.html" class="login-btn">Help</a></li>
<li class="devider"> </li>
<li><a href="page_login.html" class="login-btn">Login</a></li>
</ul>
</div>
</div><!--/top-->
<!--=== End Top ===-->
<!--=== Header ===-->
<div class="header">
<div class="container">
<!-- Logo -->
<div class="logo">
<a href="index.html"><img id="logo-header" src="assets/img/logo1-default.png" alt="Logo" /></a>
</div><!-- /logo -->
<!-- Menu -->
<div class="navbar">
<div class="navbar-inner">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a><!-- /nav-collapse -->
<div class="nav-collapse collapse">
<ul class="nav top-2">
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Home
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="index.html">Option1: Landing Page</a></li>
<li><a href="page_home.html">Option2: Header Option</a></li>
<li><a href="page_home4.html">Option3: Revolution Slider</a></li>
<li><a href="page_home5.html">Option4: Amazing Content</a></li>
<li><a href="page_home1.html">Option5: Mixed Content</a></li>
<li><a href="page_home2.html">Option6: Content with Sidebar</a></li>
<li><a href="page_home3.html">Option7: Aplle Style Slider</a></li>
<li><a href="page_home_all.html">Home All In One</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li>
<a href="" class="dropdown-toggle" data-toggle="dropdown">Pages
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="page_about.html">About Us</a></li>
<li><a href="page_services.html">Services</a></li>
<li><a href="page_pricing.html">Pricing</a></li>
<li><a href="page_coming_soon.html">Coming Soon</a></li>
<li><a href="page_faq.html">FAQs</a></li>
<li><a href="page_search.html">Search Result</a></li>
<li><a href="page_gallery.html">Gallery</a></li>
<li><a href="page_registration.html">Registration</a></li>
<li><a href="page_login.html">Login</a></li>
<li><a href="page_404.html">404</a></li>
<li><a href="page_clients.html">Clients</a></li>
<li><a href="page_privacy.html">Privacy Policy</a></li>
<li><a href="page_terms.html">Terms of Service</a></li>
<li><a href="page_column_left.html">2 Columns (Left)</a></li>
<li><a href="page_column_right.html">2 Columns (Right)</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li class="active">
<a href="" class="dropdown-toggle" data-toggle="dropdown">Features
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="feature_grid.html">Grid Layout</a></li>
<li><a href="feature_typography.html">Typography</a></li>
<li><a href="feature_thumbnail.html">Thumbnails</a></li>
<li><a href="feature_component.html">Components</a></li>
<li><a href="feature_navigation.html">Navigation</a></li>
<li class="active"><a href="feature_table.html">Tables</a></li>
<li><a href="feature_form.html">Forms</a></li>
<li><a href="feature_icons.html">Icons</a></li>
<li><a href="feature_button.html">Buttons</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Portfolio
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="portfolio_item.html">Portfolio Item</a></li>
<li><a href="portfolio_2columns.html">Portfolio 2 Columns</a></li>
<li><a href="portfolio_3columns.html">Portfolio 3 Columns</a></li>
<li><a href="portfolio_4columns.html">Portfolio 4 Columns</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Blog
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="blog.html">Blog</a></li>
<li><a href="blog_item.html">Blog Item</a></li>
<li><a href="blog_left_sidebar.html">Blog Left Sidebar</a></li>
<li><a href="blog_item_left_sidebar.html">Blog Item Left Sidebar</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contact
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="page_contact.html">Contact Default</a></li>
<li><a href="page_contact1.html">Contact Boxed Map</a></li>
</ul>
<b class="caret-out"></b>
</li>
<li><a class="search"><i class="icon-search search-btn"></i></a></li>
</ul>
<div class="search-open">
<div class="input-append">
<form />
<input type="text" class="span3" placeholder="Search" />
<button type="submit" class="btn-u">Go</button>
</form>
</div>
</div>
</div><!-- /nav-collapse -->
</div><!-- /navbar-inner -->
</div><!-- /navbar -->
</div><!-- /container -->
</div><!--/header -->
<!--=== End Header ===-->
<!--=== Breadcrumbs ===-->
<div class="row-fluid breadcrumbs margin-bottom-20">
<div class="container">
<h1 class="pull-left">Tables</h1>
<ul class="pull-right breadcrumb">
<li><a href="index.html">Home</a> <span class="divider">/</span></li>
<li><a href="">Features</a> <span class="divider">/</span></li>
<li class="active">Tables</li>
</ul>
</div><!--/container-->
</div><!--/breadcrumbs-->
<!--=== End Breadcrumbs ===-->
<!--=== Content Part ===-->
<div class="container">
<div class="row-fluid">
<!-- Default Tables styles -->
<div class="row-fluid margin-bottom-20">
<div class="span6">
<div class="headline"><h3>Default styles</h3></div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
<div class="span6">
<div class="headline"><h3>Default Styles with Zebra-Striping</h3></div>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
</div><!--/row-fluid-->
<div class="row-fluid">
<div class="span6">
<div class="headline"><h3>Default Styles with Border</h3></div>
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
<div class="span6">
<div class="headline"><h3>Default Styles with hover effect</h3></div>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
</div><!--/row-fluid-->
<div class="row-fluid">
<div class="span6">
<div class="headline"><h3>Default Tables with Color Styles</h3></div>
<table class="table">
<thead>
<tr class="info">
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr class="success">
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr class="error">
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr class="warning">
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
<div class="span6">
<div class="headline"><h3>Default Styles with Less Cell-Padding</h3></div>
<table class="table table-condensed">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
</div><!--/row-fluid-->
</div><!--/row-fluid-->
<!--//Default Tables styles -->
</div><!--/container-->
<!--=== End Content Part ===-->
<!--=== Footer ===-->
<div class="footer">
<div class="container">
<div class="row-fluid">
<div class="span4">
<!-- About -->
<div class="headline"><h3>About</h3></div>
<p class="margin-bottom-25">Unify is an incredibly beautiful responsive Bootstrap Template for corporate and creative professionals.</p>
<!-- Monthly Newsletter -->
<div class="headline"><h3>Monthly Newsletter</h3></div>
<p>Subscribe to our newsletter and stay up to date with the latest news and deals!</p>
<form class="form-inline" />
<div class="input-append">
<input type="text" placeholder="Email Address" class="input-medium" />
<button class="btn-u">Subscribe</button>
</div>
</form>
</div><!--/span4-->
<div class="span4">
<div class="posts">
<div class="headline"><h3>Recent Blog Entries</h3></div>
<dl class="dl-horizontal">
<dt><a href="#"><img src="assets/img/sliders/elastislide/6.jpg" alt="" /></a></dt>
<dd>
<p><a href="#">Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template</a></p>
</dd>
</dl>
<dl class="dl-horizontal">
<dt><a href="#"><img src="assets/img/sliders/elastislide/10.jpg" alt="" /></a></dt>
<dd>
<p><a href="#">Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template</a></p>
</dd>
</dl>
<dl class="dl-horizontal">
<dt><a href="#"><img src="assets/img/sliders/elastislide/11.jpg" alt="" /></a></dt>
<dd>
<p><a href="#">Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template</a></p>
</dd>
</dl>
</div>
</div><!--/span4-->
<div class="span4">
<!-- Monthly Newsletter -->
<div class="headline"><h3>Contact Us</h3></div>
<address>
25, Lorem Lis Street, Orange <br />
California, US <br />
Phone: 800 123 3456 <br />
Fax: 800 123 3456 <br />
Email: <a href="mailto:[email protected]" class="">[email protected]</a>
</address>
<!-- Stay Connected -->
<div class="headline"><h3>Stay Connected</h3></div>
<ul class="social-icons">
<li><a href="#" data-original-title="Feed" class="social_rss"></a></li>
<li><a href="#" data-original-title="Facebook" class="social_facebook"></a></li>
<li><a href="#" data-original-title="Twitter" class="social_twitter"></a></li>
<li><a href="#" data-original-title="Goole Plus" class="social_googleplus"></a></li>
<li><a href="#" data-original-title="Pinterest" class="social_pintrest"></a></li>
<li><a href="#" data-original-title="Linkedin" class="social_linkedin"></a></li>
<li><a href="#" data-original-title="Vimeo" class="social_vimeo"></a></li>
</ul>
</div><!--/span4-->
</div><!--/row-fluid-->
</div><!--/container-->
</div><!--/footer-->
<!--=== End Footer ===-->
<!--=== Copyright ===-->
<div class="copyright">
<div class="container">
<div class="row-fluid">
<div class="span8">
<p>2013 © Unify. ALL Rights Reserved. <a href="#">Privacy Policy</a> | <a href="#">Terms of Service</a></p>
</div>
<div class="span4">
<a href="index.html"><img id="logo-footer" src="assets/img/logo2-default.png" class="pull-right" alt="" /></a>
</div>
</div><!--/row-fluid-->
</div><!--/container-->
</div><!--/copyright-->
<!--=== End Copyright ===-->
<!-- JS Global Compulsory -->
<script type="text/javascript" src="assets/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="assets/js/modernizr.custom.js"></script>
<script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!-- JS Implementing Plugins -->
<script type="text/javascript" src="assets/plugins/back-to-top.js"></script>
<!-- JS Page Level -->
<script type="text/javascript" src="assets/js/app.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
});
</script>
<!--[if lt IE 9]>
<script src="assets/js/respond.js"></script>
<![endif]-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29166220-1']);
_gaq.push(['_setDomainName', 'htmlstream.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
|
cristiannores/construccion
|
public/unify/feature_table.html
|
HTML
|
bsd-3-clause
| 24,839 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel backend\models\GoodsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('common', 'Goods');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="goods-index">
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('common', 'Create Goods'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'idcat',
'name',
'height',
'hard',
// 'gload',
// 'cost1',
// 'cost2',
// 'cost3',
// 'cost4',
// 'cost5',
// 'cost6',
// 'sostav',
// 'material',
// 'pic',
// 'note1:ntext',
// 'note2:ntext',
// 'pic2',
// 'bl1:ntext',
// 'bl1pic',
// 'bl2:ntext',
// 'bl2pic',
// 'bl3:ntext',
// 'bl3pic',
// 'bl4:ntext',
// 'bl4pic',
// 'bl5:ntext',
// 'bl5pic',
// 'bl6:ntext',
// 'bl6pic',
// 'bl7:ntext',
// 'bl7pic',
// 'bl8:ntext',
// 'bl8pic',
// 'bl9:ntext',
// 'bl9pic',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
|
AngryGantz/yii2-advanced-site_skazka
|
backend/views/goods/index.php
|
PHP
|
bsd-3-clause
| 1,666 |
package org.dirtymechanics.frc.component.drive;
import org.dirtymechanics.frc.actuator.DoubleSolenoid;
/**
*
* @author Daniel Ruess
*/
public class Transmission {
private final DoubleSolenoid solenoid;
public Transmission(DoubleSolenoid solenoid) {
this.solenoid = solenoid;
}
public void setHigh() {
solenoid.set(true);
}
public void setLow() {
solenoid.set(false);
}
}
|
daniel-ruess/FRC-3932
|
src/org/dirtymechanics/frc/component/drive/Transmission.java
|
Java
|
bsd-3-clause
| 433 |
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/node-properties.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/operator-properties.h"
namespace v8 {
namespace internal {
namespace compiler {
// static
int NodeProperties::PastValueIndex(Node* node) {
return FirstValueIndex(node) + node->op()->ValueInputCount();
}
// static
int NodeProperties::PastContextIndex(Node* node) {
return FirstContextIndex(node) +
OperatorProperties::GetContextInputCount(node->op());
}
// static
int NodeProperties::PastFrameStateIndex(Node* node) {
return FirstFrameStateIndex(node) +
OperatorProperties::GetFrameStateInputCount(node->op());
}
// static
int NodeProperties::PastEffectIndex(Node* node) {
return FirstEffectIndex(node) + node->op()->EffectInputCount();
}
// static
int NodeProperties::PastControlIndex(Node* node) {
return FirstControlIndex(node) + node->op()->ControlInputCount();
}
// static
Node* NodeProperties::GetValueInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->ValueInputCount());
return node->InputAt(FirstValueIndex(node) + index);
}
// static
Node* NodeProperties::GetContextInput(Node* node) {
DCHECK(OperatorProperties::HasContextInput(node->op()));
return node->InputAt(FirstContextIndex(node));
}
// static
Node* NodeProperties::GetFrameStateInput(Node* node, int index) {
DCHECK_LT(index, OperatorProperties::GetFrameStateInputCount(node->op()));
return node->InputAt(FirstFrameStateIndex(node) + index);
}
// static
Node* NodeProperties::GetEffectInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->EffectInputCount());
return node->InputAt(FirstEffectIndex(node) + index);
}
// static
Node* NodeProperties::GetControlInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->ControlInputCount());
return node->InputAt(FirstControlIndex(node) + index);
}
// static
bool NodeProperties::IsValueEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstValueIndex(node),
node->op()->ValueInputCount());
}
// static
bool NodeProperties::IsContextEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstContextIndex(node),
OperatorProperties::GetContextInputCount(node->op()));
}
// static
bool NodeProperties::IsFrameStateEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstFrameStateIndex(node),
OperatorProperties::GetFrameStateInputCount(node->op()));
}
// static
bool NodeProperties::IsEffectEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstEffectIndex(node),
node->op()->EffectInputCount());
}
// static
bool NodeProperties::IsControlEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstControlIndex(node),
node->op()->ControlInputCount());
}
// static
void NodeProperties::ReplaceContextInput(Node* node, Node* context) {
node->ReplaceInput(FirstContextIndex(node), context);
}
// static
void NodeProperties::ReplaceControlInput(Node* node, Node* control) {
node->ReplaceInput(FirstControlIndex(node), control);
}
// static
void NodeProperties::ReplaceEffectInput(Node* node, Node* effect, int index) {
DCHECK(index < node->op()->EffectInputCount());
return node->ReplaceInput(FirstEffectIndex(node) + index, effect);
}
// static
void NodeProperties::ReplaceFrameStateInput(Node* node, int index,
Node* frame_state) {
DCHECK_LT(index, OperatorProperties::GetFrameStateInputCount(node->op()));
node->ReplaceInput(FirstFrameStateIndex(node) + index, frame_state);
}
// static
void NodeProperties::RemoveNonValueInputs(Node* node) {
node->TrimInputCount(node->op()->ValueInputCount());
}
// static
void NodeProperties::ReplaceWithValue(Node* node, Node* value, Node* effect,
Node* control) {
if (!effect && node->op()->EffectInputCount() > 0) {
effect = NodeProperties::GetEffectInput(node);
}
if (control == nullptr && node->op()->ControlInputCount() > 0) {
control = NodeProperties::GetControlInput(node);
}
// Requires distinguishing between value, effect and control edges.
for (Edge edge : node->use_edges()) {
if (IsControlEdge(edge)) {
DCHECK_EQ(IrOpcode::kIfSuccess, edge.from()->opcode());
DCHECK_NOT_NULL(control);
edge.from()->ReplaceUses(control);
edge.UpdateTo(NULL);
} else if (IsEffectEdge(edge)) {
DCHECK_NOT_NULL(effect);
edge.UpdateTo(effect);
} else {
edge.UpdateTo(value);
}
}
}
// static
Node* NodeProperties::FindProjection(Node* node, size_t projection_index) {
for (auto use : node->uses()) {
if (use->opcode() == IrOpcode::kProjection &&
ProjectionIndexOf(use->op()) == projection_index) {
return use;
}
}
return nullptr;
}
// static
void NodeProperties::CollectControlProjections(Node* node, Node** projections,
size_t projection_count) {
#ifdef DEBUG
DCHECK_LE(static_cast<int>(projection_count), node->UseCount());
std::memset(projections, 0, sizeof(*projections) * projection_count);
#endif
size_t if_value_index = 0;
for (Node* const use : node->uses()) {
size_t index;
switch (use->opcode()) {
case IrOpcode::kIfTrue:
DCHECK_EQ(IrOpcode::kBranch, node->opcode());
index = 0;
break;
case IrOpcode::kIfFalse:
DCHECK_EQ(IrOpcode::kBranch, node->opcode());
index = 1;
break;
case IrOpcode::kIfSuccess:
DCHECK_EQ(IrOpcode::kCall, node->opcode());
index = 0;
break;
case IrOpcode::kIfException:
DCHECK_EQ(IrOpcode::kCall, node->opcode());
index = 1;
break;
case IrOpcode::kIfValue:
DCHECK_EQ(IrOpcode::kSwitch, node->opcode());
index = if_value_index++;
break;
case IrOpcode::kIfDefault:
DCHECK_EQ(IrOpcode::kSwitch, node->opcode());
index = projection_count - 1;
break;
default:
continue;
}
DCHECK_LT(if_value_index, projection_count);
DCHECK_LT(index, projection_count);
DCHECK_NULL(projections[index]);
projections[index] = use;
}
#ifdef DEBUG
for (size_t index = 0; index < projection_count; ++index) {
DCHECK_NOT_NULL(projections[index]);
}
#endif
}
// static
bool NodeProperties::AllValueInputsAreTyped(Node* node) {
int input_count = node->op()->ValueInputCount();
for (int index = 0; index < input_count; ++index) {
if (!IsTyped(GetValueInput(node, index))) return false;
}
return true;
}
// static
bool NodeProperties::IsInputRange(Edge edge, int first, int num) {
if (num == 0) return false;
int const index = edge.index();
return first <= index && index < first + num;
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
sgraham/nope
|
v8/src/compiler/node-properties.cc
|
C++
|
bsd-3-clause
| 7,189 |
<?php
/**
* View for residential_house objects
*
* @var int $image_path
* @var $residential_house
*/
?>
<?php foreach ($residential_house as $item) { ?>
<div class="object-card">
<a href="/objects/residential-house-view?id=<?php print $item->id; ?>">
<img src="<?php print $item->urlAttribute('widget_photo_url');?>" alt="<?php print $item->name ?>" >
<div class="description">
<span class="price"><?php print number_format($item->price_total,0,' ', ' '); ?> руб.</span>
<span class="info"><?php print $item->name; ?></span>
<span class="info"><?php print $item->administrativeDistrict->name; ?> <br/> <?php print $item->street->name; ?></span>
<span class="info"><?php print $item->space_gross; ?> м<sup>2</sup></span>
</div>
</a>
</div>
<?php } ?>
|
hurduring/smolyakoff
|
frontend/components/objects/views/residential-house-element.php
|
PHP
|
bsd-3-clause
| 888 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.genmod.families.family.InverseGaussian.resid_dev — statsmodels v0.10.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.genmod.families.family.InverseGaussian.starting_mu" href="statsmodels.genmod.families.family.InverseGaussian.starting_mu.html" />
<link rel="prev" title="statsmodels.genmod.families.family.InverseGaussian.resid_anscombe" href="statsmodels.genmod.families.family.InverseGaussian.resid_anscombe.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.InverseGaussian.starting_mu.html" title="statsmodels.genmod.families.family.InverseGaussian.starting_mu"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.InverseGaussian.resid_anscombe.html" title="statsmodels.genmod.families.family.InverseGaussian.resid_anscombe"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../glm.html" >Generalized Linear Models</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.genmod.families.family.InverseGaussian.html" accesskey="U">statsmodels.genmod.families.family.InverseGaussian</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-genmod-families-family-inversegaussian-resid-dev">
<h1>statsmodels.genmod.families.family.InverseGaussian.resid_dev<a class="headerlink" href="#statsmodels-genmod-families-family-inversegaussian-resid-dev" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.genmod.families.family.InverseGaussian.resid_dev">
<code class="sig-prename descclassname">InverseGaussian.</code><code class="sig-name descname">resid_dev</code><span class="sig-paren">(</span><em class="sig-param">endog</em>, <em class="sig-param">mu</em>, <em class="sig-param">var_weights=1.0</em>, <em class="sig-param">scale=1.0</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.genmod.families.family.InverseGaussian.resid_dev" title="Permalink to this definition">¶</a></dt>
<dd><p>The deviance residuals</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl class="simple">
<dt><strong>endog</strong><span class="classifier">array-like</span></dt><dd><p>The endogenous response variable</p>
</dd>
<dt><strong>mu</strong><span class="classifier">array-like</span></dt><dd><p>The inverse of the link function at the linear predicted values.</p>
</dd>
<dt><strong>var_weights</strong><span class="classifier">array-like</span></dt><dd><p>1d array of variance (analytic) weights. The default is 1.</p>
</dd>
<dt><strong>scale</strong><span class="classifier">float, optional</span></dt><dd><p>An optional scale argument. The default is 1.</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl class="simple">
<dt><strong>resid_dev</strong><span class="classifier">float</span></dt><dd><p>Deviance residuals as defined below.</p>
</dd>
</dl>
</dd>
</dl>
<p class="rubric">Notes</p>
<p>The deviance residuals are defined by the contribution D_i of
observation i to the deviance as</p>
<div class="math notranslate nohighlight">
\[resid\_dev_i = sign(y_i-\mu_i) \sqrt{D_i}\]</div>
<p>D_i is calculated from the _resid_dev method in each family.
Distribution-specific documentation of the calculation is available
there.</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.InverseGaussian.resid_anscombe.html"
title="previous chapter">statsmodels.genmod.families.family.InverseGaussian.resid_anscombe</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.InverseGaussian.starting_mu.html"
title="next chapter">statsmodels.genmod.families.family.InverseGaussian.starting_mu</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.genmod.families.family.InverseGaussian.resid_dev.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.10.0/generated/statsmodels.genmod.families.family.InverseGaussian.resid_dev.html
|
HTML
|
bsd-3-clause
| 9,031 |
var initialize_ProfilerTest = function() {
InspectorTest.preloadPanel("profiles");
InspectorTest.startProfilerTest = function(callback)
{
Runtime.experiments.enableForTest("disableAgentsWhenProfile");
InspectorTest.addResult("Profiler was enabled.");
InspectorTest.addSniffer(WebInspector.panels.profiles, "_addProfileHeader", InspectorTest._profileHeaderAdded, true);
InspectorTest.addSniffer(WebInspector.CPUProfileView.prototype, "refresh", InspectorTest._profileViewRefresh, true);
InspectorTest.safeWrap(callback)();
};
InspectorTest.completeProfilerTest = function()
{
InspectorTest.addResult("");
InspectorTest.addResult("Profiler was disabled.");
InspectorTest.completeTest();
};
InspectorTest.runProfilerTestSuite = function(testSuite)
{
var testSuiteTests = testSuite.slice();
function runner()
{
if (!testSuiteTests.length) {
InspectorTest.completeProfilerTest();
return;
}
var nextTest = testSuiteTests.shift();
InspectorTest.addResult("");
InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]);
InspectorTest.safeWrap(nextTest)(runner, runner);
}
InspectorTest.startProfilerTest(runner);
};
InspectorTest.showProfileWhenAdded = function(title)
{
InspectorTest._showProfileWhenAdded = title;
};
InspectorTest._profileHeaderAdded = function(profile)
{
if (InspectorTest._showProfileWhenAdded === profile.title)
WebInspector.panels.profiles.showProfile(profile);
};
InspectorTest.waitUntilProfileViewIsShown = function(title, callback)
{
callback = InspectorTest.safeWrap(callback);
var profilesPanel = WebInspector.panels.profiles;
if (profilesPanel.visibleView && profilesPanel.visibleView.profile && profilesPanel.visibleView._profileHeader.title === title)
callback(profilesPanel.visibleView);
else
InspectorTest._waitUntilProfileViewIsShownCallback = { title: title, callback: callback };
}
InspectorTest._profileViewRefresh = function()
{
// Called in the context of ProfileView.
if (InspectorTest._waitUntilProfileViewIsShownCallback && InspectorTest._waitUntilProfileViewIsShownCallback.title === this._profileHeader.title) {
var callback = InspectorTest._waitUntilProfileViewIsShownCallback;
delete InspectorTest._waitUntilProfileViewIsShownCallback;
callback.callback(this);
}
};
};
|
smilusingjavascript/blink
|
LayoutTests/inspector/profiler/profiler-test.js
|
JavaScript
|
bsd-3-clause
| 2,448 |
<?php
namespace DoctrineORMModule\Proxy\__CG__\Domain\Entity\Customer;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class CustomerTypeEntity extends \Domain\Entity\Customer\CustomerTypeEntity implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = array('description' => NULL);
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
unset($this->description);
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @param string $name
*/
public function __get($name)
{
if (array_key_exists($name, $this->__getLazyProperties())) {
$this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name));
return $this->$name;
}
trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE);
}
/**
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
if (array_key_exists($name, $this->__getLazyProperties())) {
$this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value));
$this->$name = $value;
return;
}
$this->$name = $value;
}
/**
*
* @param string $name
* @return boolean
*/
public function __isset($name)
{
if (array_key_exists($name, $this->__getLazyProperties())) {
$this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name));
return isset($this->$name);
}
return false;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return array('__isInitialized__', 'id', 'description');
}
return array('__isInitialized__', 'id');
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (CustomerTypeEntity $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
unset($this->description);
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array());
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array());
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function getDescription()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getDescription', array());
return parent::getDescription();
}
/**
* {@inheritDoc}
*/
public function setId($id)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setId', array($id));
return parent::setId($id);
}
/**
* {@inheritDoc}
*/
public function setDescription($description)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setDescription', array($description));
return parent::setDescription($description);
}
}
|
Anak1nSkywalker/vixnu
|
data/DoctrineORMModule/Proxy/__CG__DomainEntityCustomerCustomerTypeEntity.php
|
PHP
|
bsd-3-clause
| 6,910 |
//**************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// FILE: SpringSys.h
// DESCRIPTION: Public header files for the Spring System created by Adam Felt.
// To use this interface you will need to link to "SpringSys.lib"
//
// This spring system is a multi-point spring-based dynamic system.
// In order to your the sytem you must derive from SpringSysClient and implement
// Tab<Matrix3> SpringSysClient::GetForceMatrices(TimeValue t)
// You are responsible for gathering the spring constraint forces at any given time.
// You initialize the
//
// AUTHOR: Adam Felt
// HISTORY:
//**************************************************************************/
#pragma once
#include "maxheap.h"
#include "baseinterface.h"
#include "tab.h"
#include "point3.h"
#include "matrix3.h"
#include "containers/Array.h"
#ifndef SpringSysExport
# ifdef BLD_SPRING_SYS
# define SpringSysExport __declspec( dllexport )
# else
# define SpringSysExport __declspec( dllimport )
# endif
#endif
/*! \sa Class Point3 , Class SpringSys\n\n
This class represents the constraint point object as it is used in the spring
system. This controlled particle class is used to constrain a point to an
object. */
class SSConstraintPoint: public MaxHeapOperators
{
public:
/*! This bone index is used to identify the bone.
Usually refers to a reference index, or paramblock index. */
int index;
//! The control nodes stored position.
Point3 pos;
//! The control nodes stored velocity.
Point3 vel;
/*! \remarks Constructor.
\par Default Implementation:
<b>{ index = -1; pos = Point3(0.0f, 0.0f, 0.0f);</b>\n\n
<b>vel = Point3(0.0f, 0.0f, 0.0f); }</b> */
SSConstraintPoint() {index = -1; pos = Point3(0.0f, 0.0f, 0.0f); vel = Point3(0.0f, 0.0f, 0.0f);}
/*! \remarks Constructor.
\par Parameters:
<b>int id</b>\n\n
The index to initialize with.
\par Default Implementation:
<b>{index = id; vel = Point3(0,0,0);}</b> */
SSConstraintPoint(int id) {index = id; pos = Point3(0.0f, 0.0f, 0.0f); vel = Point3(0,0,0);}
/*! \remarks Destructor.
\par Default Implementation:
<b>{ }</b> */
~SSConstraintPoint() {}
/*! \remarks Assignment operator. */
SSConstraintPoint& operator=(const SSConstraintPoint& from)
{
index = from.index;
pos = from.pos;
vel = from.vel;
return *this;
}
/*! \remarks This method allows you to copy the data from the
specified <b>SSConstraintPoint</b>.
\par Parameters:
<b>const SSConstraintPoint from</b>\n\n
The object to copy from. */
SSConstraintPoint Copy(const SSConstraintPoint from)
{
index = from.index;
pos = from.pos;
vel = from.vel;
return *this;
}
/*! \remarks This method returns the value of the index. */
int GetIndex() { return index; }
/*! \remarks This method allows you to set the index. */
void SetIndex(int id) { index = id; }
/*! \remarks This method returns the position data. */
Point3 GetPos() { return pos; }
/*! \remarks This method allows you to set the position data.
\par Parameters:
<b>Point3 p</b>\n\n
The position to set. */
void SetPos(Point3 p) { pos = p; }
/*! \remarks This method returns the velocity data. */
Point3 GetVel() { return vel; }
/*! \remarks This method allows you to set the velocity data.
\par Parameters:
<b>Point3 v</b>\n\n
The velocity data to set. */
void SetVel(Point3 v) { vel = v; }
/*! \remarks Compares this class instance to another one */
bool operator ==( const SSConstraintPoint& b ) const
{
return index == b.index && pos == b.pos && vel == b.vel;
}
};
/*! \sa Class SSConstraintPoint, Class SpringSys\n\n
This class represents the particle cache to store the state of particle data as
it is used in the spring system. */
class SSParticleCache: public MaxHeapOperators
{
public:
//! The control node stored position.
Point3 pos;
//! The control node stored velocity.
Point3 vel;
//! The array of spring system constraint points.
MaxSDK::Array<SSConstraintPoint> bone;
/*! \remarks Constructor.
\par Default Implementation:
<b>{pos = Point3(0,0,0); vel = Point3(0,0,0);}</b> */
SSParticleCache() {pos = Point3(0,0,0); vel = Point3(0,0,0); }
};
/*! \sa Class BaseInterfaceServer, Class SSConstraintPoint, Class SpringSys\n\n
Stores the parameters for binding an object to any force with a controllable spring.
This class represents the particle cache to store the state of particle data as
it is used in the spring system. */
class SSSpring : public BaseInterfaceServer
{
private:
//! The spring tension value.
float tension;
//! The spring dampening value.
float dampening;
//! The spring rest length.
Point3 length;
//! The spring system constraint point.
SSConstraintPoint bone;
public:
/*! \remarks Constructor.
\par Default Implementation:
<b>{</b>\n\n
<b> bone = NULL;</b>\n\n
<b> length = Point3(0.0f, 0.0f, 0.0f);</b>\n\n
<b> tension = 1.0f;</b>\n\n
<b> dampening = 0.5f;</b>\n\n
<b>}</b> */
SSSpring()
{
bone = NULL;
length = Point3(0.0f, 0.0f, 0.0f);
tension = 1.0f;
dampening = 0.5f;
}
/*! \remarks Constructor.\n\n
This allows you to initialize the spring.
\par Parameters:
<b>SSConstraintPoint *b</b>\n\n
The constraint point to set.\n\n
<b>Point3 l</b>\n\n
The spring length to set.\n\n
<b>float t=2.0f</b>\n\n
The tension to set.\n\n
<b>float d=1.0f</b>\n\n
The dampening to set.
\par Default Implementation:
<b>{</b>\n\n
<b> bone = *b;</b>\n\n
<b> length = l;</b>\n\n
<b> tension = t;</b>\n\n
<b> dampening = d;</b>\n\n
<b>}</b> */
SSSpring(SSConstraintPoint *b, Point3 l, float t=2.0f, float d=1.0f)
{
bone = *b;
length = l;
tension = t;
dampening = d;
}
/*! \remarks Assignment operator. */
SSSpring& operator=(const SSSpring& from)
{
tension = from.tension;
dampening = from.dampening;
length = from.length;
bone = from.bone;
return *this;
}
/*! \remarks This method allows you to copy the data from the
specified spring object.
\par Parameters:
<b>const SSSpring from</b>\n\n
The spring to copy from. */
SSSpring Copy(const SSSpring from)
{
tension = from.tension;
dampening = from.dampening;
length = from.length;
bone = from.bone;
return *this;
}
/*! \remarks This method returns the tension value. */
float GetTension() {return tension;}
/*! \remarks This method allows you to set the tension value.
\par Parameters:
<b>float t</b>\n\n
The tension to set. */
void SetTension(float t) {tension = t;}
/*! \remarks This method returns the dampening value. */
float GetDampening() {return dampening;}
/*! \remarks This method allows you to set the dampening value.
\par Parameters:
<b>float d</b>\n\n
The dampening value to set. */
void SetDampening(float d) {dampening = d;}
/*! \remarks This method returns the length of the spring. */
Point3 GetLength() {return length;}
/*! \remarks This method allows you to set the spring length.
\par Parameters:
<b>Point3 len</b>\n\n
The spring length to set. */
void SetLength(Point3 len) {length = len;}
/*! \remarks This method returns the point constraint data. */
SSConstraintPoint* GetPointConstraint() { return &bone;}
/*! \remarks This method allows you to set the point constraint data.
\par Parameters:
<b>SSConstraintPoint b</b>\n\n
The constraint point to set. */
void SetPointConstraint(SSConstraintPoint b) { bone = b; }
/*! \remarks This method allos you to set the point constraint data.
\par Parameters:
<b>int id</b>\n\n
The index.\n\n
<b>Point3 pos</b>\n\n
The position data.\n\n
<b>Point3 vel</b>\n\n
The velocity data. */
void SetPointConstraint(int id, Point3 pos, Point3 vel)
{
bone.SetIndex(id);
bone.SetPos(pos);
bone.SetVel(vel);
}
/*! \remarks Compares this class instance to another one */
bool operator ==( const SSSpring& b ) const
{
return tension == b.tension && dampening == b.dampening && length == b.length && bone == b.bone;
}
bool operator !=( const SSSpring& b ) const
{
return !( *this == b );
}
};
/*! \sa Class SpringSys, Class SSSpring, Class SSConstraintPoint\n\n
This class represents the spring system particle. */
class SSParticle: public MaxHeapOperators
{
friend class SpringSys;
private:
//! The spring particle mass.
float mass;
//! The spring particle drag.
float drag;
//! The particle position.
Point3 pos;
//! The particle velocity.
Point3 vel;
//! The Force accumulator.
Point3 force;
//! The collection of spring system springs
MaxSDK::Array<SSSpring> springs;
public:
/*! \remarks Constructor.
\par Default Implementation:
<b>{</b>\n\n
<b> mass = 300.0f;</b>\n\n
<b> drag = 1.0f;</b>\n\n
<b> pos = vel = force = Point3(0.0f,0.0f,0.0f);</b>\n\n
<b> springs.ZeroCount();</b>\n\n
<b>}</b> */
SSParticle()
{
mass = 300.0f;
drag = 1.0f;
pos = vel = force = Point3(0.0f,0.0f,0.0f);
springs.removeAll();
}
/*! \remarks Destructor.
\par Default Implementation:
<b>{ }</b> */
~SSParticle(){}
/*! \remarks Assignment operator. */
SSParticle& operator=(const SSParticle& from)
{
mass = from.mass;
drag = from.drag;
pos = from.pos;
vel = from.vel;
force = from.force;
springs.removeAll();
for (size_t i=0; i < from.springs.length(); i++)
{
SSSpring spring = from.springs[i];
springs.append(spring);
}
return *this;
}
/*! \remarks This method allows you to copy the data from the
specified <b>SSParticle</b>.
\par Parameters:
<b>const SSParticle from</b>\n\n
The spring system particle to copy from. */
SSParticle Copy(const SSParticle from)
{
SSSpring spring;
mass = from.mass;
drag = from.drag;
pos = from.pos;
vel = from.vel;
force = from.force;
springs.removeAll();
for (size_t i = 0; i < from.springs.length(); i++)
{
spring.Copy(from.springs[i]);
springs.append(spring);
}
return *this;
}
/*! \remarks This method returns the spring particle mass. */
float GetMass() {return mass;}
/*! \remarks This method allows you to set the spring particle mass.
\par Parameters:
<b>float m</b>\n\n
The mass to set. */
void SetMass(float m) {mass = m;}
/*! \remarks This method returns the spring particle drag. */
float GetDrag() {return drag;}
/*! \remarks This method allows you to set the spring particle drag.
\par Parameters:
<b>float d</b>\n\n
The drag value to set. */
void SetDrag(float d) {drag = d;}
/*! \remarks This method returns the spring particle position. */
Point3 GetPos() {return pos;}
/*! \remarks This method allows you to set the spring particle
position.
\par Parameters:
<b>Point3 p</b>\n\n
The position to set. */
void SetPos(Point3 p) {pos = p;}
/*! \remarks This method returns the spring particle velocity. */
Point3 GetVel() {return vel;}
/*! \remarks This method allows you to set the spring particle
velocity.
\par Parameters:
<b>Point3 v</b>\n\n
The velocity to set. */
void SetVel(Point3 v) {vel = v;}
/*! \remarks This method returns the spring particle force. */
Point3 GetForce() {return force;}
/*! \remarks This method allows you to set the spring particle force.
\par Parameters:
<b>Point3 f</b>\n\n
The force to set. */
void SetForce(Point3 f) {force = f;}
/*! \remarks This method returns a pointer to the collection of springs. */
MaxSDK::Array<SSSpring>* GetSprings() { return &springs;}
/*! \remarks This method returns a pointer to the I-th spring in the
array.
\par Parameters:
<b>int i</b>\n\n
The index of the spring to return. */
SSSpring* GetSpring(int i) {if (i>=0 && i < (int)springs.length()) return &(springs[i]);
else return NULL; }
/*! \remarks This method allows you to set the specified spring at the
specified I-th index in the array.
\par Parameters:
<b>int i</b>\n\n
The index of the spring to set.\n\n
<b>SSSpring spring</b>\n\n
The spring to set. */
void SetSpring(int i, SSSpring spring) {if (i>=0 && i < (int)springs.length())
springs[i] = spring; }
/*! \remarks This method allows you to set the entire spring array.
\par Parameters:
<b>MaxSDK::Array\<SSSpring\>springsArray</b>\n\n
The array of springs to set. */
void SetSprings(const MaxSDK::Array<SSSpring>& springsArray)
{
springs.removeAll();
for (size_t i = 0; i < springsArray.length();i++)
{
springs.append(springsArray[i]);
}
}
/*! \remarks This method allows you to add a spring to the array.
Note that if the spring already exists it will be made stronger.
\par Parameters:
<b>SSConstraintPoint *bone</b>\n\n
A pointer to the spring system constraint point to set.\n\n
<b>Point3 length</b>\n\n
The length of the spring.\n\n
<b>tension=2.0f</b>\n\n
The tension of the spring.\n\n
<b>float dampening = 1.0f</b>\n\n
The dampening value of the spring.
\return TRUE if the spring was added, FALSE if the spring was made
stronger. */
SpringSysExport BOOL AddSpring(SSConstraintPoint *bone, Point3 length, float tension=2.0f, float dampening = 1.0f);
/*! \remarks This method allows you to delete a spring.
\par Parameters:
<b>int index</b>\n\n
The index in the array of the spring to delete. */
void DeleteSpring(int index)
{
if ( index == 0 )
return;
for (size_t i = 0;i < springs.length(); i++)
{
if ( (springs[i].GetPointConstraint()->GetIndex()) == index)
springs.removeAt(i--);
else if (springs[i].GetPointConstraint()->GetIndex() > index)
springs[i].GetPointConstraint()->SetIndex(springs[i].GetPointConstraint()->GetIndex()-1);
}
}
/*! \remarks Compares this class instance to another one */
bool operator ==( const SSParticle& b ) const
{
return mass == b.mass && drag == b.drag && pos == b.pos && vel == b.vel && force == b.force && springs == b.springs;
}
};
/*! \sa Class SpringSys\n\n
This class describes a spring system client as used by the SpringSys class. */
class SpringSysClient: public MaxHeapOperators
{
public:
/*! \remarks This method returns the forces acting inside the spring system.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to get the force matrices. */
virtual Tab<Matrix3> GetForceMatrices(TimeValue t)=0;
/*! \remarks This method returns the dynamic forces acting inside the
spring system.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to get the forces.\n\n
<b>Point3 pos</b>\n\n
The position force.\n\n
<b>Point3 vel</b>\n\n
The velocity force.
\par Default Implementation:
<b>{ return Point3(0,0,0); }</b> */
virtual Point3 GetDynamicsForces(TimeValue t, Point3 pos, Point3 vel)
{
UNUSED_PARAM(t);
UNUSED_PARAM(pos);
UNUSED_PARAM(vel);
return Point3(0,0,0);
}
};
/*! \sa Class BaseInterfaceServer, Class SSParticle, Class SSParticleCache, Class SpringSysClient , Class IJiggle\n\n
\par Description:
This class is the main spring system class.
This spring system is a multi-point spring-based dynamic system.
In order to your the system you must derive from
<b>SpringSysClient</b> and implement the
<b>SpringSysClient::GetForceMatrices()</b> method You are responsible for
gathering the spring constraint forces at any given time.\n\n
The spring system uses its own position and velocity to determine its motion,
as well as allowing you to add multiple spring constraints to any other objects
in the scene. Multiple constraints act like multiple links.\n\n
The solution is calculated using a start time and a step size. Solutions are
cached once for the last tick calculated, and once per frame. Performance
should be the same one each frame as you step forward, and significantly faster
after the first pass if nothing changes. Cached values will be used if going
backwards in time. */
class SpringSys : public BaseInterfaceServer
{
private:
//! The stored reference time.
float referenceTime;
//! The stored last time.
float lastTime;
//! This flag indicates whether the spring system is valid.
bool isValid;
//! The spring system particle cache.
SSParticleCache frameCache;
//! The cached table of positions.
Tab<Point3> pos_cache;
//! The cached table of velocities.
Tab<Point3> vel_cache;
//! The table of initial positions.
Tab<Point3> initPosTab;
//! The table of spring system particles.
MaxSDK::Array<SSParticle> parts;
//! The spring system client object.
SpringSysClient* client;
public:
/*! \remarks Constructor. */
SpringSys()
{
client = NULL;
referenceTime = lastTime = 0.0f;
SetParticleCount(1);
isValid = false;
}
/*! \remarks Constructor.\n\n
Initialize the class with the specified data.
\par Parameters:
<b>SpringSysClient* c</b>\n\n
A pointer to the spring system client class.\n\n
<b>int count</b>\n\n
The number of spring system particles. */
SpringSys(SpringSysClient* c, int count)
{
client = c;
referenceTime = lastTime = 0.0f;
SetParticleCount(count);
isValid = false;
}
/*! \remarks Destructor. */
~SpringSys() {}
/*! \remarks Assignment operator. */
SpringSysExport SpringSys& operator=(const SpringSys& from);
/*! \remarks This method allows you to copy the data from the
specified spring system.
\par Parameters:
<b>const SpringSys* from</b>\n\n
The spring system to copy the data from. */
SpringSysExport SpringSys Copy(const SpringSys* from);
/*! \remarks This method allows you to set the reference time.
\par Parameters:
<b>float t</b>\n\n
The reference time to set. */
void SetReferenceTime (float t) { referenceTime = t; }
/*! \remarks This method returns the reference time. */
float GetReferenceTime () { return referenceTime; }
/*! \remarks This method returns a pointer to the array of spring
system particles. */
MaxSDK::Array<SSParticle>* GetParticles() { return &parts;}
/*! \remarks This method returns a pointer to the I-th spring system
particle.
\par Parameters:
<b>int i</b>\n\n
The index of the spring system particle in the array. */
SSParticle* GetParticle(int i) { if (i >=0 && i< (int)parts.length()) return &(parts[i]);
else return NULL; }
/*! \remarks This method allows you to set the number of particles in
the spring system.
\par Parameters:
<b>int count</b>\n\n
The number of particles to set. */
SpringSysExport void SetParticleCount(int count);
/*! \remarks This method allows you to set the initial position for
the specified spring system particle.
\par Parameters:
<b>Point3 p</b>\n\n
The initial position to set.\n\n
<b>int partIndex</b>\n\n
The index of the particle in the array for which to set the initial
position. */
SpringSysExport void SetInitialPosition (Point3 p, int partIndex);
/*! \remarks This method allows you to set the initial velocity for
the specified spring system particle.
\par Parameters:
<b>Point3 p</b>\n\n
The initial velocity to set.\n\n
<b>int partIndex</b>\n\n
The index of the particle in the array for which to set the initial
velocity. */
SpringSysExport void SetInitialVelocity (Point3 p, int partIndex);
/*! \remarks This method allows you to set the initial bone states for
the spring system.
\par Parameters:
<b>Tab\<Matrix3\> boneTMs</b>\n\n
The bone transformation matrices to set. */
SpringSysExport void SetInitialBoneStates(Tab<Matrix3> boneTMs);
/*! \remarks This method will invalidate the spring system and issue
the re-computation of the spring system state. */
SpringSysExport void Invalidate ();
/*! \remarks This method allows you to solve the spring system
dynamics.
\par Parameters:
<b>int time</b>\n\n
The time at which to solve\n\n
<b>float TimeDelta</b>\n\n
The time difference. */
SpringSysExport void Solve (int time, float TimeDelta);
/*! \remarks This method returns the position of the specified spring
system particle.
\par Parameters:
<b>Point3\& p</b>\n\n
The position which is returned\n\n
<b>int index</b>\n\n
The index of the spring system particle in the array. <br> protected:
*/
SpringSysExport void GetPosition (Point3& p, int index);
SpringSysExport IOResult Load(ILoad *iload);
SpringSysExport IOResult Save(ISave *isave);
protected:
/*! \remarks This method allows you to get the spring system last
time.
\par Default Implementation:
<b>{ return lastTime; }</b> */
float GetTime() { return lastTime; }
/*! \remarks This method allows you to set the spring system last
time.
\par Parameters:
<b>float t</b>\n\n
The time to set.
\par Default Implementation:
<b>{ lastTime = t; }</b> */
void SetTime(float t) { lastTime = t; }
//force functions
/*! \remarks This method will clear the forces acting upon the
specified spring system particle.
\par Parameters:
<b>int index</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void Clear_Forces(int index);
/*! \remarks This method will compute the forces acting upon the
specified spring system particle..
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to compute the forces.\n\n
<b>int index</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void Compute_Forces(TimeValue t, int index);
/*! \remarks This method will apply the drag forces onto the specified
spring system particle.
\par Parameters:
<b>int index</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void ApplyDrag(int index);
/*! \remarks This method will apply the unary forces onto the
specified spring system particle.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to apply the unary forces.\n\n
<b>int index</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void ApplyUnaryForces(TimeValue t, int index);
/*! \remarks This method will compute the controlled particle force.
\par Parameters:
<b>Matrix3 tm</b>\n\n
The transformation matrix.\n\n
<b>int vertIndex</b>\n\n
The vertex index for which to compute the controlled particle
force.\n\n
<b>int springIndex</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void ComputeControlledParticleForce(Matrix3 tm, int vertIndex, int springIndex);
/*! \remarks This method will apply the spring to the specified spring
system particle.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to apply the unary forces.\n\n
<b>int index</b>\n\n
The index into the array of spring system particles. */
SpringSysExport void ApplySpring(TimeValue t, int index);
//Solver functions
/*! \remarks This method will update the particle state.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to apply the unary forces.\n\n
<b>Tab\<Matrix3\> tmArray</b>\n\n
The table of transformation matrices.\n\n
<b>int pIndex</b>\n\n
The index into the table of spring system particles.\n\n
<b>TimeValue Delta</b>\n\n
The time difference for which to update. */
SpringSysExport void UpdateParticleState(TimeValue t, Tab<Matrix3> tmArray, int pIndex, TimeValue Delta);
/*! \remarks This method will compute the derivative forces for the
specified spring system particle.
\par Parameters:
<b>int index</b>\n\n
The index into the table of spring system particles.\n\n
<b>Point3 \&pos</b>\n\n
The computed position.\n\n
<b>Point3 \&vel</b>\n\n
The computed velocity. */
SpringSysExport void ComputeDerivative(int index, Point3 &pos, Point3 &vel);
/*! \remarks This method retrieves the state of the specified spring
system particle.
\par Parameters:
<b>int index</b>\n\n
The index into the table of spring system particles.\n\n
<b>Point3 \&pos</b>\n\n
The current position.\n\n
<b>Point3 \&vel</b>\n\n
The current velocity. */
SpringSysExport void GetParticleState(int index, Point3 &pos, Point3 &vel);
/*! \remarks This method allows you to set the particle state of the
specified spring system particle.
\par Parameters:
<b>int index</b>\n\n
The index into the table of spring system particles.\n\n
<b>Point3 pos</b>\n\n
The position to set.\n\n
<b>Point3 vel</b>\n\n
The velocity to set. */
SpringSysExport void SetParticleState(int index, Point3 pos, Point3 vel);
/*! \remarks This method allows you to scale the vectors by the
specified difference.
\par Parameters:
<b>Point3 \&pos</b>\n\n
The scaled position.\n\n
<b>Point3 \&vel</b>\n\n
The scaled velocity.\n\n
<b>float delta</b>\n\n
The time difference to scale by. */
SpringSysExport void ScaleVectors(Point3 &pos, Point3 &vel, float delta);
/*! \remarks This method allows you to add vector forces to the spring
system.
\par Parameters:
<b>Point3 pos1, vel1</b>\n\n
The position and velocity to add.\n\n
<b>Point3 \&pos, \&vel</b>\n\n
The position and velocity. */
SpringSysExport void AddVectors(Point3 pos1, Point3 vel1, Point3 &pos, Point3 &vel);
};
|
kshman/sblsp
|
sbqgp/exp_3dsmax/include/springsys.h
|
C
|
bsd-3-clause
| 26,543 |
/*! normalize.css v1.0.0 | MIT License | git.io/normalize */
/* ===[ HTML5 display definitions ]========================================== */
/*
* Corrects `block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
nav,
section,
summary {
display: block;
}
/*
* Corrects `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
audio,
canvas,
video {
display: inline-block;
*display: inline;
*zoom: 1;
}
/*
* Prevents modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/*
* Addresses styling for `hidden` attribute not present in IE 7/8/9, Firefox 3,
* and Safari 4.
* Known issue: no IE 6 support.
*/
[hidden] {
display: none;
}
/* ===[ Base ]=============================================================== */
/*
* 1. Corrects text resizing oddly in IE 6/7 when body `font-size` is set using
* `em` units.
* 2. Prevents iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-size: 100%; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
-ms-text-size-adjust: 100%; /* 2 */
}
/*
* Addresses `font-family` inconsistency between `textarea` and other form
* elements.
*/
html,
button,
input,
select,
textarea {
font-family: sans-serif;
}
/*
* Addresses margins handled incorrectly in IE 6/7.
*/
body {
margin: 0;
}
/* ===[ Links ]============================================================== */
/*
* Addresses `outline` inconsistency between Chrome and other browsers.
*/
a:focus {
outline: thin dotted;
}
/*
* Improves readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* ===[ Typography ]========================================================= */
/*
* Addresses font sizes and margins set differently in IE 6/7.
* Addresses font sizes within `section` and `article` in Firefox 4+, Safari 5,
* and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
h2 {
font-size: 1.5em;
margin: 0.83em 0;
}
h3 {
font-size: 1.17em;
margin: 1em 0;
}
h4 {
font-size: 1em;
margin: 1.33em 0;
}
h5 {
font-size: 0.83em;
margin: 1.67em 0;
}
h6 {
font-size: 0.75em;
margin: 2.33em 0;
}
/*
* Addresses styling not present in IE 7/8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/*
* Addresses style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
blockquote {
margin: 1em 40px;
}
/*
* Addresses styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/*
* Addresses styling not present in IE 6/7/8/9.
*/
mark {
background: #ff0;
color: #000;
}
/*
* Addresses margins set differently in IE 6/7.
*/
p,
pre {
margin: 1em 0;
}
/*
* Corrects font family set oddly in IE 6, Safari 4/5, and Chrome.
*/
code,
kbd,
pre,
samp {
font-family: monospace, serif;
_font-family: 'courier new', monospace;
font-size: 1em;
}
/*
* Improves readability of pre-formatted text in all browsers.
*/
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
/*
* Addresses CSS quotes not supported in IE 6/7.
*/
q {
quotes: none;
}
/*
* Addresses `quotes` property not supported in Safari 4.
*/
q:before,
q:after {
content: '';
content: none;
}
small {
font-size: 75%;
}
/*
* Prevents `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* ===[ Lists ]============================================================== */
/*
* Addresses margins set differently in IE 6/7.
*/
dl,
menu,
ol,
ul {
margin: 1em 0;
}
dd {
margin: 0 0 0 40px;
}
/*
* Addresses paddings set differently in IE 6/7.
*/
menu,
ol,
ul {
padding: 0 0 0 40px;
}
/*
* Corrects list images handled incorrectly in IE 7.
*/
nav ul,
nav ol {
list-style: none;
list-style-image: none;
}
/* ===[ Embedded content ]=================================================== */
/*
* 1. Removes border when inside `a` element in IE 6/7/8/9 and Firefox 3.
* 2. Improves image quality when scaled in IE 7.
*/
img {
border: 0; /* 1 */
-ms-interpolation-mode: bicubic; /* 2 */
}
/*
* Corrects overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* ===[ Figures ]============================================================ */
/*
* Addresses margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
*/
figure {
margin: 0;
}
/* ===[ Forms ]============================================================== */
/*
* Corrects margin displayed oddly in IE 6/7.
*/
form {
margin: 0;
}
/*
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/*
* 1. Corrects color not being inherited in IE 6/7/8/9.
* 2. Corrects text not wrapping in Firefox 3.
* 3. Corrects alignment displayed oddly in IE 6/7.
*/
legend {
border: 0; /* 1 */
padding: 0;
white-space: normal; /* 2 */
*margin-left: -7px; /* 3 */
}
/*
* 1. Corrects font size not being inherited in all browsers.
* 2. Addresses margins set differently in IE 6/7, Firefox 3+, Safari 5,
* and Chrome.
* 3. Improves appearance and consistency in all browsers.
*/
button,
input,
select,
textarea {
font-size: 100%; /* 1 */
margin: 0; /* 2 */
vertical-align: baseline; /* 3 */
*vertical-align: middle; /* 3 */
}
/*
* Addresses Firefox 3+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
button,
input {
line-height: normal;
}
/*
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Corrects inability to style clickable `input` types in iOS.
* 3. Improves usability and consistency of cursor style between image-type
* `input` and others.
* 4. Removes inner spacing in IE 7 without affecting normal text inputs.
* Known issue: inner spacing remains in IE 6.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
*overflow: visible; /* 4 */
}
/*
* Re-set default cursor for disabled elements.
*/
button[disabled],
input[disabled] {
cursor: default;
}
/*
* 1. Addresses box sizing set to content-box in IE 8/9.
* 2. Removes excess padding in IE 8/9.
* 3. Removes excess padding in IE 7.
* Known issue: excess padding remains in IE 6.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
*height: 13px; /* 3 */
*width: 13px; /* 3 */
}
/*
* 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/*
* Removes inner padding and search cancel button in Safari 5 and Chrome
* on OS X.
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
* Removes inner padding and border in Firefox 3+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/*
* 1. Removes default vertical scrollbar in IE 6/7/8/9.
* 2. Improves readability and alignment in all browsers.
*/
textarea {
overflow: auto; /* 1 */
vertical-align: top; /* 2 */
}
/* ===[ Tables ]============================================================= */
/*
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
|
mozilla/mozilla-badges
|
mozbadges/site/base/static/css/normalize.css
|
CSS
|
bsd-3-clause
| 7,859 |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is configman
#
# The Initial Developer of the Original Code is
# Mozilla Foundation
# Portions created by the Initial Developer are Copyright (C) 2011
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# K Lars Lohn, [email protected]
# Peter Bengtsson, [email protected]
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
class DotDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
|
twobraids/configman_orginal
|
configman/dotdict.py
|
Python
|
bsd-3-clause
| 1,840 |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_PhotoatomACEFactory.hpp
//! \author Alex Robinson
//! \brief The photoatom ace factory class declaration.
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_PHOTOATOM_ACE_FACTORY_HPP
#define MONTE_CARLO_PHOTOATOM_ACE_FACTORY_HPP
// Trilinos Includes
#include <Teuchos_RCP.hpp>
// FRENSIE Includes
#include "MonteCarlo_Photoatom.hpp"
#include "MonteCarlo_PhotoatomCore.hpp"
#include "MonteCarlo_AtomicRelaxationModel.hpp"
#include "MonteCarlo_IncoherentModelType.hpp"
#include "Data_XSSEPRDataExtractor.hpp"
namespace MonteCarlo{
//! The Photoatomic factory class that uses ACE data
class PhotoatomACEFactory
{
public:
//! Create a photoatom core (using the provided atomic relaxation model)
static void createPhotoatomCore(
const Data::XSSEPRDataExtractor& raw_photoatom_data,
const Teuchos::RCP<AtomicRelaxationModel>& atomic_relaxation_model,
Teuchos::RCP<PhotoatomCore>& photoatom_core,
const unsigned hash_grid_bins,
const IncoherentModelType incoherent_model,
const double kahn_sampling_cutoff_energy,
const bool use_detailed_pair_production_data,
const bool use_atomic_relaxation_data );
//! Create a photoatom (using the provided atomic relaxation model)
static void createPhotoatom(
const Data::XSSEPRDataExtractor& raw_photoatom_data,
const std::string& photoatom_name,
const double atomic_weight,
const Teuchos::RCP<AtomicRelaxationModel>& atomic_relaxation_model,
Teuchos::RCP<Photoatom>& photoatom,
const unsigned hash_grid_bins,
const IncoherentModelType incoherent_model,
const double kahn_sampling_cutoff_energy,
const bool use_detailed_pair_production_data,
const bool use_atomic_relaxation_data );
private:
// Constructor
PhotoatomACEFactory();
};
} // end MonteCarlo
#endif // end MONTE_CARLO_PHOTOATOM_ACE_FACTORY_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_PhotoatomACEFactory.hpp
//---------------------------------------------------------------------------//
|
lkersting/SCR-2123
|
packages/monte_carlo/collision/native/src/MonteCarlo_PhotoatomACEFactory.hpp
|
C++
|
bsd-3-clause
| 2,215 |
# A Tour of Go Exercise
[A Tour of Go](http://go-tour-jp.appspot.com/#1)
## Setup
```bash
$ got get https://code.google.com/p/go-tour
```
|
koshigoe/a-tour-of-go-exercise
|
README.md
|
Markdown
|
bsd-3-clause
| 141 |
---
layout: default
title: Basic Usage
description: Basic usage of the CommonMark parser
---
# Basic Usage
<i class="fa fa-exclamation-triangle"></i>
**Important:** See the [security](/2.2/security/) section for important details on avoiding security misconfigurations.
The `CommonMarkConverter` class provides a simple wrapper for converting Markdown to HTML:
```php
require __DIR__ . '/vendor/autoload.php';
use League\CommonMark\CommonMarkConverter;
$converter = new CommonMarkConverter();
echo $converter->convert('# Hello World!');
// <h1>Hello World!</h1>
```
Or if you want GitHub-Flavored Markdown:
```php
require __DIR__ . '/vendor/autoload.php';
use League\CommonMark\GithubFlavoredMarkdownConverter;
$converter = new GithubFlavoredMarkdownConverter();
echo $converter->convert('# Hello World!');
// <h1>Hello World!</h1>
```
## Using Extensions
The `CommonMarkConverter` and `GithubFlavoredMarkdownConverter` shown above automatically configure [the environment](/2.2/customization/environment/) for you, but if you want to use [additional extensions](/2.2/customization/extensions/) you'll need to avoid those classes and use the generic `MarkdownConverter` class instead to customize [the environment](/2.2/customization/environment/) with whatever extensions you wish to use:
```php
require __DIR__ . '/vendor/autoload.php';
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
use League\CommonMark\Extension\SmartPunct\SmartPunctExtension;
use League\CommonMark\Extension\Strikethrough\StrikethroughExtension;
use League\CommonMark\MarkdownConverter;
$environment = new Environment();
$environment->addExtension(new InlinesOnlyExtension());
$environment->addExtension(new SmartPunctExtension());
$environment->addExtension(new StrikethroughExtension());
$converter = new MarkdownConverter($environment);
echo $converter->convert('**Hello World!**');
// <p><strong>Hello World!</strong></p>
```
## Configuration
If you're using the `CommonMarkConverter` or `GithubFlavoredMarkdownConverter` class you can pass configuration options directly into their constructor:
```php
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\GithubFlavoredMarkdownConverter;
$converter = new CommonMarkConverter($config);
// or
$converter = new GithubFlavoredMarkdownConverter($config);
```
Otherwise, if you’re using `MarkdownConverter` to customize the extensions in your parser, pass the configuration into the `Environment`'s constructor instead:
```php
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
use League\CommonMark\MarkdownConverter;
// Here's where we set the configuration array:
$environment = new Environment($config);
// TODO: Add any/all the extensions you wish; for example:
$environment->addExtension(new InlinesOnlyExtension());
// Go forth and convert you some Markdown!
$converter = new MarkdownConverter($environment);
```
See the [configuration section](/2.2/configuration/) for more information on the available configuration options.
## Supported Character Encodings
Please note that only UTF-8 and ASCII encodings are supported. If your Markdown uses a different encoding please convert it to UTF-8 before running it through this library.
## Return Value
The `convert()` method actually returns an instance of `League\CommonMark\Output\RenderedContentInterface`. You can cast this (implicitly, as shown above, or explicitly) to a `string` or call `getContent()` to get the final HTML output.
|
thephpleague/commonmark
|
docs/2.2/basic-usage.md
|
Markdown
|
bsd-3-clause
| 3,594 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from datetime import datetime
from uuid import UUID
from sentry.coreapi import (
APIError, APIUnauthorized, Auth, ClientApiHelper, InvalidFingerprint,
InvalidTimestamp, get_interface, CspApiHelper,
)
from sentry.testutils import TestCase
class BaseAPITest(TestCase):
helper_cls = ClientApiHelper
def setUp(self):
self.user = self.create_user('[email protected]')
self.team = self.create_team(name='Foo')
self.project = self.create_project(team=self.team)
self.pm = self.project.team.member_set.get_or_create(user=self.user)[0]
self.pk = self.project.key_set.get_or_create()[0]
self.helper = self.helper_cls(agent='Awesome Browser', ip_address='69.69.69.69')
class AuthFromRequestTest(BaseAPITest):
def test_valid(self):
request = mock.Mock()
request.META = {'HTTP_X_SENTRY_AUTH': 'Sentry sentry_key=value, biz=baz'}
result = self.helper.auth_from_request(request)
assert result.public_key == 'value'
def test_invalid_header_defers_to_GET(self):
request = mock.Mock()
request.META = {'HTTP_X_SENTRY_AUTH': 'foobar'}
request.GET = {'sentry_version': '1', 'foo': 'bar'}
result = self.helper.auth_from_request(request)
assert result.version == '1'
def test_invalid_legacy_header_defers_to_GET(self):
request = mock.Mock()
request.META = {'HTTP_AUTHORIZATION': 'foobar'}
request.GET = {'sentry_version': '1', 'foo': 'bar'}
result = self.helper.auth_from_request(request)
assert result.version == '1'
class ProjectFromAuthTest(BaseAPITest):
def test_invalid_if_missing_key(self):
self.assertRaises(APIUnauthorized, self.helper.project_from_auth, Auth({}))
def test_valid_with_key(self):
auth = Auth({'sentry_key': self.pk.public_key})
result = self.helper.project_from_auth(auth)
self.assertEquals(result, self.project)
def test_invalid_key(self):
auth = Auth({'sentry_key': 'z'})
self.assertRaises(APIUnauthorized, self.helper.project_from_auth, auth)
def test_invalid_secret(self):
auth = Auth({'sentry_key': self.pk.public_key, 'sentry_secret': 'z'})
self.assertRaises(APIUnauthorized, self.helper.project_from_auth, auth)
class ProcessFingerprintTest(BaseAPITest):
def test_invalid_as_string(self):
self.assertRaises(InvalidFingerprint, self.helper._process_fingerprint, {
'fingerprint': '2012-01-01T10:30:45',
})
def test_invalid_component(self):
self.assertRaises(InvalidFingerprint, self.helper._process_fingerprint, {
'fingerprint': ['foo', ['bar']],
})
def simple(self):
data = self.helper._process_fingerprint({
'fingerprint': ['{{default}}', 1, 'bar', 4.5],
})
self.assertTrue('fingerprint' in data)
self.assertEquals(data['fingerprint'], ['{{default}}', '1', 'bar', '4.5'])
class ProcessDataTimestampTest(BaseAPITest):
def test_iso_timestamp(self):
d = datetime(2012, 01, 01, 10, 30, 45)
data = self.helper._process_data_timestamp({
'timestamp': '2012-01-01T10:30:45'
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], 1325413845.0)
def test_iso_timestamp_with_ms(self):
d = datetime(2012, 01, 01, 10, 30, 45, 434000)
data = self.helper._process_data_timestamp({
'timestamp': '2012-01-01T10:30:45.434'
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], 1325413845.0)
def test_timestamp_iso_timestamp_with_Z(self):
d = datetime(2012, 01, 01, 10, 30, 45)
data = self.helper._process_data_timestamp({
'timestamp': '2012-01-01T10:30:45Z'
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], 1325413845.0)
def test_invalid_timestamp(self):
self.assertRaises(InvalidTimestamp, self.helper._process_data_timestamp, {
'timestamp': 'foo'
})
def test_invalid_numeric_timestamp(self):
self.assertRaises(InvalidTimestamp, self.helper._process_data_timestamp, {
'timestamp': '100000000000000000000.0'
})
def test_future_timestamp(self):
self.assertRaises(InvalidTimestamp, self.helper._process_data_timestamp, {
'timestamp': '2052-01-01T10:30:45Z'
})
def test_long_microseconds_value(self):
d = datetime(2012, 01, 01, 10, 30, 45)
data = self.helper._process_data_timestamp({
'timestamp': '2012-01-01T10:30:45.341324Z'
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], 1325413845.0)
class ValidateDataTest(BaseAPITest):
def test_missing_project_id(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
})
assert data['project'] == self.project.id
@mock.patch('uuid.uuid4', return_value=UUID('031667ea1758441f92c7995a428d2d14'))
def test_empty_event_id(self, uuid4):
data = self.helper.validate_data(self.project, {
'event_id': '',
})
assert data['event_id'] == '031667ea1758441f92c7995a428d2d14'
@mock.patch('uuid.uuid4', return_value=UUID('031667ea1758441f92c7995a428d2d14'))
def test_missing_event_id(self, uuid4):
data = self.helper.validate_data(self.project, {})
assert data['event_id'] == '031667ea1758441f92c7995a428d2d14'
@mock.patch('uuid.uuid4', return_value=UUID('031667ea1758441f92c7995a428d2d14'))
def test_invalid_event_id(self, uuid4):
data = self.helper.validate_data(self.project, {
'event_id': 'a' * 33,
})
assert data['event_id'] == '031667ea1758441f92c7995a428d2d14'
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'value_too_long'
assert data['errors'][0]['name'] == 'event_id'
assert data['errors'][0]['value'] == 'a' * 33
def test_invalid_event_id_raises(self):
self.assertRaises(APIError, self.helper.validate_data, self.project, {
'event_id': 1
})
def test_unknown_attribute(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'foo': 'bar',
})
assert 'foo' not in data
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'invalid_attribute'
assert data['errors'][0]['name'] == 'foo'
def test_invalid_interface_name(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'foo.baz': 'bar',
})
assert 'foo.baz' not in data
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'invalid_attribute'
assert data['errors'][0]['name'] == 'foo.baz'
def test_invalid_interface_import_path(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'sentry.interfaces.Exception2': 'bar',
})
assert 'sentry.interfaces.Exception2' not in data
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'invalid_attribute'
assert data['errors'][0]['name'] == 'sentry.interfaces.Exception2'
def test_does_expand_list(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'exception': [{
'type': 'ValueError',
'value': 'hello world',
'module': 'foo.bar',
}]
})
assert 'sentry.interfaces.Exception' in data
def test_log_level_as_string(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'level': 'error',
})
assert data['level'] == 40
def test_invalid_log_level(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'level': 'foobar',
})
assert data['level'] == 40
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'invalid_data'
assert data['errors'][0]['name'] == 'level'
assert data['errors'][0]['value'] == 'foobar'
def test_tags_as_string(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'tags': 'bar',
})
assert 'tags' not in data
def test_tags_out_of_bounds(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'tags': {'f' * 33: 'value', 'foo': 'v' * 201, 'bar': 'value'},
})
assert data['tags'] == [('bar', 'value')]
assert len(data['errors']) == 2
def test_tags_as_invalid_pair(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'tags': [('foo', 'bar'), ('biz', 'baz', 'boz')],
})
assert data['tags'] == [('foo', 'bar')]
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'invalid_data'
assert data['errors'][0]['name'] == 'tags'
assert data['errors'][0]['value'] == ('biz', 'baz', 'boz')
def test_extra_as_string(self):
data = self.helper.validate_data(self.project, {
'message': 'foo',
'extra': 'bar',
})
assert 'extra' not in data
def test_invalid_culprit_raises(self):
self.assertRaises(APIError, self.helper.validate_data, self.project, {
'culprit': 1
})
def test_release_too_long(self):
data = self.helper.validate_data(self.project, {
'release': 'a' * 65,
})
assert not data.get('release')
assert len(data['errors']) == 1
assert data['errors'][0]['type'] == 'value_too_long'
assert data['errors'][0]['name'] == 'release'
assert data['errors'][0]['value'] == 'a' * 65
def test_release_as_non_string(self):
data = self.helper.validate_data(self.project, {
'release': 42,
})
assert data.get('release') == '42'
class GetInterfaceTest(TestCase):
def test_does_not_let_through_disallowed_name(self):
with self.assertRaises(ValueError):
get_interface('subprocess')
def test_allows_http(self):
from sentry.interfaces.http import Http
result = get_interface('sentry.interfaces.Http')
assert result is Http
result = get_interface('request')
assert result is Http
class EnsureHasIpTest(BaseAPITest):
def test_with_remote_addr(self):
inp = {
'sentry.interfaces.Http': {
'env': {
'REMOTE_ADDR': '192.168.0.1',
},
},
}
out = inp.copy()
self.helper.ensure_has_ip(out, '127.0.0.1')
assert inp == out
def test_with_user_ip(self):
inp = {
'sentry.interfaces.User': {
'ip_address': '192.168.0.1',
},
}
out = inp.copy()
self.helper.ensure_has_ip(out, '127.0.0.1')
assert inp == out
def test_without_ip_values(self):
out = {
'sentry.interfaces.User': {
},
'sentry.interfaces.Http': {
'env': {},
},
}
self.helper.ensure_has_ip(out, '127.0.0.1')
assert out['sentry.interfaces.User']['ip_address'] == '127.0.0.1'
def test_without_any_values(self):
out = {}
self.helper.ensure_has_ip(out, '127.0.0.1')
assert out['sentry.interfaces.User']['ip_address'] == '127.0.0.1'
class CspApiHelperTest(BaseAPITest):
helper_cls = CspApiHelper
def test_validate_basic(self):
report = {
"document-uri": "http://45.55.25.245:8123/csp",
"referrer": "http://example.com",
"violated-directive": "child-src https://45.55.25.245:8123/",
"effective-directive": "frame-src",
"original-policy": "default-src https://45.55.25.245:8123/; child-src https://45.55.25.245:8123/; connect-src https://45.55.25.245:8123/; font-src https://45.55.25.245:8123/; img-src https://45.55.25.245:8123/; media-src https://45.55.25.245:8123/; object-src https://45.55.25.245:8123/; script-src https://45.55.25.245:8123/; style-src https://45.55.25.245:8123/; form-action https://45.55.25.245:8123/; frame-ancestors 'none'; plugin-types 'none'; report-uri http://45.55.25.245:8123/csp-report?os=OS%20X&device=&browser_version=43.0&browser=chrome&os_version=Lion",
"blocked-uri": "http://google.com",
"status-code": 200
}
result = self.helper.validate_data(self.project, report)
assert result['project'] == self.project.id
assert 'message' in result
assert 'culprit' in result
assert result['sentry.interfaces.User'] == {'ip_address': '69.69.69.69'}
assert result['sentry.interfaces.Http'] == {
'url': 'http://45.55.25.245:8123/csp',
'headers': {
'User-Agent': 'Awesome Browser',
'Referer': 'http://example.com'
}
}
|
BayanGroup/sentry
|
tests/sentry/coreapi/tests.py
|
Python
|
bsd-3-clause
| 13,511 |
package synergynetframework.appsystem.services.net.filestore;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import synergynetframework.appsystem.services.ServiceManager;
import synergynetframework.appsystem.services.SynergyNetService;
import synergynetframework.appsystem.services.exceptions.CouldNotStartServiceException;
import synergynetframework.appsystem.services.exceptions.ServiceNotRunningException;
import synergynetframework.appsystem.services.net.filestore.messages.EndFileTransfer;
import synergynetframework.appsystem.services.net.filestore.messages.FilePart;
import synergynetframework.appsystem.services.net.filestore.messages.FileTransferComplete;
import synergynetframework.appsystem.services.net.filestore.messages.StartFileTransfer;
import synergynetframework.appsystem.services.net.landiscovery.ServiceDescriptor;
import synergynetframework.appsystem.services.net.landiscovery.ServiceDiscoverySystem;
import synergynetframework.appsystem.services.net.netservicediscovery.NetworkServiceDiscoveryService;
import synergynetframework.appsystem.services.net.peer.ServerStatusMonitor;
import synergynetframework.utils.crypto.CryptoUtils;
/**
* The Class FileStoreClient.
*/
public class FileStoreClient extends SynergyNetService implements Runnable {
/** The Constant log. */
private static final Logger log = Logger.getLogger(FileStoreClient.class
.getName());
/** The address. */
private InetAddress address;
/** The socket. */
private Socket socket;
/**
* Instantiates a new file store client.
*/
public FileStoreClient() {
}
/*
* (non-Javadoc)
* @see
* synergynetframework.appsystem.services.SynergyNetService#hasStarted()
*/
@Override
public boolean hasStarted() {
return false;
}
/*
* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
}
/**
* Send file.
*
* @param file
* the file
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public String sendFile(File file) throws IOException {
socket = new Socket(address, FileStoreServer.TCP_PORT);
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
try {
StartFileTransfer sft = new StartFileTransfer();
sft.setFileName(file.getName());
String md5 = CryptoUtils.md5(file);
sft.setMD5(md5);
oos.writeObject(sft);
byte[] buf = new byte[8 * 1024];
FileInputStream fis = new FileInputStream(file);
int read;
while ((read = fis.read(buf)) != -1) {
FilePart fp = new FilePart();
fp.setBytes(buf, read);
oos.writeObject(fp);
}
oos.writeObject(new EndFileTransfer());
try {
FileTransferComplete ftc = (FileTransferComplete) ois
.readObject();
if (ftc != null) {
log.info("File transfer completed.");
}
socket.close();
log.info("Disconnected from file store server");
} catch (ClassNotFoundException e) {
log.warning(e.toString());
}
fis.close();
return md5;
} catch (NoSuchAlgorithmException e) {
log.warning(e.toString());
}
return null;
}
/*
* (non-Javadoc)
* @see synergynetframework.appsystem.services.SynergyNetService#shutdown()
*/
@Override
public void shutdown() {
}
/*
* (non-Javadoc)
* @see synergynetframework.appsystem.services.SynergyNetService#start()
*/
public void start() throws CouldNotStartServiceException {
NetworkServiceDiscoveryService nsds = (NetworkServiceDiscoveryService) ServiceManager
.getInstance().get(NetworkServiceDiscoveryService.class);
ServiceDiscoverySystem serviceDiscovery = nsds.getServiceDiscovery();
ServerStatusMonitor smon = new ServerStatusMonitor(
FileStoreServer.SERVICE_TYPE, FileStoreServer.SERVICE_NAME,
3000);
serviceDiscovery.registerListener(smon);
serviceDiscovery.registerServiceForListening(
FileStoreServer.SERVICE_TYPE, FileStoreServer.SERVICE_NAME);
try {
smon.connect();
boolean serverFound = smon.serverFound();
if (!serverFound) {
log.severe("Could not find file store server!");
} else {
ServiceDescriptor found = smon.getServerServiceDescriptor();
address = found.getServiceAddress();
Thread t = new Thread(this);
t.start();
log.info("Ready.");
}
} catch (InterruptedException e) {
log.warning(e.toString());
}
}
/*
* (non-Javadoc)
* @see synergynetframework.appsystem.services.SynergyNetService#stop()
*/
@Override
public void stop() throws ServiceNotRunningException {
}
/*
* (non-Javadoc)
* @see synergynetframework.appsystem.services.SynergyNetService#update()
*/
@Override
public void update() {
}
}
|
synergynet/synergynet2.5
|
synergynet2.5/src/main/java/synergynetframework/appsystem/services/net/filestore/FileStoreClient.java
|
Java
|
bsd-3-clause
| 4,993 |
namespace Orchard.Events.Tests
{
public interface ITestEventHandler : IEventHandler
{
void OnEvent(string data);
}
}
|
DeSjoerd/Orchard.Events
|
src/Orchard.Events/Orchard.Events.Tests/ITestEventHandler.cs
|
C#
|
bsd-3-clause
| 140 |
<?php
/*
* Autor : Juan Carlos Ludeña Montesinos
* Año : Marzo 2016
* Descripción :
*
*/
namespace Sistema\Model\Service\Factory;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use Sistema\Model\Service\UbigeoService;
use Sistema\Model\Repository\UbigeoRepository;
class UbigeoFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$adapter = $serviceLocator->get('dbAdapter');
$repository = new UbigeoRepository($adapter);
return new UbigeoService($repository, $serviceLocator);
}
}
|
NextTrick/cp
|
module/Sistema/src/Sistema/Model/Service/Factory/UbigeoFactory.php
|
PHP
|
bsd-3-clause
| 646 |
/* rescoff.c -- read and write resources in Windows COFF files.
Copyright 1997, 1998, 1999, 2000, 2003
Free Software Foundation, Inc.
Written by Ian Lance Taylor, Cygnus Support.
This file is part of GNU Binutils.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
/* This file contains function that read and write Windows resources
in COFF files. */
#include "bfd.h"
#include "bucomm.h"
#include "libiberty.h"
#include "windres.h"
#include <assert.h>
/* In order to use the address of a resource data entry, we need to
get the image base of the file. Right now we extract it from
internal BFD information. FIXME. */
#include "coff/internal.h"
#include "libcoff.h"
/* Information we extract from the file. */
struct coff_file_info
{
/* File name. */
const char *filename;
/* Data read from the file. */
const bfd_byte *data;
/* End of data read from file. */
const bfd_byte *data_end;
/* Address of the resource section minus the image base of the file. */
bfd_vma secaddr;
/* Non-zero if the file is big endian. */
int big_endian;
};
/* A resource directory table in a COFF file. */
struct extern_res_directory
{
/* Characteristics. */
bfd_byte characteristics[4];
/* Time stamp. */
bfd_byte time[4];
/* Major version number. */
bfd_byte major[2];
/* Minor version number. */
bfd_byte minor[2];
/* Number of named directory entries. */
bfd_byte name_count[2];
/* Number of directory entries with IDs. */
bfd_byte id_count[2];
};
/* A resource directory entry in a COFF file. */
struct extern_res_entry
{
/* Name or ID. */
bfd_byte name[4];
/* Address of resource entry or subdirectory. */
bfd_byte rva[4];
};
/* A resource data entry in a COFF file. */
struct extern_res_data
{
/* Address of resource data. This is apparently a file relative
address, rather than a section offset. */
bfd_byte rva[4];
/* Size of resource data. */
bfd_byte size[4];
/* Code page. */
bfd_byte codepage[4];
/* Reserved. */
bfd_byte reserved[4];
};
/* Macros to swap in values. */
#define getfi_16(fi, s) ((fi)->big_endian ? bfd_getb16 (s) : bfd_getl16 (s))
#define getfi_32(fi, s) ((fi)->big_endian ? bfd_getb32 (s) : bfd_getl32 (s))
/* Local functions. */
static void overrun (const struct coff_file_info *, const char *);
static struct res_directory *read_coff_res_dir
(const bfd_byte *, const struct coff_file_info *,
const struct res_id *, int);
static struct res_resource *read_coff_data_entry
(const bfd_byte *, const struct coff_file_info *, const struct res_id *);
/* Read the resources in a COFF file. */
struct res_directory *
read_coff_rsrc (const char *filename, const char *target)
{
bfd *abfd;
char **matching;
asection *sec;
bfd_size_type size;
bfd_byte *data;
struct coff_file_info finfo;
if (filename == NULL)
fatal (_("filename required for COFF input"));
abfd = bfd_openr (filename, target);
if (abfd == NULL)
bfd_fatal (filename);
if (! bfd_check_format_matches (abfd, bfd_object, &matching))
{
bfd_nonfatal (bfd_get_filename (abfd));
if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
list_matching_formats (matching);
xexit (1);
}
sec = bfd_get_section_by_name (abfd, ".rsrc");
if (sec == NULL)
{
fatal (_("%s: no resource section"), filename);
}
size = bfd_section_size (abfd, sec);
data = (bfd_byte *) res_alloc (size);
if (! bfd_get_section_contents (abfd, sec, data, 0, size))
bfd_fatal (_("can't read resource section"));
finfo.filename = filename;
finfo.data = data;
finfo.data_end = data + size;
finfo.secaddr = (bfd_get_section_vma (abfd, sec)
- pe_data (abfd)->pe_opthdr.ImageBase);
finfo.big_endian = bfd_big_endian (abfd);
bfd_close (abfd);
/* Now just read in the top level resource directory. Note that we
don't free data, since we create resource entries that point into
it. If we ever want to free up the resource information we read,
this will have to be cleaned up. */
return read_coff_res_dir (data, &finfo, (const struct res_id *) NULL, 0);
}
/* Give an error if we are out of bounds. */
static void
overrun (const struct coff_file_info *finfo, const char *msg)
{
fatal (_("%s: %s: address out of bounds"), finfo->filename, msg);
}
/* Read a resource directory. */
static struct res_directory *
read_coff_res_dir (const bfd_byte *data, const struct coff_file_info *finfo,
const struct res_id *type, int level)
{
const struct extern_res_directory *erd;
struct res_directory *rd;
int name_count, id_count, i;
struct res_entry **pp;
const struct extern_res_entry *ere;
if ((size_t) (finfo->data_end - data) < sizeof (struct extern_res_directory))
overrun (finfo, _("directory"));
erd = (const struct extern_res_directory *) data;
rd = (struct res_directory *) res_alloc (sizeof *rd);
rd->characteristics = getfi_32 (finfo, erd->characteristics);
rd->time = getfi_32 (finfo, erd->time);
rd->major = getfi_16 (finfo, erd->major);
rd->minor = getfi_16 (finfo, erd->minor);
rd->entries = NULL;
name_count = getfi_16 (finfo, erd->name_count);
id_count = getfi_16 (finfo, erd->id_count);
pp = &rd->entries;
/* The resource directory entries immediately follow the directory
table. */
ere = (const struct extern_res_entry *) (erd + 1);
for (i = 0; i < name_count; i++, ere++)
{
unsigned long name, rva;
struct res_entry *re;
const bfd_byte *ers;
int length, j;
if ((const bfd_byte *) ere >= finfo->data_end)
overrun (finfo, _("named directory entry"));
name = getfi_32 (finfo, ere->name);
rva = getfi_32 (finfo, ere->rva);
/* For some reason the high bit in NAME is set. */
name &=~ 0x80000000;
if (name > (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("directory entry name"));
ers = finfo->data + name;
re = (struct res_entry *) res_alloc (sizeof *re);
re->next = NULL;
re->id.named = 1;
length = getfi_16 (finfo, ers);
re->id.u.n.length = length;
re->id.u.n.name = (unichar *) res_alloc (length * sizeof (unichar));
for (j = 0; j < length; j++)
re->id.u.n.name[j] = getfi_16 (finfo, ers + j * 2 + 2);
if (level == 0)
type = &re->id;
if ((rva & 0x80000000) != 0)
{
rva &=~ 0x80000000;
if (rva >= (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("named subdirectory"));
re->subdir = 1;
re->u.dir = read_coff_res_dir (finfo->data + rva, finfo, type,
level + 1);
}
else
{
if (rva >= (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("named resource"));
re->subdir = 0;
re->u.res = read_coff_data_entry (finfo->data + rva, finfo, type);
}
*pp = re;
pp = &re->next;
}
for (i = 0; i < id_count; i++, ere++)
{
unsigned long name, rva;
struct res_entry *re;
if ((const bfd_byte *) ere >= finfo->data_end)
overrun (finfo, _("ID directory entry"));
name = getfi_32 (finfo, ere->name);
rva = getfi_32 (finfo, ere->rva);
re = (struct res_entry *) res_alloc (sizeof *re);
re->next = NULL;
re->id.named = 0;
re->id.u.id = name;
if (level == 0)
type = &re->id;
if ((rva & 0x80000000) != 0)
{
rva &=~ 0x80000000;
if (rva >= (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("ID subdirectory"));
re->subdir = 1;
re->u.dir = read_coff_res_dir (finfo->data + rva, finfo, type,
level + 1);
}
else
{
if (rva >= (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("ID resource"));
re->subdir = 0;
re->u.res = read_coff_data_entry (finfo->data + rva, finfo, type);
}
*pp = re;
pp = &re->next;
}
return rd;
}
/* Read a resource data entry. */
static struct res_resource *
read_coff_data_entry (const bfd_byte *data, const struct coff_file_info *finfo, const struct res_id *type)
{
const struct extern_res_data *erd;
struct res_resource *r;
unsigned long size, rva;
const bfd_byte *resdata;
if (type == NULL)
fatal (_("resource type unknown"));
if ((size_t) (finfo->data_end - data) < sizeof (struct extern_res_data))
overrun (finfo, _("data entry"));
erd = (const struct extern_res_data *) data;
size = getfi_32 (finfo, erd->size);
rva = getfi_32 (finfo, erd->rva);
if (rva < finfo->secaddr
|| rva - finfo->secaddr >= (size_t) (finfo->data_end - finfo->data))
overrun (finfo, _("resource data"));
resdata = finfo->data + (rva - finfo->secaddr);
if (size > (size_t) (finfo->data_end - resdata))
overrun (finfo, _("resource data size"));
r = bin_to_res (*type, resdata, size, finfo->big_endian);
memset (&r->res_info, 0, sizeof (struct res_res_info));
r->coff_info.codepage = getfi_32 (finfo, erd->codepage);
r->coff_info.reserved = getfi_32 (finfo, erd->reserved);
return r;
}
/* This structure is used to build a list of bindata structures. */
struct bindata_build
{
/* The data. */
struct bindata *d;
/* The last structure we have added to the list. */
struct bindata *last;
/* The size of the list as a whole. */
unsigned long length;
};
/* This structure keeps track of information as we build the directory
tree. */
struct coff_write_info
{
/* These fields are based on the BFD. */
/* The BFD itself. */
bfd *abfd;
/* Non-zero if the file is big endian. */
int big_endian;
/* Pointer to section symbol used to build RVA relocs. */
asymbol **sympp;
/* These fields are computed initially, and then not changed. */
/* Length of directory tables and entries. */
unsigned long dirsize;
/* Length of directory entry strings. */
unsigned long dirstrsize;
/* Length of resource data entries. */
unsigned long dataentsize;
/* These fields are updated as we add data. */
/* Directory tables and entries. */
struct bindata_build dirs;
/* Directory entry strings. */
struct bindata_build dirstrs;
/* Resource data entries. */
struct bindata_build dataents;
/* Actual resource data. */
struct bindata_build resources;
/* Relocations. */
arelent **relocs;
/* Number of relocations. */
unsigned int reloc_count;
};
/* Macros to swap out values. */
#define putcwi_16(cwi, v, s) \
((cwi->big_endian) ? bfd_putb16 ((v), (s)) : bfd_putl16 ((v), (s)))
#define putcwi_32(cwi, v, s) \
((cwi->big_endian) ? bfd_putb32 ((v), (s)) : bfd_putl32 ((v), (s)))
static void coff_bin_sizes
(const struct res_directory *, struct coff_write_info *);
static unsigned char *coff_alloc (struct bindata_build *, size_t);
static void coff_to_bin
(const struct res_directory *, struct coff_write_info *);
static void coff_res_to_bin
(const struct res_resource *, struct coff_write_info *);
/* Write resources to a COFF file. RESOURCES should already be
sorted.
Right now we always create a new file. Someday we should also
offer the ability to merge resources into an existing file. This
would require doing the basic work of objcopy, just modifying or
adding the .rsrc section. */
void
write_coff_file (const char *filename, const char *target,
const struct res_directory *resources)
{
bfd *abfd;
asection *sec;
struct coff_write_info cwi;
struct bindata *d;
unsigned long length, offset;
if (filename == NULL)
fatal (_("filename required for COFF output"));
abfd = bfd_openw (filename, target);
if (abfd == NULL)
bfd_fatal (filename);
if (! bfd_set_format (abfd, bfd_object))
bfd_fatal ("bfd_set_format");
#if defined DLLTOOL_SH
if (! bfd_set_arch_mach (abfd, bfd_arch_sh, 0))
bfd_fatal ("bfd_set_arch_mach(sh)");
#elif defined DLLTOOL_MIPS
if (! bfd_set_arch_mach (abfd, bfd_arch_mips, 0))
bfd_fatal ("bfd_set_arch_mach(mips)");
#elif defined DLLTOOL_ARM
if (! bfd_set_arch_mach (abfd, bfd_arch_arm, 0))
bfd_fatal ("bfd_set_arch_mach(arm)");
#else
/* FIXME: This is obviously i386 specific. */
if (! bfd_set_arch_mach (abfd, bfd_arch_i386, 0))
bfd_fatal ("bfd_set_arch_mach(i386)");
#endif
if (! bfd_set_file_flags (abfd, HAS_SYMS | HAS_RELOC))
bfd_fatal ("bfd_set_file_flags");
sec = bfd_make_section (abfd, ".rsrc");
if (sec == NULL)
bfd_fatal ("bfd_make_section");
if (! bfd_set_section_flags (abfd, sec,
(SEC_HAS_CONTENTS | SEC_ALLOC
| SEC_LOAD | SEC_DATA)))
bfd_fatal ("bfd_set_section_flags");
if (! bfd_set_symtab (abfd, sec->symbol_ptr_ptr, 1))
bfd_fatal ("bfd_set_symtab");
/* Requiring this is probably a bug in BFD. */
sec->output_section = sec;
/* The order of data in the .rsrc section is
resource directory tables and entries
resource directory strings
resource data entries
actual resource data
We build these different types of data in different lists. */
cwi.abfd = abfd;
cwi.big_endian = bfd_big_endian (abfd);
cwi.sympp = sec->symbol_ptr_ptr;
cwi.dirsize = 0;
cwi.dirstrsize = 0;
cwi.dataentsize = 0;
cwi.dirs.d = NULL;
cwi.dirs.last = NULL;
cwi.dirs.length = 0;
cwi.dirstrs.d = NULL;
cwi.dirstrs.last = NULL;
cwi.dirstrs.length = 0;
cwi.dataents.d = NULL;
cwi.dataents.last = NULL;
cwi.dataents.length = 0;
cwi.resources.d = NULL;
cwi.resources.last = NULL;
cwi.resources.length = 0;
cwi.relocs = NULL;
cwi.reloc_count = 0;
/* Work out the sizes of the resource directory entries, so that we
know the various offsets we will need. */
coff_bin_sizes (resources, &cwi);
/* Force the directory strings to be 32 bit aligned. Every other
structure is 32 bit aligned anyhow. */
cwi.dirstrsize = (cwi.dirstrsize + 3) &~ 3;
/* Actually convert the resources to binary. */
coff_to_bin (resources, &cwi);
/* Add another 2 bytes to the directory strings if needed for
alignment. */
if ((cwi.dirstrs.length & 3) != 0)
{
unsigned char *ex;
ex = coff_alloc (&cwi.dirstrs, 2);
ex[0] = 0;
ex[1] = 0;
}
/* Make sure that the data we built came out to the same size as we
calculated initially. */
assert (cwi.dirs.length == cwi.dirsize);
assert (cwi.dirstrs.length == cwi.dirstrsize);
assert (cwi.dataents.length == cwi.dataentsize);
length = (cwi.dirsize
+ cwi.dirstrsize
+ cwi.dataentsize
+ cwi.resources.length);
if (! bfd_set_section_size (abfd, sec, length))
bfd_fatal ("bfd_set_section_size");
bfd_set_reloc (abfd, sec, cwi.relocs, cwi.reloc_count);
offset = 0;
for (d = cwi.dirs.d; d != NULL; d = d->next)
{
if (! bfd_set_section_contents (abfd, sec, d->data, offset, d->length))
bfd_fatal ("bfd_set_section_contents");
offset += d->length;
}
for (d = cwi.dirstrs.d; d != NULL; d = d->next)
{
if (! bfd_set_section_contents (abfd, sec, d->data, offset, d->length))
bfd_fatal ("bfd_set_section_contents");
offset += d->length;
}
for (d = cwi.dataents.d; d != NULL; d = d->next)
{
if (! bfd_set_section_contents (abfd, sec, d->data, offset, d->length))
bfd_fatal ("bfd_set_section_contents");
offset += d->length;
}
for (d = cwi.resources.d; d != NULL; d = d->next)
{
if (! bfd_set_section_contents (abfd, sec, d->data, offset, d->length))
bfd_fatal ("bfd_set_section_contents");
offset += d->length;
}
assert (offset == length);
if (! bfd_close (abfd))
bfd_fatal ("bfd_close");
/* We allocated the relocs array using malloc. */
free (cwi.relocs);
}
/* Work out the sizes of the various fixed size resource directory
entries. This updates fields in CWI. */
static void
coff_bin_sizes (const struct res_directory *resdir,
struct coff_write_info *cwi)
{
const struct res_entry *re;
cwi->dirsize += sizeof (struct extern_res_directory);
for (re = resdir->entries; re != NULL; re = re->next)
{
cwi->dirsize += sizeof (struct extern_res_entry);
if (re->id.named)
cwi->dirstrsize += re->id.u.n.length * 2 + 2;
if (re->subdir)
coff_bin_sizes (re->u.dir, cwi);
else
cwi->dataentsize += sizeof (struct extern_res_data);
}
}
/* Allocate data for a particular list. */
static unsigned char *
coff_alloc (struct bindata_build *bb, size_t size)
{
struct bindata *d;
d = (struct bindata *) reswr_alloc (sizeof *d);
d->next = NULL;
d->data = (unsigned char *) reswr_alloc (size);
d->length = size;
if (bb->d == NULL)
bb->d = d;
else
bb->last->next = d;
bb->last = d;
bb->length += size;
return d->data;
}
/* Convert the resource directory RESDIR to binary. */
static void
coff_to_bin (const struct res_directory *resdir, struct coff_write_info *cwi)
{
struct extern_res_directory *erd;
int ci, cn;
const struct res_entry *e;
struct extern_res_entry *ere;
/* Write out the directory table. */
erd = ((struct extern_res_directory *)
coff_alloc (&cwi->dirs, sizeof (*erd)));
putcwi_32 (cwi, resdir->characteristics, erd->characteristics);
putcwi_32 (cwi, resdir->time, erd->time);
putcwi_16 (cwi, resdir->major, erd->major);
putcwi_16 (cwi, resdir->minor, erd->minor);
ci = 0;
cn = 0;
for (e = resdir->entries; e != NULL; e = e->next)
{
if (e->id.named)
++cn;
else
++ci;
}
putcwi_16 (cwi, cn, erd->name_count);
putcwi_16 (cwi, ci, erd->id_count);
/* Write out the data entries. Note that we allocate space for all
the entries before writing them out. That permits a recursive
call to work correctly when writing out subdirectories. */
ere = ((struct extern_res_entry *)
coff_alloc (&cwi->dirs, (ci + cn) * sizeof (*ere)));
for (e = resdir->entries; e != NULL; e = e->next, ere++)
{
if (! e->id.named)
putcwi_32 (cwi, e->id.u.id, ere->name);
else
{
unsigned char *str;
int i;
/* For some reason existing files seem to have the high bit
set on the address of the name, although that is not
documented. */
putcwi_32 (cwi,
0x80000000 | (cwi->dirsize + cwi->dirstrs.length),
ere->name);
str = coff_alloc (&cwi->dirstrs, e->id.u.n.length * 2 + 2);
putcwi_16 (cwi, e->id.u.n.length, str);
for (i = 0; i < e->id.u.n.length; i++)
putcwi_16 (cwi, e->id.u.n.name[i], str + i * 2 + 2);
}
if (e->subdir)
{
putcwi_32 (cwi, 0x80000000 | cwi->dirs.length, ere->rva);
coff_to_bin (e->u.dir, cwi);
}
else
{
putcwi_32 (cwi,
cwi->dirsize + cwi->dirstrsize + cwi->dataents.length,
ere->rva);
coff_res_to_bin (e->u.res, cwi);
}
}
}
/* Convert the resource RES to binary. */
static void
coff_res_to_bin (const struct res_resource *res, struct coff_write_info *cwi)
{
arelent *r;
struct extern_res_data *erd;
struct bindata *d;
unsigned long length;
/* For some reason, although every other address is a section
offset, the address of the resource data itself is an RVA. That
means that we need to generate a relocation for it. We allocate
the relocs array using malloc so that we can use realloc. FIXME:
This relocation handling is correct for the i386, but probably
not for any other target. */
r = (arelent *) reswr_alloc (sizeof (arelent));
r->sym_ptr_ptr = cwi->sympp;
r->address = cwi->dirsize + cwi->dirstrsize + cwi->dataents.length;
r->addend = 0;
r->howto = bfd_reloc_type_lookup (cwi->abfd, BFD_RELOC_RVA);
if (r->howto == NULL)
bfd_fatal (_("can't get BFD_RELOC_RVA relocation type"));
cwi->relocs = xrealloc (cwi->relocs,
(cwi->reloc_count + 2) * sizeof (arelent *));
cwi->relocs[cwi->reloc_count] = r;
cwi->relocs[cwi->reloc_count + 1] = NULL;
++cwi->reloc_count;
erd = (struct extern_res_data *) coff_alloc (&cwi->dataents, sizeof (*erd));
putcwi_32 (cwi,
(cwi->dirsize
+ cwi->dirstrsize
+ cwi->dataentsize
+ cwi->resources.length),
erd->rva);
putcwi_32 (cwi, res->coff_info.codepage, erd->codepage);
putcwi_32 (cwi, res->coff_info.reserved, erd->reserved);
d = res_to_bin (res, cwi->big_endian);
if (cwi->resources.d == NULL)
cwi->resources.d = d;
else
cwi->resources.last->next = d;
length = 0;
for (; d->next != NULL; d = d->next)
length += d->length;
length += d->length;
cwi->resources.last = d;
cwi->resources.length += length;
putcwi_32 (cwi, length, erd->size);
/* Force the next resource to have 32 bit alignment. */
if ((length & 3) != 0)
{
int add;
unsigned char *ex;
add = 4 - (length & 3);
ex = coff_alloc (&cwi->resources, add);
memset (ex, 0, add);
}
}
|
shaotuanchen/sunflower_exp
|
tools/source/binutils-2.16.1/binutils/rescoff.c
|
C
|
bsd-3-clause
| 21,366 |
import html4Symbols
def diff(a, b):
b = set(b)
return [aa for aa in a if aa not in b]
REMOVED_SYMBOLS = ['acronym','applet','basefont','big','center','dir','font','frame','frameset','noframes','strike','tt']
NEW_ELEMENTS = [
'canvas',
'audio' ,
'video',
'source',
'embed',
'track',
'datalist', #Specifies a list of pre-defined options for input controls
'keygen', #Defines a key-pair generator field (for forms)
'output', #Defines the result of a calculation
'article', #Defines an article
'aside',#Defines content aside from the page content
'bdi',#Isolates a part of text that might be formatted in a different direction from other text outside it
'command',#Defines a command button that a user can invoke
'details',#Defines additional details that the user can view or hide
'dialog',#Defines a dialog box or window
'summary',#Defines a visible heading for a 'details' element
'figure',#Specifies self-contained content, like illustrations, diagrams, photos, code listings, etc.
'figcaption',#Defines a caption for a 'figure' element
'footer',#Defines a footer for a document or section
'header',#Defines a header for a document or section
'mark',#Defines marked/highlighted text
'meter',#Defines a scalar measurement within a known range (a gauge)
'nav',#Defines navigation links
'progress',#Represents the progress of a task
'ruby',#Defines a ruby annotation (for East Asian typography)
'rt',#Defines an explanation/pronunciation of characters (for East Asian typography)
'rp',#Defines what to show in browsers that do not support ruby annotations
'section',#Defines a section in a document
'time',#Defines a date/time
'wbr'#Defines a possible line-break
]
CLOSING_TAGS = diff(html4Symbols.CLOSING_TAGS,REMOVED_SYMBOLS) + NEW_ELEMENTS
LINE_BREAK_AFTER = diff(html4Symbols.LINE_BREAK_AFTER,REMOVED_SYMBOLS) + NEW_ELEMENTS
NON_CLOSING_TAGS = diff(html4Symbols.NON_CLOSING_TAGS,REMOVED_SYMBOLS)
ONE_LINE = diff(html4Symbols.ONE_LINE,REMOVED_SYMBOLS)
|
bossiernesto/python-snipplets
|
htmlgenerator/html5Symbols.py
|
Python
|
bsd-3-clause
| 1,966 |
/*
* Copyright (c) 2018, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <limits.h>
#include <algorithm>
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/helpers.h"
#include "utils/logger.h"
#include "utils/macro.h"
#ifdef ENABLE_SECURITY
#include "security_manager/security_manager.h"
#include "security_manager/ssl_context.h"
#endif // ENABLE_SECURITY
/**
* \namespace connection_handler
* \brief SmartDeviceLink ConnectionHandler namespace.
*/
namespace connection_handler {
SDL_CREATE_LOG_VARIABLE("ConnectionHandler")
Service* Session::FindService(
const protocol_handler::ServiceType& service_type) {
ServiceList::iterator service_it =
std::find(service_list.begin(), service_list.end(), service_type);
if (service_it != service_list.end()) {
return &(*service_it);
}
return NULL;
}
const Service* Session::FindService(
const protocol_handler::ServiceType& service_type) const {
ServiceList::const_iterator service_it =
std::find(service_list.begin(), service_list.end(), service_type);
if (service_it != service_list.end()) {
return &(*service_it);
}
return NULL;
}
Connection::Connection(ConnectionHandle connection_handle,
DeviceHandle connection_device_handle,
ConnectionHandler* connection_handler,
uint32_t heartbeat_timeout)
: connection_handler_(connection_handler)
, connection_handle_(connection_handle)
, connection_device_handle_(connection_device_handle)
, primary_connection_handle_(0)
, heartbeat_timeout_(heartbeat_timeout)
, final_message_sent_(false) {
SDL_LOG_AUTO_TRACE();
DCHECK(connection_handler_);
heartbeat_monitor_ = new HeartBeatMonitor(heartbeat_timeout_, this);
heart_beat_monitor_thread_ =
threads::CreateThread("HeartBeatMonitor", heartbeat_monitor_);
heart_beat_monitor_thread_->Start();
}
Connection::~Connection() {
SDL_LOG_AUTO_TRACE();
heart_beat_monitor_thread_->Stop(threads::Thread::kThreadSoftStop);
delete heartbeat_monitor_;
threads::DeleteThread(heart_beat_monitor_thread_);
// Before clearing out the session_map_, we must remove all sessions
// associated with this Connection from the SessionConnectionMap.
// NESTED LOCK: make sure to lock session_map_lock_ then ConnectionHandler's
// session_connection_map_lock_ptr_ (which will be taken in RemoveSession).
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.begin();
while (session_it != session_map_.end()) {
SDL_LOG_INFO("Removed Session ID "
<< static_cast<int>(session_it->first)
<< " from Session/Connection Map in Connection Destructor");
connection_handler_->RemoveSession(session_it->first);
++session_it;
}
session_map_.clear();
}
uint32_t Connection::AddNewSession(
const transport_manager::ConnectionUID connection_handle) {
SDL_LOG_AUTO_TRACE();
// NESTED LOCK: make sure to lock session_map_lock_ then ConnectionHandler's
// session_connection_map_lock_ptr_ (which will be taken in AddSession)
sync_primitives::AutoLock lock(session_map_lock_);
// Even though we have our own SessionMap, we use the Connection Handler's
// SessionConnectionMap to generate a session ID. We want to make sure that
// session IDs are globally unique, and not only unique within a Connection.
const uint32_t session_id =
connection_handler_->AddSession(connection_handle);
if (session_id > 0) {
Session& new_session = session_map_[session_id];
new_session.protocol_version = ::protocol_handler::PROTOCOL_VERSION_2;
new_session.service_list.push_back(
Service(protocol_handler::kRpc, connection_handle));
new_session.service_list.push_back(
Service(protocol_handler::kBulk, connection_handle));
}
return session_id;
}
uint32_t Connection::RemoveSession(uint8_t session_id) {
SDL_LOG_AUTO_TRACE();
// Again, a NESTED lock, but it follows the rules.
sync_primitives::AutoLock lock(session_map_lock_);
if (!connection_handler_->RemoveSession(session_id)) {
return 0;
}
SessionMap::iterator it = session_map_.find(session_id);
if (session_map_.end() == it) {
SDL_LOG_WARN("Session not found in this connection!");
return 0;
}
heartbeat_monitor_->RemoveSession(session_id);
session_map_.erase(session_id);
return session_id;
}
void Connection::OnFinalMessageCallback() {
SDL_LOG_AUTO_TRACE();
final_message_sent_ = true;
}
bool Connection::IsFinalMessageSent() const {
return final_message_sent_;
}
bool Connection::AddNewService(uint8_t session_id,
protocol_handler::ServiceType service_type,
const bool request_protection,
transport_manager::ConnectionUID connection_id,
std::string* err_reason) {
// Ignore wrong services
if (protocol_handler::kControl == service_type ||
protocol_handler::kInvalidServiceType == service_type) {
SDL_LOG_WARN("Wrong service " << static_cast<int>(service_type));
if (err_reason) {
*err_reason = "Wrong service type " + std::to_string(service_type);
}
return false;
}
SDL_LOG_DEBUG("Add service " << service_type << " for session "
<< static_cast<uint32_t>(session_id)
<< " using connection ID "
<< static_cast<uint32_t>(connection_id));
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
SDL_LOG_WARN("Session not found in this connection!");
if (err_reason) {
*err_reason = "Session " + std::to_string(session_id) +
" not found for connection " +
std::to_string(connection_id);
}
return false;
}
Session& session = session_it->second;
if (session.protocol_version <= protocol_handler::PROTOCOL_VERSION_2 &&
helpers::
Compare<protocol_handler::ServiceType, helpers::EQ, helpers::ONE>(
service_type,
protocol_handler::ServiceType::kAudio,
protocol_handler::ServiceType::kMobileNav)) {
SDL_LOG_WARN(
"Audio and video services are disallowed for protocol version "
"2 or lower");
return false;
}
Service* service = session.FindService(service_type);
// if service already exists
if (service) {
#ifdef ENABLE_SECURITY
if (!request_protection) {
SDL_LOG_WARN("Session " << static_cast<int>(session_id)
<< " already has unprotected service "
<< static_cast<int>(service_type));
if (err_reason) {
*err_reason = "Session " + std::to_string(session_id) +
" already has an unprotected service of type " +
std::to_string(service_type);
}
return false;
}
if (service->is_protected_) {
SDL_LOG_WARN("Session " << static_cast<int>(session_id)
<< " already has protected service "
<< static_cast<int>(service_type));
if (err_reason) {
*err_reason = "Session " + std::to_string(session_id) +
" already has a protected service of type " +
std::to_string(service_type);
}
return false;
}
// For unproteced service could be start protection
return true;
#else
// Service already exists
return false;
#endif // ENABLE_SECURITY
}
// id service is not exists
session.service_list.push_back(Service(service_type, connection_id));
return true;
}
inline bool is_incorrect_for_remove_service(
const protocol_handler::ServiceType service_type) {
return
// Control type is internal part of session
protocol_handler::kControl == service_type ||
// RPC and bulk service is necessary part of session
protocol_handler::kRpc == service_type ||
protocol_handler::kBulk == service_type ||
// Invalid service is not part of session
protocol_handler::kInvalidServiceType == service_type;
}
bool Connection::RemoveService(uint8_t session_id,
protocol_handler::ServiceType service_type) {
// Ignore wrong and required for Session services
if (is_incorrect_for_remove_service(service_type)) {
SDL_LOG_WARN("Could not remove service " << static_cast<int>(service_type));
return false;
}
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return false;
}
ServiceList& service_list = session_it->second.service_list;
ServiceList::iterator service_it =
find(service_list.begin(), service_list.end(), service_type);
if (service_list.end() == service_it) {
SDL_LOG_WARN("Session " << session_id
<< " didn't established"
" service "
<< service_type);
return false;
}
service_list.erase(service_it);
return true;
}
uint8_t Connection::RemoveSecondaryServices(
transport_manager::ConnectionUID secondary_connection_handle,
std::list<protocol_handler::ServiceType>& removed_services_list) {
SDL_LOG_AUTO_TRACE();
uint8_t found_session_id = 0;
sync_primitives::AutoLock lock(session_map_lock_);
SDL_LOG_INFO("RemoveSecondaryServices looking for services on Connection ID "
<< static_cast<int>(secondary_connection_handle));
// Walk the SessionMap in the primary connection, and for each
// Session, we walk its ServiceList, looking for all the services
// that were running on the now-closed Secondary Connection.
for (SessionMap::iterator session_it = session_map_.begin();
session_map_.end() != session_it;
++session_it) {
SDL_LOG_INFO("RemoveSecondaryServices found session ID "
<< static_cast<int>(session_it->first));
// Now, for each session, walk the its ServiceList, looking for services
// that were using secondary)_connection_handle. If we find such a service,
// set session_found and break out of the outer loop.
ServiceList& service_list = session_it->second.service_list;
ServiceList::iterator service_it = service_list.begin();
for (; service_it != service_list.end();) {
SDL_LOG_INFO("RemoveSecondaryServices found service ID "
<< static_cast<int>(service_it->service_type));
if (service_it->connection_id == secondary_connection_handle) {
found_session_id = session_it->first;
SDL_LOG_INFO("RemoveSecondaryServices removing Service "
<< static_cast<int>(service_it->service_type)
<< " in session " << static_cast<int>(found_session_id));
removed_services_list.push_back(service_it->service_type);
service_it = service_list.erase(service_it);
} else {
++service_it;
}
}
// If we found a session that had services running on the secondary
// connection, we're done.
if (found_session_id != 0) {
break;
}
}
return found_session_id;
}
#ifdef ENABLE_SECURITY
int Connection::SetSSLContext(uint8_t session_id,
security_manager::SSLContext* context) {
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
SDL_LOG_WARN("Session not found in this connection!");
return security_manager::SecurityManager::ERROR_INTERNAL;
}
Session& session = session_it->second;
session.ssl_context = context;
return security_manager::SecurityManager::ERROR_SUCCESS;
}
security_manager::SSLContext* Connection::GetSSLContext(
const uint8_t session_id,
const protocol_handler::ServiceType& service_type) const {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::const_iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
SDL_LOG_WARN("Session not found in this connection!");
return NULL;
}
const Session& session = session_it->second;
// for control services return current SSLContext value
if (protocol_handler::kControl == service_type)
return session.ssl_context;
const Service* service = session.FindService(service_type);
if (!service) {
SDL_LOG_WARN("Service not found in this session!");
return NULL;
}
if (!service->is_protected_)
return NULL;
SDL_LOG_TRACE("SSLContext is " << session.ssl_context);
return session.ssl_context;
}
void Connection::SetProtectionFlag(
const uint8_t session_id,
const protocol_handler::ServiceType& service_type) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
SDL_LOG_WARN("Session not found in this connection!");
return;
}
Session& session = session_it->second;
Service* service = session.FindService(service_type);
if (!service) {
SDL_LOG_WARN("Service not found in this session!");
return;
}
service->is_protected_ = true;
// Rpc and bulk shall be protected as one service
if (service->service_type == protocol_handler::kRpc) {
Service* service_bulk = session.FindService(protocol_handler::kBulk);
DCHECK(service_bulk);
service_bulk->is_protected_ = true;
} else if (service->service_type == protocol_handler::kBulk) {
Service* service_rpc = session.FindService(protocol_handler::kRpc);
DCHECK(service_rpc);
service_rpc->is_protected_ = true;
}
}
#endif // ENABLE_SECURITY
bool Connection::SessionServiceExists(
const uint8_t session_id,
const protocol_handler::ServiceType& service_type) const {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::const_iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
SDL_LOG_WARN("Session not found in this connection!");
return false;
}
const Session& session = session_it->second;
return session.FindService(service_type);
}
ConnectionHandle Connection::connection_handle() const {
return connection_handle_;
}
DeviceHandle Connection::connection_device_handle() const {
return connection_device_handle_;
}
const SessionMap Connection::session_map() const {
sync_primitives::AutoLock lock(session_map_lock_);
return session_map_;
}
void Connection::CloseSession(uint8_t session_id) {
{
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
return;
}
}
connection_handler_->CloseSession(
connection_handle_, session_id, connection_handler::kCommon);
}
void Connection::UpdateProtocolVersionSession(uint8_t session_id,
uint8_t protocol_version) {
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return;
}
Session& session = session_it->second;
session.protocol_version = protocol_version;
if (session.full_protocol_version.major_version_ !=
session.protocol_version) {
session.full_protocol_version =
utils::SemanticVersion(protocol_version, 0, 0);
}
}
void Connection::UpdateProtocolVersionSession(
uint8_t session_id, const utils::SemanticVersion& full_protocol_version) {
SDL_LOG_AUTO_TRACE();
if (!full_protocol_version.isValid()) {
SDL_LOG_WARN("Invalid version: " << full_protocol_version.toString());
return;
}
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return;
}
Session& session = session_it->second;
session.protocol_version =
static_cast<uint8_t>(full_protocol_version.major_version_);
session.full_protocol_version = full_protocol_version;
}
bool Connection::SupportHeartBeat(uint8_t session_id) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return false;
}
Session& session = session_it->second;
return (
(session.protocol_version >= ::protocol_handler::PROTOCOL_VERSION_3) &&
(0 != heartbeat_timeout_));
}
bool Connection::ProtocolVersion(uint8_t session_id,
uint8_t& protocol_version) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return false;
}
protocol_version = (session_it->second).protocol_version;
return true;
}
bool Connection::IsSessionHeartbeatTracked(const uint8_t session_id) const {
return heartbeat_monitor_->IsSessionHeartbeatTracked(session_id);
}
bool Connection::ProtocolVersion(
uint8_t session_id, utils::SemanticVersion& full_protocol_version) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
SDL_LOG_WARN("Session not found in this connection!");
return false;
}
full_protocol_version = (session_it->second).full_protocol_version;
return true;
}
ConnectionHandle Connection::primary_connection_handle() const {
return primary_connection_handle_;
}
void Connection::SetPrimaryConnectionHandle(
ConnectionHandle primary_connection_handle) {
primary_connection_handle_ = primary_connection_handle;
}
void Connection::StartHeartBeat(uint8_t session_id) {
heartbeat_monitor_->AddSession(session_id);
}
void Connection::SendHeartBeat(uint8_t session_id) {
connection_handler_->SendHeartBeat(connection_handle_, session_id);
}
void Connection::KeepAlive(uint8_t session_id) {
heartbeat_monitor_->KeepAlive(session_id);
}
void Connection::SetHeartBeatTimeout(uint32_t timeout, uint8_t session_id) {
heartbeat_monitor_->set_heartbeat_timeout_milliseconds(timeout, session_id);
}
} // namespace connection_handler
|
smartdevicelink/sdl_core
|
src/components/connection_handler/src/connection.cc
|
C++
|
bsd-3-clause
| 20,483 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.