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
|
---|---|---|---|---|---|
from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def fill_v0_vx(context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256
context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y]
context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
}
|
martindimondo/PyC8
|
chip8/operations.py
|
Python
|
bsd-3-clause
| 6,673 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.vector_ar.svar_model.SVARResults.irf — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.irf_errband_mc" href="statsmodels.tsa.vector_ar.svar_model.SVARResults.irf_errband_mc.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.intercept_longrun" href="statsmodels.tsa.vector_ar.svar_model.SVARResults.intercept_longrun.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.irf" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.13.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.vector_ar.svar_model.SVARResults.irf </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../vector_ar.html" class="md-tabs__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.html" class="md-tabs__link">statsmodels.tsa.vector_ar.svar_model.SVARResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.13.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.irf.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-vector-ar-svar-model-svarresults-irf--page-root">statsmodels.tsa.vector_ar.svar_model.SVARResults.irf<a class="headerlink" href="#generated-statsmodels-tsa-vector-ar-svar-model-svarresults-irf--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.tsa.vector_ar.svar_model.SVARResults.irf">
<span class="sig-prename descclassname"><span class="pre">SVARResults.</span></span><span class="sig-name descname"><span class="pre">irf</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">periods</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">10</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">var_order</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/svar_model.html#SVARResults.irf"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.svar_model.SVARResults.irf" title="Permalink to this definition">¶</a></dt>
<dd><p>Analyze structural impulse responses to shocks in system</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>periods</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">int</span></code></a></span></dt><dd></dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl>
<dt><strong>irf</strong><span class="classifier"><code class="xref py py-obj docutils literal notranslate"><span class="pre">IRAnalysis</span></code></span></dt><dd></dd>
</dl>
</dd>
</dl>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.intercept_longrun.html" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.intercept_longrun"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.vector_ar.svar_model.SVARResults.intercept_longrun </span>
</div>
</a>
<a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.irf_errband_mc.html" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.irf_errband_mc"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.vector_ar.svar_model.SVARResults.irf_errband_mc </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 06, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.0.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.13.0/generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.irf.html
|
HTML
|
bsd-3-clause
| 18,885 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.tsa.vector_ar.var_model.VARProcess.acorr — 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.tsa.vector_ar.var_model.VARProcess.forecast" href="statsmodels.tsa.vector_ar.var_model.VARProcess.forecast.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARProcess.acf" href="statsmodels.tsa.vector_ar.var_model.VARProcess.acf.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.tsa.vector_ar.var_model.VARProcess.forecast.html" title="statsmodels.tsa.vector_ar.var_model.VARProcess.forecast"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.tsa.vector_ar.var_model.VARProcess.acf.html" title="statsmodels.tsa.vector_ar.var_model.VARProcess.acf"
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="../vector_ar.html" >Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.tsa.vector_ar.var_model.VARProcess.html" accesskey="U">statsmodels.tsa.vector_ar.var_model.VARProcess</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-tsa-vector-ar-var-model-varprocess-acorr">
<h1>statsmodels.tsa.vector_ar.var_model.VARProcess.acorr<a class="headerlink" href="#statsmodels-tsa-vector-ar-var-model-varprocess-acorr" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.tsa.vector_ar.var_model.VARProcess.acorr">
<code class="sig-prename descclassname">VARProcess.</code><code class="sig-name descname">acorr</code><span class="sig-paren">(</span><em class="sig-param">nlags=None</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.acorr"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.var_model.VARProcess.acorr" title="Permalink to this definition">¶</a></dt>
<dd><p>Compute theoretical autocorrelation function</p>
<dl class="field-list simple">
<dt class="field-odd">Returns</dt>
<dd class="field-odd"><dl class="simple">
<dt><strong>acorr</strong><span class="classifier">ndarray (p x k x k)</span></dt><dd></dd>
</dl>
</dd>
</dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARProcess.acf.html"
title="previous chapter">statsmodels.tsa.vector_ar.var_model.VARProcess.acf</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARProcess.forecast.html"
title="next chapter">statsmodels.tsa.vector_ar.var_model.VARProcess.forecast</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARProcess.acorr.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.tsa.vector_ar.var_model.VARProcess.acorr.html
|
HTML
|
bsd-3-clause
| 7,934 |
/*
* Created on Oct 18, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.tolweb.tapestry;
import java.util.Collection;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.IRequestCycle;
import org.tolweb.hibernate.TitleIllustration;
import org.tolweb.tapestry.injections.BaseInjectable;
import org.tolweb.tapestry.injections.ImageInjectable;
import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.ImageVersion;
import org.tolweb.treegrow.main.NodeImage;
import org.tolweb.treegrow.main.StringUtils;
/**
* @author dmandel
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class TitleIllustrations extends BaseComponent implements
ImageInjectable, BaseInjectable {
@SuppressWarnings("unchecked")
public abstract Collection getIllustrations();
public abstract TitleIllustration getCurrentIllustration();
public abstract void setCurrentIllustration(TitleIllustration value);
public abstract void setIsSingleIllustration(boolean value);
public abstract boolean getIsSingleIllustration();
public abstract int getIndex();
public abstract void setContributor(Contributor contributor);
public String getAltText() {
if (getCurrentIllustration().getImage() != null) {
NodeImage img = getCurrentIllustration().getImage();
if (StringUtils.notEmpty(img.getAltText())) {
return img.getAltText();
} else {
return " ";
}
} else {
return " ";
}
}
public void prepareForRender(IRequestCycle cycle) {
super.prepareForRender(cycle);
if (getIllustrations() != null && getIllustrations().size() == 1) {
setIsSingleIllustration(true);
} else {
setIsSingleIllustration(false);
}
}
public String getCurrentImageLocation() {
TitleIllustration currentIllustration = getCurrentIllustration();
ImageVersion version = currentIllustration.getVersion();
String url;
if (StringUtils.isEmpty(version.getFileName())) {
url = getImageDAO().generateAndSaveVersion(version);
} else {
url = getImageUtils().getVersionUrl(currentIllustration.getVersion());
}
return url;
}
public String getCurrentImageClass() {
if (getIsSingleIllustration()) {
return "singletillus";
} else {
return null;
}
}
}
|
tolweb/tolweb-app
|
OnlineContributors/src/org/tolweb/tapestry/TitleIllustrations.java
|
Java
|
bsd-3-clause
| 2,683 |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_ParticleState.cpp
//! \author Alex Robinson
//! \brief Basic particle state class definition.
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_ParticleState.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_DirectionHelpers.hpp"
namespace MonteCarlo{
// Default constructor
/*! \details The default constructor should only be called before loading the
* particle state from an archive.
*/
ParticleState::ParticleState()
: d_history_number( 0 ),
d_particle_type(),
d_position(),
d_direction{0.0,0.0,1.0},
d_energy( 0.0 ),
d_time( 0.0 ),
d_collision_number( 0 ),
d_generation_number( 0 ),
d_weight( 1.0 ),
d_cell( Geometry::ModuleTraits::invalid_internal_cell_handle ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{ /* ... */ }
// Constructor
ParticleState::ParticleState(
const ParticleState::historyNumberType history_number,
const ParticleType type )
: d_history_number( history_number ),
d_particle_type( type ),
d_position(),
d_direction(),
d_energy( 0.0 ),
d_time( 0.0 ),
d_collision_number( 0 ),
d_generation_number( 0 ),
d_weight( 1.0 ),
d_cell( Geometry::ModuleTraits::invalid_internal_cell_handle ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{ /* ... */ }
// Copy constructor
/*! \details When copied, the new particle is assumed to not be lost and
* not be gone.
*/
ParticleState::ParticleState( const ParticleState& existing_base_state,
const ParticleType new_type,
const bool increment_generation_number,
const bool reset_collision_number )
: d_history_number( existing_base_state.d_history_number ),
d_particle_type( new_type ),
d_position{existing_base_state.d_position[0],
existing_base_state.d_position[1],
existing_base_state.d_position[2]},
d_direction{existing_base_state.d_direction[0],
existing_base_state.d_direction[1],
existing_base_state.d_direction[2]},
d_energy( existing_base_state.d_energy ),
d_time( existing_base_state.d_time ),
d_collision_number( existing_base_state.d_collision_number ),
d_generation_number( existing_base_state.d_generation_number ),
d_weight( existing_base_state.d_weight ),
d_cell( existing_base_state.d_cell ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{
// Increment the generation number if requested
if( increment_generation_number )
++d_generation_number;
// Reset the collision number if requested
if( reset_collision_number )
d_collision_number = 0u;
}
// Clone the particle state but change the history number
/*! \details This method returns a heap-allocated pointer. It is only safe
* to call this method inside of a smart pointer constructor or reset method.
* The clone will only need a new history number in very rare circumstances
* (e.g. state source).
*/
ParticleState* ParticleState::clone(
const ParticleState::historyNumberType new_history_number ) const
{
ParticleState* clone_state = this->clone();
clone_state->d_history_number = new_history_number;
return clone_state;
}
// Return the history number
ParticleState::historyNumberType ParticleState::getHistoryNumber() const
{
return d_history_number;
}
// Return the particle type
ParticleType ParticleState::getParticleType() const
{
return d_particle_type;
}
// Return the cell handle for the cell containing the particle
Geometry::ModuleTraits::InternalCellHandle ParticleState::getCell() const
{
return d_cell;
}
// Set the cell containing the particle
void ParticleState::setCell(
const Geometry::ModuleTraits::InternalCellHandle cell )
{
// Make sure the cell handle is valid
testPrecondition( cell !=
Geometry::ModuleTraits::invalid_internal_cell_handle);
d_cell = cell;
}
// Return the x position of the particle
double ParticleState::getXPosition() const
{
return d_position[0];
}
// Return the y position of the particle
double ParticleState::getYPosition() const
{
return d_position[1];
}
// Return the z position of the particle
double ParticleState::getZPosition() const
{
return d_position[2];
}
// Return the position of the particle
const double* ParticleState::getPosition() const
{
return d_position;
}
// Set the position of the particle
void ParticleState::setPosition( const double x_position,
const double y_position,
const double z_position )
{
// Make sure the coordinates are valid
testPrecondition( !ST::isnaninf( x_position ) );
testPrecondition( !ST::isnaninf( y_position ) );
testPrecondition( !ST::isnaninf( z_position ) );
d_position[0] = x_position;
d_position[1] = y_position;
d_position[2] = z_position;
}
// Return the x direction of the particle
double ParticleState::getXDirection() const
{
return d_direction[0];
}
// Return the y direction of the particle
double ParticleState::getYDirection() const
{
return d_direction[1];
}
// Return the z direction of the particle
double ParticleState::getZDirection() const
{
return d_direction[2];
}
// Return the direction of the particle
const double* ParticleState::getDirection() const
{
return d_direction;
}
// Set the direction of the particle
void ParticleState::setDirection( const double x_direction,
const double y_direction,
const double z_direction )
{
// Make sure the direction coordinates are valid
testPrecondition( !ST::isnaninf( x_direction ) );
testPrecondition( !ST::isnaninf( y_direction ) );
testPrecondition( !ST::isnaninf( z_direction ) );
// Make sure the direction is a unit vector
testPrecondition( Utility::validDirection( x_direction,
y_direction,
z_direction ) );
d_direction[0] = x_direction;
d_direction[1] = y_direction;
d_direction[2] = z_direction;
}
// Rotate the direction of the particle using polar a. cosine and azimuthal a.
/*! \details The polar angle cosine and azimuthal angle are w.r.t. the
* current particle direction and not the global coordinate system. These
* are the variables the commonly occur when sampling a new direction
* for the particle from a scattering distribution. This function is therefore
* meant to avoid duplicate code that would otherwise arise when determining
* the new particle direction
*/
void ParticleState::rotateDirection( const double polar_angle_cosine,
const double azimuthal_angle )
{
// Make sure the current particle direction is valid (initialized)
testPrecondition( Utility::validDirection( this->getDirection() ) );
// Make sure the polar angle cosine is valid
testPrecondition( polar_angle_cosine >= -1.0 );
testPrecondition( polar_angle_cosine <= 1.0 );
// Make sure the azimuthal angle is valid
testPrecondition( azimuthal_angle >= 0.0 );
testPrecondition( azimuthal_angle <= 2*Utility::PhysicalConstants::pi );
double outgoing_direction[3];
Utility::rotateDirectionThroughPolarAndAzimuthalAngle( polar_angle_cosine,
azimuthal_angle,
this->getDirection(),
outgoing_direction );
this->setDirection( outgoing_direction );
}
// Advance the particle along its direction by the requested distance
void ParticleState::advance( const double distance )
{
// Make sure the distance is valid
testPrecondition( !ST::isnaninf( distance ) );
d_position[0] += d_direction[0]*distance;
d_position[1] += d_direction[1]*distance;
d_position[2] += d_direction[2]*distance;
// Compute the time to traverse the distance
d_time += calculateTraversalTime( distance );
}
// Set the energy of the particle
/*! The default implementation is only valid for massless particles (It is
* assumed that the speed of the particle does not change with the energy).
*/
void ParticleState::setEnergy( const ParticleState::energyType energy )
{
// Make sure the energy is valid
testPrecondition( !ST::isnaninf( energy ) );
testPrecondition( energy > 0.0 );
d_energy = energy;
}
// Return the time state of the particle
ParticleState::timeType ParticleState::getTime() const
{
return d_time;
}
// Set the time state of the particle
void ParticleState::setTime( const ParticleState::timeType time )
{
d_time = time;
}
// Return the collision number of the particle
ParticleState::collisionNumberType ParticleState::getCollisionNumber() const
{
return d_collision_number;
}
// Increment the collision number
void ParticleState::incrementCollisionNumber()
{
++d_collision_number;
}
// Reset the collision number
/*! \details This should rarely be used - try to rely on the contructor to
* reset the collision number.
*/
void ParticleState::resetCollisionNumber()
{
d_collision_number = 0u;
}
// Return the generation number of the particle
ParticleState::generationNumberType ParticleState::getGenerationNumber() const
{
return d_generation_number;
}
// Increment the generation number
void ParticleState::incrementGenerationNumber()
{
++d_generation_number;
}
// Return the weight of the particle
double ParticleState::getWeight() const
{
return d_weight;
}
// Set the weight of the particle
void ParticleState::setWeight( const double weight )
{
d_weight = weight;
}
// Multiply the weight of the particle by a factor
void ParticleState::multiplyWeight( const double weight_factor )
{
// Make sure that the current weight is valid
testPrecondition( d_weight > 0.0 );
d_weight *= weight_factor;
}
// Return if the particle is lost
bool ParticleState::isLost() const
{
return d_lost;
}
// Set the particle as lost
void ParticleState::setAsLost()
{
d_lost = true;
}
// Return if the particle is gone
bool ParticleState::isGone() const
{
return d_gone;
}
// Set the particle as gone
void ParticleState::setAsGone()
{
d_gone = true;
}
} // end MonteCarlo
//---------------------------------------------------------------------------//
// end MonteCarlo_ParticleState.cpp
//---------------------------------------------------------------------------//
|
lkersting/SCR-2123
|
packages/monte_carlo/core/src/MonteCarlo_ParticleState.cpp
|
C++
|
bsd-3-clause
| 10,274 |
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <[email protected]>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules;
/**
* @group rule
* @covers Respect\Validation\Rules\PrimeNumber
* @covers Respect\Validation\Exceptions\PrimeNumberException
*/
class PrimeNumberTest extends \PHPUnit_Framework_TestCase
{
protected $object;
protected function setUp()
{
$this->object = new PrimeNumber();
}
/**
* @dataProvider providerForPrimeNumber
*/
public function testPrimeNumber($input)
{
$this->assertTrue($this->object->__invoke($input));
$this->assertTrue($this->object->check($input));
$this->assertTrue($this->object->assert($input));
}
/**
* @dataProvider providerForNotPrimeNumber
* @expectedException Respect\Validation\Exceptions\PrimeNumberException
*/
public function testNotPrimeNumber($input)
{
$this->assertFalse($this->object->__invoke($input));
$this->assertFalse($this->object->assert($input));
}
public function providerForPrimeNumber()
{
return array(
array(3),
array(5),
array(7),
array('3'),
array('5'),
array('+7'),
);
}
public function providerForNotPrimeNumber()
{
return array(
array(''),
array(null),
array(0),
array(10),
array(25),
array(36),
array(-1),
array('-1'),
array('25'),
array('0'),
array('a'),
array(' '),
array('Foo'),
);
}
}
|
zinovyev/Validation
|
tests/unit/Rules/PrimeNumberTest.php
|
PHP
|
bsd-3-clause
| 1,843 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/set_time_dialog.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/string16.h"
#include "chrome/common/url_constants.h"
#include "chromeos/login/login_state/login_state.h"
#include "ui/gfx/geometry/size.h"
namespace chromeos {
namespace {
// Dialog width and height in DIPs.
const int kDefaultWidth = 530;
const int kDefaultHeightWithTimezone = 286;
const int kDefaultHeightWithoutTimezone = 228;
} // namespace
// static
void SetTimeDialog::ShowDialog(gfx::NativeWindow parent) {
base::RecordAction(base::UserMetricsAction("Options_SetTimeDialog_Show"));
auto* dialog = new SetTimeDialog();
dialog->ShowSystemDialog(parent);
}
// static
bool SetTimeDialog::ShouldShowTimezone() {
// After login the user should set the timezone via Settings, which applies
// additional restrictions.
return !LoginState::Get()->IsUserLoggedIn();
}
SetTimeDialog::SetTimeDialog()
: SystemWebDialogDelegate(GURL(chrome::kChromeUISetTimeURL),
base::string16() /* title */) {}
SetTimeDialog::~SetTimeDialog() = default;
void SetTimeDialog::GetDialogSize(gfx::Size* size) const {
size->SetSize(kDefaultWidth, ShouldShowTimezone()
? kDefaultHeightWithTimezone
: kDefaultHeightWithoutTimezone);
}
} // namespace chromeos
|
endlessm/chromium-browser
|
chrome/browser/chromeos/set_time_dialog.cc
|
C++
|
bsd-3-clause
| 1,543 |
/*
* GaussianKernel.java
*
* Created on September 25, 2004, 4:52 PM
*/
package jpview.graphics;
/**
* This class creates a kernel for use by an AffineTransformOp
*
* @author clyon
*/
public class GaussianKernel {
private int radius = 5;
private float sigma = 1;
private float[] kernel;
/** Creates a new instance of GaussianKernel */
public GaussianKernel() {
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius
*
* @param r
* the radius for the gaussian kernel
*/
public GaussianKernel(int r) {
radius = r;
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius and sigma value
*
* @param r
* the radius of the blur
* @param s
* the sigma value for the kernel
*/
public GaussianKernel(int r, float s) {
radius = r;
sigma = s;
kernel = makeKernel();
}
private float[] makeKernel() {
kernel = new float[radius * radius];
float sum = 0;
for (int y = 0; y < radius; y++) {
for (int x = 0; x < radius; x++) {
int off = y * radius + x;
int xx = x - radius / 2;
int yy = y - radius / 2;
kernel[off] = (float) Math.pow(Math.E, -(xx * xx + yy * yy)
/ (2 * (sigma * sigma)));
sum += kernel[off];
}
}
for (int i = 0; i < kernel.length; i++)
kernel[i] /= sum;
return kernel;
}
/**
* Dumps a string representation of the kernel to standard out
*/
public void dump() {
for (int x = 0; x < radius; x++) {
for (int y = 0; y < radius; y++) {
System.out.print(kernel[y * radius + x] + "\t");
}
System.out.println();
}
}
/**
* returns the kernel as a float [] suitable for use with an affine
* transform
*
* @return the kernel values
*/
public float[] getKernel() {
return kernel;
}
public static void main(String args[]) {
GaussianKernel gk = new GaussianKernel(5, 100f);
gk.dump();
}
}
|
synergynet/synergynet3
|
synergynet3-museum-parent/synergynet3-museum-table/src/main/java/jpview/graphics/GaussianKernel.java
|
Java
|
bsd-3-clause
| 2,024 |
<?php
/**
* This file is part of the proophsoftware/event-machine.
* (c) 2017-2019 prooph software GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ProophExample\FunctionalFlavour;
use Prooph\EventMachine\Messaging\Message;
use Prooph\EventMachine\Messaging\MessageBag;
use Prooph\EventMachine\Runtime\Functional\Port;
use ProophExample\FunctionalFlavour\Api\Command;
use ProophExample\FunctionalFlavour\Api\Event;
use ProophExample\FunctionalFlavour\Api\Query;
final class ExampleFunctionalPort implements Port
{
/**
* {@inheritdoc}
*/
public function deserialize(Message $message)
{
//Note: we use a very simple mapping strategy here
//You could also use a deserializer or other techniques
switch ($message->messageType()) {
case Message::TYPE_COMMAND:
return Command::createFromNameAndPayload($message->messageName(), $message->payload());
case Message::TYPE_EVENT:
return Event::createFromNameAndPayload($message->messageName(), $message->payload());
case Message::TYPE_QUERY:
return Query::createFromNameAndPayload($message->messageName(), $message->payload());
}
}
/**
* {@inheritdoc}
*/
public function serializePayload($customMessage): array
{
//Since, we use objects with public properties as custom messages, casting to array is enough
//In a production setting, you should use your own immutable messages and a serializer
return (array) $customMessage;
}
/**
* {@inheritdoc}
*/
public function decorateEvent($customEvent): MessageBag
{
return new MessageBag(
Event::nameOf($customEvent),
MessageBag::TYPE_EVENT,
$customEvent
);
}
/**
* {@inheritdoc}
*/
public function getAggregateIdFromCommand(string $aggregateIdPayloadKey, $command): string
{
//Duck typing, do not do this in production but rather use your own interfaces
return $command->{$aggregateIdPayloadKey};
}
/**
* {@inheritdoc}
*/
public function callCommandPreProcessor($customCommand, $preProcessor)
{
//Duck typing, do not do this in production but rather use your own interfaces
return $preProcessor->preProcess($customCommand);
}
/**
* {@inheritdoc}
*/
public function callContextProvider($customCommand, $contextProvider)
{
//Duck typing, do not do this in production but rather use your own interfaces
return $contextProvider->provide($customCommand);
}
}
|
proophsoftware/event-machine
|
examples/FunctionalFlavour/ExampleFunctionalPort.php
|
PHP
|
bsd-3-clause
| 2,788 |
// Copyright 2016 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 ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
#define ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
#include "ash/ash_export.h"
#include "base/macros.h"
namespace ash {
namespace test {
class MaterialDesignControllerTestAPI;
} // namespace test
// Central controller to handle material design modes.
class ASH_EXPORT MaterialDesignController {
public:
// The different material design modes for Chrome OS system UI.
enum Mode {
// Not initialized.
UNINITIALIZED = -1,
// Classic, non-material design.
NON_MATERIAL = 0,
// Basic material design.
MATERIAL_NORMAL = 1,
// Material design with experimental features.
MATERIAL_EXPERIMENTAL = 2
};
// Initializes |mode_|. Must be called before calling IsMaterial(),
// IsMaterialExperimental(), IsMaterialNormal(), or GetMode().
static void Initialize();
// Returns the currently initialized MaterialDesignController::Mode type for
// Chrome OS system UI.
static Mode GetMode();
// Returns true if overview mode is using Material Design.
static bool IsOverviewMaterial();
// Returns true if Material Design features are enabled for Chrome OS shelf.
static bool IsShelfMaterial();
// Returns true if Material Design features are enabled for Chrome OS system
// tray menu.
static bool IsSystemTrayMenuMaterial();
// Returns true if material design versions of icons should be used in the
// status tray and system menu.
static bool UseMaterialDesignSystemIcons();
private:
friend class test::MaterialDesignControllerTestAPI;
// Declarations only. Do not allow construction of an object.
MaterialDesignController();
~MaterialDesignController();
// Material Design |Mode| for Chrome OS system UI. Used only by tests.
static Mode mode();
// Returns true if Material Design is enabled in Chrome OS system UI.
// Maps to "ash-md" flag "enabled" or "experimental" values.
static bool IsMaterial();
// Returns true if Material Design normal features are enabled in Chrome OS
// system UI. Maps to "--ash-md=enabled" command line switch value.
static bool IsMaterialNormal();
// Returns true if Material Design experimental features are enabled in
// Chrome OS system UI. Maps to "--ash-md=experimental" command line switch
// value.
static bool IsMaterialExperimental();
// Returns the per-platform default material design variant.
static Mode DefaultMode();
// Sets |mode_| to |mode|. Can be used by tests to directly set the mode.
static void SetMode(Mode mode);
// Resets the initialization state to uninitialized. To be used by tests to
// allow calling Initialize() more than once.
static void Uninitialize();
DISALLOW_COPY_AND_ASSIGN(MaterialDesignController);
};
} // namespace ash
#endif // ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
|
danakj/chromium
|
ash/common/material_design/material_design_controller.h
|
C
|
bsd-3-clause
| 3,032 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
#define CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
#include <string>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/image_decoder.h"
class SkBitmap;
namespace base {
class SequencedTaskRunner;
}
namespace user_manager {
class UserImage;
}
namespace chromeos {
// Helper that reads, decodes and optionally resizes an image on a background
// thread. Returns the image in the form of an SkBitmap.
class UserImageLoader : public base::RefCountedThreadSafe<UserImageLoader> {
public:
// Callback used to return the result of an image load operation.
typedef base::Callback<void(const user_manager::UserImage& user_image)>
LoadedCallback;
// All file I/O, decoding and resizing are done via |background_task_runner|.
UserImageLoader(
ImageDecoder::ImageCodec image_codec,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
// Load an image in the background and call |loaded_cb| with the resulting
// UserImage (which may be empty in case of error). If |pixels_per_side| is
// positive, the image is cropped to a square and shrunk so that it does not
// exceed |pixels_per_side|x|pixels_per_side|. The first variant of this
// method reads the image from |filepath| on disk, the second processes |data|
// read into memory already.
void Start(const std::string& filepath,
int pixels_per_side,
const LoadedCallback& loaded_cb);
void Start(scoped_ptr<std::string> data,
int pixels_per_side,
const LoadedCallback& loaded_cb);
private:
friend class base::RefCountedThreadSafe<UserImageLoader>;
// Contains attributes we need to know about each image we decode.
struct ImageInfo {
ImageInfo(const std::string& file_path,
int pixels_per_side,
const LoadedCallback& loaded_cb);
~ImageInfo();
const std::string file_path;
const int pixels_per_side;
const LoadedCallback loaded_cb;
};
class UserImageRequest : public ImageDecoder::ImageRequest {
public:
UserImageRequest(const ImageInfo& image_info,
const std::string& image_data,
UserImageLoader* user_image_loader);
// ImageDecoder::ImageRequest implementation. These callbacks will only be
// invoked via user_image_loader_'s background_task_runner_.
void OnImageDecoded(const SkBitmap& decoded_image) override;
void OnDecodeImageFailed() override;
private:
~UserImageRequest() override;
const ImageInfo image_info_;
std::vector<unsigned char> image_data_;
UserImageLoader* user_image_loader_;
};
~UserImageLoader();
// Reads the image from |image_info.file_path| and starts the decoding
// process. This method may only be invoked via the |background_task_runner_|.
void ReadAndDecodeImage(const ImageInfo& image_info);
// Decodes the image |data|. This method may only be invoked via the
// |background_task_runner_|.
void DecodeImage(const scoped_ptr<std::string> data,
const ImageInfo& image_info);
// The foreground task runner on which |this| is instantiated, Start() is
// called and LoadedCallbacks are invoked.
scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_;
// The background task runner on which file I/O, image decoding and resizing
// are done.
scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
// Specify how the file should be decoded in the utility process.
const ImageDecoder::ImageCodec image_codec_;
DISALLOW_COPY_AND_ASSIGN(UserImageLoader);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
|
mou4e/zirconium
|
chrome/browser/chromeos/login/users/avatar/user_image_loader.h
|
C
|
bsd-3-clause
| 4,006 |
//===-- MainLoopBase.h ------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_HOST_MAINLOOPBASE_H
#define LLDB_HOST_MAINLOOPBASE_H
#include "lldb/Utility/IOObject.h"
#include "lldb/Utility/Status.h"
#include "llvm/Support/ErrorHandling.h"
#include <functional>
namespace lldb_private {
// The purpose of this class is to enable multiplexed processing of data from
// different sources without resorting to multi-threading. Clients can register
// IOObjects, which will be monitored for readability, and when they become
// ready, the specified callback will be invoked. Monitoring for writability is
// not supported, but can be easily added if needed.
//
// The RegisterReadObject function return a handle, which controls the duration
// of the monitoring. When this handle is destroyed, the callback is
// deregistered.
//
// This class simply defines the interface common for all platforms, actual
// implementations are platform-specific.
class MainLoopBase {
private:
class ReadHandle;
public:
MainLoopBase() {}
virtual ~MainLoopBase() {}
typedef std::unique_ptr<ReadHandle> ReadHandleUP;
typedef std::function<void(MainLoopBase &)> Callback;
virtual ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp,
const Callback &callback,
Status &error) {
llvm_unreachable("Not implemented");
}
// Waits for registered events and invoke the proper callbacks. Returns when
// all callbacks deregister themselves or when someone requests termination.
virtual Status Run() { llvm_unreachable("Not implemented"); }
// Requests the exit of the Run() function.
virtual void RequestTermination() { llvm_unreachable("Not implemented"); }
protected:
ReadHandleUP CreateReadHandle(const lldb::IOObjectSP &object_sp) {
return ReadHandleUP(new ReadHandle(*this, object_sp->GetWaitableHandle()));
}
virtual void UnregisterReadObject(IOObject::WaitableHandle handle) {
llvm_unreachable("Not implemented");
}
private:
class ReadHandle {
public:
~ReadHandle() { m_mainloop.UnregisterReadObject(m_handle); }
private:
ReadHandle(MainLoopBase &mainloop, IOObject::WaitableHandle handle)
: m_mainloop(mainloop), m_handle(handle) {}
MainLoopBase &m_mainloop;
IOObject::WaitableHandle m_handle;
friend class MainLoopBase;
DISALLOW_COPY_AND_ASSIGN(ReadHandle);
};
private:
DISALLOW_COPY_AND_ASSIGN(MainLoopBase);
};
} // namespace lldb_private
#endif // LLDB_HOST_MAINLOOPBASE_H
|
endlessm/chromium-browser
|
third_party/llvm/lldb/include/lldb/Host/MainLoopBase.h
|
C
|
bsd-3-clause
| 2,859 |
\hypertarget{ChassisTurnRate_8cpp}{\section{framework/\-Chassis\-Turn\-Rate.cpp File Reference}
\label{ChassisTurnRate_8cpp}\index{framework/\-Chassis\-Turn\-Rate.\-cpp@{framework/\-Chassis\-Turn\-Rate.\-cpp}}
}
\hyperlink{classChassisTurnRate}{Chassis\-Turn\-Rate} is a strictly defined type for specifying the turn rate of a moving chassis.
{\ttfamily \#include \char`\"{}Chassis\-Turn\-Rate.\-hpp\char`\"{}}\\*
\subsection{Detailed Description}
\hyperlink{classChassisTurnRate}{Chassis\-Turn\-Rate} is a strictly defined type for specifying the turn rate of a moving chassis. \begin{DoxyCopyright}{Copyright}
(c) 2017 Mark R. Jenkins. All rights reserved.
\end{DoxyCopyright}
\begin{DoxyAuthor}{Author}
M\-Jenkins, E\-N\-P\-M 808\-X Spring 2017
\end{DoxyAuthor}
\begin{DoxyDate}{Date}
Mar 13, 2017 -\/ Creation
\end{DoxyDate}
\hyperlink{classChassis}{Chassis} turn rates may be specified in a variety of ways; the one implemented here is as a degree of turn per foot of movement. This class creates a strict type for chassis turn rates, and can provide a variety of accessor functiont so allow setting/getting the turn rate in different units. The class stores the turn rate internaly as \char`\"{}\-Degrees per Foot of movement\char`\"{}. Note that a zero turn rate indicates movement straight ahead, a negative turn rate indicates a deviation (turn) to the left, and a positive turn rate indicates a deviation (turn) to the right.
|
mark1-umd/mtp-MCSF
|
docs/latex/ChassisTurnRate_8cpp.tex
|
TeX
|
bsd-3-clause
| 1,445 |
Гость создан
|
Veredior/filesender
|
language/ru_RU/guest_created.mail.php
|
PHP
|
bsd-3-clause
| 23 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeClassQualifiedName;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.CronetEngine;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.urlconnection.CronetHttpURLConnection;
import org.chromium.net.urlconnection.CronetURLStreamHandlerFactory;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.GuardedBy;
/**
* CronetEngine using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
@UsedByReflection("CronetEngine.java")
@VisibleForTesting
public class CronetUrlRequestContext extends CronetEngine {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long mUrlRequestContextAdapter = 0;
private Thread mNetworkThread;
private boolean mNetworkQualityEstimatorEnabled;
/**
* Locks operations on network quality listeners, because listener
* addition and removal may occur on a different thread from notification.
*/
private final Object mNetworkQualityLock = new Object();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityRttListener> mRttListenerList =
new ObserverList<NetworkQualityRttListener>();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityThroughputListener> mThroughputListenerList =
new ObserverList<NetworkQualityThroughputListener>();
@GuardedBy("mFinishedListenerLock")
private final List<RequestFinishedInfo.Listener> mFinishedListenerList =
new ArrayList<RequestFinishedInfo.Listener>();
/**
* Synchronize access to mCertVerifierData.
*/
private ConditionVariable mWaitGetCertVerifierDataComplete = new ConditionVariable();
/** Holds CertVerifier data. */
private String mCertVerifierData;
@UsedByReflection("CronetEngine.java")
public CronetUrlRequestContext(final CronetEngine.Builder builder) {
CronetLibraryLoader.ensureInitialized(builder.getContext(), builder);
nativeSetMinLogLevel(getLoggingLevel());
synchronized (mLock) {
mUrlRequestContextAdapter = nativeCreateRequestContextAdapter(
createNativeUrlRequestContextConfig(builder.getContext(), builder));
if (mUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed.");
}
mNetworkQualityEstimatorEnabled = builder.networkQualityEstimatorEnabled();
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
CronetLibraryLoader.ensureInitializedOnMainThread(builder.getContext());
synchronized (mLock) {
// mUrlRequestContextAdapter is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
nativeInitRequestContextOnMainThread(mUrlRequestContextAdapter);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@VisibleForTesting
public static long createNativeUrlRequestContextConfig(
final Context context, CronetEngine.Builder builder) {
final long urlRequestContextConfig = nativeCreateRequestContextConfig(
builder.getUserAgent(), builder.storagePath(), builder.quicEnabled(),
builder.getDefaultQuicUserAgentId(context), builder.http2Enabled(),
builder.sdchEnabled(), builder.dataReductionProxyKey(),
builder.dataReductionProxyPrimaryProxy(), builder.dataReductionProxyFallbackProxy(),
builder.dataReductionProxySecureProxyCheckUrl(), builder.cacheDisabled(),
builder.httpCacheMode(), builder.httpCacheMaxSize(), builder.experimentalOptions(),
builder.mockCertVerifier(), builder.networkQualityEstimatorEnabled(),
builder.publicKeyPinningBypassForLocalTrustAnchorsEnabled(),
builder.certVerifierData());
for (Builder.QuicHint quicHint : builder.quicHints()) {
nativeAddQuicHint(urlRequestContextConfig, quicHint.mHost, quicHint.mPort,
quicHint.mAlternatePort);
}
for (Builder.Pkp pkp : builder.publicKeyPins()) {
nativeAddPkp(urlRequestContextConfig, pkp.mHost, pkp.mHashes, pkp.mIncludeSubdomains,
pkp.mExpirationDate.getTime());
}
return urlRequestContextConfig;
}
@Override
public UrlRequest createRequest(String url, UrlRequest.Callback callback, Executor executor,
int priority, Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration) {
synchronized (mLock) {
checkHaveAdapter();
boolean metricsCollectionEnabled = false;
synchronized (mFinishedListenerLock) {
metricsCollectionEnabled = !mFinishedListenerList.isEmpty();
}
return new CronetUrlRequest(this, url, priority, callback, executor, requestAnnotations,
metricsCollectionEnabled, disableCache, disableConnectionMigration);
}
}
@Override
public BidirectionalStream createBidirectionalStream(String url,
BidirectionalStream.Callback callback, Executor executor, String httpMethod,
List<Map.Entry<String, String>> requestHeaders,
@BidirectionalStream.Builder.StreamPriority int priority, boolean disableAutoFlush,
boolean delayRequestHeadersUntilFirstFlush) {
synchronized (mLock) {
checkHaveAdapter();
return new CronetBidirectionalStream(this, url, priority, callback, executor,
httpMethod, requestHeaders, disableAutoFlush,
delayRequestHeadersUntilFirstFlush);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getVersionString() {
return "Cronet/" + ImplVersion.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
nativeDestroy(mUrlRequestContextAdapter);
mUrlRequestContextAdapter = 0;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
synchronized (mLock) {
checkHaveAdapter();
nativeStartNetLogToFile(mUrlRequestContextAdapter, fileName, logAll);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(mUrlRequestContextAdapter);
}
}
@Override
public String getCertVerifierData(long timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be a positive value");
} else if (timeout == 0) {
timeout = 100;
}
mWaitGetCertVerifierDataComplete.close();
synchronized (mLock) {
checkHaveAdapter();
nativeGetCertVerifierData(mUrlRequestContextAdapter);
}
mWaitGetCertVerifierDataComplete.block(timeout);
return mCertVerifierData;
}
// This method is intentionally non-static to ensure Cronet native library
// is loaded by class constructor.
@Override
public byte[] getGlobalMetricsDeltas() {
return nativeGetHistogramDeltas();
}
@VisibleForTesting
@Override
public void configureNetworkQualityEstimatorForTesting(
boolean useLocalHostRequests, boolean useSmallerResponses) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mLock) {
checkHaveAdapter();
nativeConfigureNetworkQualityEstimatorForTesting(
mUrlRequestContextAdapter, useLocalHostRequests, useSmallerResponses);
}
}
@Override
public void addRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, true);
}
}
mRttListenerList.addObserver(listener);
}
}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mRttListenerList.removeObserver(listener);
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, true);
}
}
mThroughputListenerList.addObserver(listener);
}
}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mThroughputListenerList.removeObserver(listener);
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.add(listener);
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.remove(listener);
}
}
@Override
public URLConnection openConnection(URL url) {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronetHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronetURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() {
mActiveRequestCount.decrementAndGet();
}
@VisibleForTesting
public long getUrlRequestContextAdapter() {
synchronized (mLock) {
checkHaveAdapter();
return mUrlRequestContextAdapter;
}
}
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
private boolean haveRequestContextAdapter() {
return mUrlRequestContextAdapter != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityRttListener listener : mRttListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRttObservation(rttMs, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onThroughputObservation(
final int throughputKbps, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityThroughputListener listener : mThroughputListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onThroughputObservation(throughputKbps, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onGetCertVerifierData(String certVerifierData) {
mCertVerifierData = certVerifierData;
mWaitGetCertVerifierDataComplete.open();
}
void reportFinished(final CronetUrlRequest request) {
final RequestFinishedInfo requestInfo = request.getRequestFinishedInfo();
ArrayList<RequestFinishedInfo.Listener> currentListeners;
synchronized (mFinishedListenerLock) {
currentListeners = new ArrayList<RequestFinishedInfo.Listener>(mFinishedListenerList);
}
for (final RequestFinishedInfo.Listener listener : currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
// Native methods are implemented in cronet_url_request_context_adapter.cc.
private static native long nativeCreateRequestContextConfig(String userAgent,
String storagePath, boolean quicEnabled, String quicUserAgentId, boolean http2Enabled,
boolean sdchEnabled, String dataReductionProxyKey,
String dataReductionProxyPrimaryProxy, String dataReductionProxyFallbackProxy,
String dataReductionProxySecureProxyCheckUrl, boolean disableCache, int httpCacheMode,
long httpCacheMaxSize, String experimentalOptions, long mockCertVerifier,
boolean enableNetworkQualityEstimator,
boolean bypassPublicKeyPinningForLocalTrustAnchors, String certVerifierData);
private static native void nativeAddQuicHint(
long urlRequestContextConfig, String host, int port, int alternatePort);
private static native void nativeAddPkp(long urlRequestContextConfig, String host,
byte[][] hashes, boolean includeSubdomains, long expirationTime);
private static native long nativeCreateRequestContextAdapter(long urlRequestContextConfig);
private static native int nativeSetMinLogLevel(int loggingLevel);
private static native byte[] nativeGetHistogramDeltas();
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeDestroy(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStartNetLogToFile(long nativePtr, String fileName, boolean logAll);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStopNetLog(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeGetCertVerifierData(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeInitRequestContextOnMainThread(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeConfigureNetworkQualityEstimatorForTesting(
long nativePtr, boolean useLocalHostRequests, boolean useSmallerResponses);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideRTTObservations(long nativePtr, boolean should);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideThroughputObservations(long nativePtr, boolean should);
}
|
danakj/chromium
|
components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java
|
Java
|
bsd-3-clause
| 21,435 |
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUXMETA_METAPROTOCOL_H
#define FLUXMETA_METAPROTOCOL_H
#include <flux/meta/MetaObject>
namespace flux {
namespace meta {
/** \brief Duck-typed object protocol
*/
class MetaProtocol: public Object
{
public:
inline static Ref<MetaProtocol> create() {
return new MetaProtocol;
}
template<class Prototype>
Prototype *define(const String &className) {
Ref<Prototype> prototype = Prototype::create(className);
define(prototype);
return prototype;
}
template<class Prototype>
Prototype *define() {
Ref<Prototype> prototype = Prototype::create();
define(prototype);
return prototype;
}
MetaObject *define(MetaObject *prototype) {
prototype->define();
prototypes()->insert(prototype->className(), prototype);
return prototype;
}
template<class Prototype>
static Ref<MetaObject> createPrototype() {
Ref<MetaObject> prototype = Prototype::create();
prototype->define();
return prototype;
}
virtual MetaObject *lookup(String className) const {
MetaObject *prototype = 0;
if (prototypes_) prototypes_->lookup(className, &prototype);
return prototype;
}
int minCount() const { return minCount_; }
int maxCount() const { return maxCount_; }
void minCount(int newCount) { minCount_ = newCount; }
void maxCount(int newCount) { maxCount_ = newCount; }
inline bool lookup(const String &className, MetaObject **prototype) const {
*prototype = lookup(className);
return *prototype;
}
protected:
friend class YasonSyntax;
MetaProtocol():
minCount_(0),
maxCount_(flux::intMax)
{}
virtual Ref<MetaObject> produce(MetaObject *prototype) const {
return prototype->produce();
}
private:
typedef Map<String, Ref<MetaObject> > Prototypes;
Prototypes *prototypes() {
if (!prototypes_) prototypes_ = Prototypes::create();
return prototypes_;
}
Ref<Prototypes> prototypes_;
int minCount_;
int maxCount_;
};
}} // namespace flux::meta
#endif // FLUXMETA_METAPROTOCOL_H
|
frankencode/fluxkit
|
meta/src/MetaProtocol.h
|
C
|
bsd-3-clause
| 2,330 |
module Carto
module Configuration
def db_config
@@db_config ||= YAML.load(File.read(db_config_file)).freeze
end
def app_config
@@app_config ||= YAML.load_file(app_config_file).freeze
end
def frontend_version
@@frontend_version ||= JSON::parse(File.read(Rails.root.join("package.json")))["version"]
end
def env_app_config
app_config[ENV['RAILS_ENV'] || 'development']
end
def log_file_path(filename)
"#{log_dir_path}/#{filename}"
end
def log_dir_path
"#{log_files_root}/log"
end
def public_uploaded_assets_path
public_uploads_path('uploads')
end
def public_uploads_path(subfolder = '')
path_with_alternative('RAILS_PUBLIC_UPLOADS_PATH', subfolder) do
if env_app_config && env_app_config[:importer] && env_app_config[:importer]["uploads_path"]
env_app_config[:importer]["uploads_path"]
else
Rails.root.join('public', subfolder).to_s
end
end
end
def uploaded_file_path(path)
pathname = Pathname.new(path)
return path if pathname.exist? && pathname.absolute?
upload_path = Cartodb.get_config(:importer, 'uploads_path')
if upload_path
# Ugly patch needed for backwards compatibility
"#{upload_path}#{path}".gsub('/uploads/uploads/', '/uploads/')
else
Rails.root.join("public#{path}").to_s
end
end
def custom_app_views_paths
config = env_app_config
(config && config['custom_paths'] && config['custom_paths']['views']) || Array.new
end
def saas?
Cartodb.config[:cartodb_com_hosted] == false
end
def mapzen_api_key
Cartodb.get_config(:geocoder, 'mapzen', 'search_bar_api_key')
end
def mapbox_api_key
Cartodb.get_config(:geocoder, 'mapbox', 'search_bar_api_key')
end
# Make some methods available. Remember that this sets methods as private.
# More information: https://idiosyncratic-ruby.com/8-self-improvement.html
# This is the chosen approach to avoid including `Configuration` all over the place. Check #12757
module_function :saas?
private
def config_files_root
rails_path('RAILS_CONFIG_BASE_PATH')
end
def log_files_root
rails_path('RAILS_LOG_BASE_PATH')
end
def rails_path(environment_variable)
path_with_alternative(environment_variable) { Rails.root }
end
# Returns an string, block should as well
def path_with_alternative(environment_variable, subfolder_at_environment = '')
if ENV[environment_variable]
Pathname.new(ENV[environment_variable]).join(subfolder_at_environment).to_s
else
alternative = yield
alternative || ''
end
end
def db_config_file
if ENV['RAILS_DATABASE_FILE']
File.join(config_files_root, 'config/' + ENV['RAILS_DATABASE_FILE'])
else
File.join(config_files_root, 'config/database.yml')
end
end
def app_config_file
"#{config_files_root}/config/app_config.yml"
end
end
class Conf
include Carto::Configuration
end
end
|
splashblot/dronedb
|
lib/carto/configuration.rb
|
Ruby
|
bsd-3-clause
| 3,138 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_33) on Fri Jul 13 11:10:51 CEST 2012 -->
<TITLE>
Sample
</TITLE>
<META NAME="date" CONTENT="2012-07-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Sample";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Sample.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../converter/FrameNetConverterTest.html" title="class in converter"><B>PREV CLASS</B></A>
<A HREF="../converter/TigerXmlConverter.html" title="class in converter"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?converter/Sample.html" target="_top"><B>FRAMES</B></A>
<A HREF="Sample.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
converter</FONT>
<BR>
Class Sample</H2>
<PRE>
java.lang.Object
<IMG SRC="../resources/inherit.gif" ALT="extended by "><B>converter.Sample</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>Sample</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../converter/Sample.html#Sample()">Sample</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../converter/Sample.html#convertFromTigerXmlToFramenet()">convertFromTigerXmlToFramenet</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="Sample()"><!-- --></A><H3>
Sample</H3>
<PRE>
public <B>Sample</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="convertFromTigerXmlToFramenet()"><!-- --></A><H3>
convertFromTigerXmlToFramenet</H3>
<PRE>
public void <B>convertFromTigerXmlToFramenet</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Sample.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../converter/FrameNetConverterTest.html" title="class in converter"><B>PREV CLASS</B></A>
<A HREF="../converter/TigerXmlConverter.html" title="class in converter"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?converter/Sample.html" target="_top"><B>FRAMES</B></A>
<A HREF="Sample.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
svoos/CorpusConverter
|
doc/converter/Sample.html
|
HTML
|
bsd-3-clause
| 9,344 |
/* Copyright (C) 2002 Jean-Marc Valin */
/**
@file speex_bits.h
@brief Handles bit packing/unpacking
*/
/*
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 Xiph.org Foundation 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 FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BITS_H
#define BITS_H
/** @defgroup SpeexBits SpeexBits: Bit-stream manipulations
* This is the structure that holds the bit-stream when encoding or decoding
* with Speex. It allows some manipulations as well.
* @{
*/
#include "speex_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Bit-packing data structure representing (part of) a bit-stream. */
typedef struct SpeexBits {
char *chars; /**< "raw" data */
int nbBits; /**< Total number of bits stored in the stream*/
int charPtr; /**< Position of the byte "cursor" */
int bitPtr; /**< Position of the bit "cursor" within the current char */
int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */
int overflow;/**< Set to one if we try to read past the valid data */
int buf_size;/**< Allocated size for buffer */
int reserved1; /**< Reserved for future use */
void *reserved2; /**< Reserved for future use */
} SpeexBits;
/** Initializes and allocates resources for a SpeexBits struct */
PUBLIC_API void speex_bits_init(SpeexBits *bits);
/** Initializes SpeexBits struct using a pre-allocated buffer*/
PUBLIC_API void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size);
/** Sets the bits in a SpeexBits struct to use data from an existing buffer (for decoding without copying data) */
PUBLIC_API void speex_bits_set_bit_buffer(SpeexBits *bits, void *buff, int buf_size);
/** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/
PUBLIC_API void speex_bits_destroy(SpeexBits *bits);
/** Resets bits to initial value (just after initialization, erasing content)*/
PUBLIC_API void speex_bits_reset(SpeexBits *bits);
/** Rewind the bit-stream to the beginning (ready for read) without erasing the content */
PUBLIC_API void speex_bits_rewind(SpeexBits *bits);
/** Initializes the bit-stream from the data in an area of memory */
PUBLIC_API void speex_bits_read_from(SpeexBits *bits, const char *bytes, int len);
/** Append bytes to the bit-stream
*
* @param bits Bit-stream to operate on
* @param bytes pointer to the bytes what will be appended
* @param len Number of bytes of append
*/
PUBLIC_API void speex_bits_read_whole_bytes(SpeexBits *bits, const char *bytes, int len);
/** Write the content of a bit-stream to an area of memory
*
* @param bits Bit-stream to operate on
* @param bytes Memory location where to write the bits
* @param max_len Maximum number of bytes to write (i.e. size of the "bytes" buffer)
* @return Number of bytes written to the "bytes" buffer
*/
PUBLIC_API int speex_bits_write(SpeexBits *bits, char *bytes, int max_len);
/** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */
PUBLIC_API int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len);
/** Append bits to the bit-stream
* @param bits Bit-stream to operate on
* @param data Value to append as integer
* @param nbBits number of bits to consider in "data"
*/
PUBLIC_API void speex_bits_pack(SpeexBits *bits, int data, int nbBits);
/** Interpret the next bits in the bit-stream as a signed integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return A signed integer represented by the bits read
*/
PUBLIC_API int speex_bits_unpack_signed(SpeexBits *bits, int nbBits);
/** Interpret the next bits in the bit-stream as an unsigned integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return An unsigned integer represented by the bits read
*/
PUBLIC_API unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits);
/** Returns the number of bytes in the bit-stream, including the last one even if it is not "full"
*
* @param bits Bit-stream to operate on
* @return Number of bytes in the stream
*/
PUBLIC_API int speex_bits_nbytes(SpeexBits *bits);
/** Same as speex_bits_unpack_unsigned, but without modifying the cursor position
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to look for
* @return Value of the bits peeked, interpreted as unsigned
*/
PUBLIC_API unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits);
/** Get the value of the next bit in the stream, without modifying the
* "cursor" position
*
* @param bits Bit-stream to operate on
* @return Value of the bit peeked (one bit only)
*/
PUBLIC_API int speex_bits_peek(SpeexBits *bits);
/** Advances the position of the "bit cursor" in the stream
*
* @param bits Bit-stream to operate on
* @param n Number of bits to advance
*/
PUBLIC_API void speex_bits_advance(SpeexBits *bits, int n);
/** Returns the number of bits remaining to be read in a stream
*
* @param bits Bit-stream to operate on
* @return Number of bits that can still be read from the stream
*/
PUBLIC_API int speex_bits_remaining(SpeexBits *bits);
/** Insert a terminator so that the data can be sent as a packet while auto-detecting
* the number of frames in each packet
*
* @param bits Bit-stream to operate on
*/
PUBLIC_API void speex_bits_insert_terminator(SpeexBits *bits);
#ifdef __cplusplus
}
#endif
/* @} */
#endif
|
ksophocleous/speex
|
include/speex/speex_bits.h
|
C
|
bsd-3-clause
| 6,916 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class RemoveValueLoggable extends AbstractBFileLoggable {
protected long page;
protected short tid;
protected byte[] oldData;
protected int offset = 0;
protected int len;
/**
*
*
* @param page
* @param tid
* @param oldData
* @param offset
* @param len
* @param fileId
* @param transaction
*/
public RemoveValueLoggable(Txn transaction, byte fileId, long page, short tid, byte[] oldData, int offset, int len) {
super(BFile.LOG_REMOVE_VALUE, fileId, transaction);
this.page = page;
this.tid = tid;
this.oldData = oldData;
this.offset = offset;
this.len = len;
}
/**
* @param broker
* @param transactionId
*/
public RemoveValueLoggable(DBBroker broker, long transactionId) {
super(broker, transactionId);
}
public void write(ByteBuffer out) {
super.write(out);
out.putInt((int) page);
out.putShort(tid);
out.putShort((short) len);
out.put(oldData, offset, len);
}
public void read(ByteBuffer in) {
super.read(in);
page = in.getInt();
tid = in.getShort();
len = in.getShort();
oldData = new byte[len];
in.get(oldData);
}
public int getLogSize() {
return super.getLogSize() + len + 8;
}
public void redo() throws LogException {
getIndexFile().redoRemoveValue(this);
}
public void undo() throws LogException {
getIndexFile().undoRemoveValue(this);
}
public String dump() {
return super.dump() + " - remove value with tid " + tid + " from page " + page;
}
}
|
NCIP/cadsr-cgmdr-nci-uk
|
src/org/exist/storage/index/RemoveValueLoggable.java
|
Java
|
bsd-3-clause
| 3,088 |
/*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@generated from sparse-iter/control/magma_zutil_sparse.cpp, normal z -> s, Tue Aug 30 09:38:47 2016
@author Hartwig Anzt
Utilities for testing MAGMA-sparse.
*/
#include <cuda_runtime_api.h>
#include "magmasparse_internal.h"
#define PRECISION_s
// --------------------
static const char *usage_sparse_short =
"%% Usage: %s [options] [-h|--help] matrices\n\n";
static const char *usage_sparse =
"Options are:\n"
" --solver Possibility to choose a solver:\n"
" CG, PCG, BICGSTAB, PBICGSTAB, GMRES, PGMRES, LOBPCG, JACOBI,\n"
" BAITER, IDR, PIDR, CGS, PCGS, TFQMR, PTFQMR, QMR, PQMR, BICG,\n"
" PBICG, BOMBARDMENT, ITERREF.\n"
" --basic Use non-optimized version\n"
" --ev x For eigensolvers, set number of eigenvalues/eigenvectors to compute.\n"
" --restart For GMRES: possibility to choose the restart.\n"
" For IDR: Number of distinct subspaces (1,2,4,8).\n"
" --atol x Set an absolute residual stopping criterion.\n"
" --verbose x Possibility to print intermediate residuals every x iteration.\n"
" --maxiter x Set an upper limit for the iteration count.\n"
" --rtol x Set a relative residual stopping criterion.\n"
" --format Possibility to choose a format for the sparse matrix:\n"
" CSR, ELL, SELLP, CUSPARSECSR\n"
" --blocksize x Set a specific blocksize for SELL-P format.\n"
" --alignment x Set a specific alignment for SELL-P format.\n"
" --mscale Possibility to scale the original matrix:\n"
" NOSCALE no scaling\n"
" UNITDIAG symmetric scaling to unit diagonal\n"
" --precond x Possibility to choose a preconditioner:\n"
" CG, BICGSTAB, GMRES, LOBPCG, JACOBI,\n"
" BAITER, IDR, CGS, TFQMR, QMR, BICG\n"
" BOMBARDMENT, ITERREF, ILU, PARILU, PARILUT, NONE.\n"
" --patol atol Absolute residual stopping criterion for preconditioner.\n"
" --prtol rtol Relative residual stopping criterion for preconditioner.\n"
" --piters k Iteration count for iterative preconditioner.\n"
" --plevels k Number of ILU levels.\n"
" --triolver k Solver for triangular ILU factors: e.g. CUSOLVE, JACOBI, ISAI.\n"
" --ppattern k Pattern used for ISAI preconditioner.\n"
" --psweeps x Number of iterative ParILU sweeps.\n"
" --trisolver Possibility to choose a triangular solver for ILU preconditioning: e.g. JACOBI, ISAI.\n"
" --ppattern k Possibility to choose a pattern for the trisolver: ISAI(k) or Block Jacobi.\n"
" --piters k Number of preconditioner relaxation steps, e.g. for ISAI or (Block) Jacobi trisolver.\n"
" --patol x Set an absolute residual stopping criterion for the preconditioner.\n"
" Corresponds to the relative fill-in in PARILUT.\n"
" --prtol x Set a relative residual stopping criterion for the preconditioner.\n"
" Corresponds to the replacement ratio in PARILUT.\n";
/**
Purpose
-------
Parses input options for a solver
Arguments
---------
@param[in]
argc int
command line input
@param[in]
argv char**
command line input
@param[in,out]
opts magma_sopts *
magma solver options
@param[out]
matrices int
counter how many linear systems to process
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_saux
********************************************************************/
extern "C"
magma_int_t
magma_sparse_opts(
int argc,
char** argv,
magma_sopts *opts,
int *matrices,
magma_queue_t queue )
{
magma_int_t info = MAGMA_SUCCESS;
// fill in default values
opts->input_format = Magma_CSR;
opts->blocksize = 32;
opts->alignment = 1;
opts->output_format = Magma_CSR;
opts->input_location = Magma_CPU;
opts->output_location = Magma_CPU;
opts->scaling = Magma_NOSCALE;
#if defined(PRECISION_z) | defined(PRECISION_d)
opts->solver_par.atol = 1e-16;
opts->solver_par.rtol = 1e-10;
#else
opts->solver_par.atol = 1e-8;
opts->solver_par.rtol = 1e-5;
#endif
opts->solver_par.maxiter = 1000;
opts->solver_par.verbose = 0;
opts->solver_par.version = 0;
opts->solver_par.restart = 50;
opts->solver_par.num_eigenvalues = 0;
opts->precond_par.solver = Magma_NONE;
opts->precond_par.trisolver = Magma_CUSOLVE;
#if defined(PRECISION_z) | defined(PRECISION_d)
opts->precond_par.atol = 1e-16;
opts->precond_par.rtol = 1e-10;
#else
opts->precond_par.atol = 0;
opts->precond_par.rtol = 1e-5;
#endif
opts->precond_par.maxiter = 100;
opts->precond_par.restart = 10;
opts->precond_par.levels = 0;
opts->precond_par.sweeps = 5;
opts->precond_par.maxiter = 1;
opts->precond_par.pattern = 1;
opts->solver_par.solver = Magma_CGMERGE;
printf( usage_sparse_short, argv[0] );
int ndevices;
cudaGetDeviceCount( &ndevices );
int basic = 0;
for( int i = 1; i < argc; ++i ) {
if ( strcmp("--format", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CSR", argv[i]) == 0 ) {
opts->output_format = Magma_CSR;
} else if ( strcmp("ELL", argv[i]) == 0 ) {
opts->output_format = Magma_ELL;
} else if ( strcmp("SELLP", argv[i]) == 0 ) {
opts->output_format = Magma_SELLP;
} else if ( strcmp("CUSPARSECSR", argv[i]) == 0 ) {
opts->output_format = Magma_CUCSR;
} else {
printf( "%%error: invalid format, use default (CSR).\n" );
}
} else if ( strcmp("--mscale", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("NOSCALE", argv[i]) == 0 ) {
opts->scaling = Magma_NOSCALE;
}
else if ( strcmp("UNITDIAG", argv[i]) == 0 ) {
opts->scaling = Magma_UNITDIAG;
}
else if ( strcmp("UNITROW", argv[i]) == 0 ) {
opts->scaling = Magma_UNITROW;
}
else {
printf( "%%error: invalid scaling, use default.\n" );
}
} else if ( strcmp("--solver", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_CGMERGE;
}
else if ( strcmp("PCG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PCGMERGE;
}
else if ( strcmp("BICG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BICG;
}
else if ( strcmp("PBICG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PBICG;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BICGSTABMERGE;
}
else if ( strcmp("PBICGSTAB", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PBICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_QMRMERGE;
}
else if ( strcmp("PQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PQMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_TFQMRMERGE;
}
else if ( strcmp("PTFQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PTFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_GMRES;
}
else if ( strcmp("PGMRES", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PGMRES;
}
else if ( strcmp("LOBPCG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_LOBPCG;
}
else if ( strcmp("LSQR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_LSQR;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_IDRMERGE;
}
else if ( strcmp("PIDR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PIDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_CGSMERGE;
}
else if ( strcmp("PCGS", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PCGSMERGE;
}
else if ( strcmp("BOMBARDMENT", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BOMBARDMERGE;
}
else if ( strcmp("ITERREF", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_ITERREF;
}
else {
printf( "%%error: invalid solver.\n" );
}
} else if ( strcmp("--restart", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.restart = atoi( argv[++i] );
} else if ( strcmp("--precond", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CGMERGE;
}
else if ( strcmp("PCG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PCG;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_QMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_TFQMRMERGE;
}
else if ( strcmp("PTFQMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PTFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_GMRES;
}
else if ( strcmp("PGMRES", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PGMRES;
}
else if ( strcmp("LOBPCG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_LOBPCG;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_IDRMERGE;
}
else if ( strcmp("PIDR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PIDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CGSMERGE;
}
else if ( strcmp("PCGS", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PCGSMERGE;
}
else if ( strcmp("BOMBARDMENT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BOMBARD;
}
else if ( strcmp("ITERREF", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ITERREF;
}
else if ( strcmp("ILU", argv[i]) == 0 || strcmp("IC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ILU;
}
else if ( strcmp("PARILU", argv[i]) == 0 || strcmp("AIC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARILU;
}
else if ( strcmp("PARICT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARICT;
}
else if ( strcmp("PARILUT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARILUT;
}
else if ( strcmp("CUSTOMIC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CUSTOMIC;
}
else if ( strcmp("CUSTOMILU", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CUSTOMILU;
}
else if ( strcmp("ISAI", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ISAI;
}
else if ( strcmp("NONE", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_NONE;
}
else {
printf( "%%error: invalid preconditioner.\n" );
}
} else if ( strcmp("--trisolver", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CGMERGE;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_QMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_TFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_GMRES;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_IDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CGSMERGE;
}
else if ( strcmp("CUSOLVE", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CUSOLVE;
}
else if ( strcmp("ISAI", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_ISAI;
}
else if ( strcmp("NONE", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_NONE;
}
else {
printf( "%%error: invalid trisolver.\n" );
}
} else if ( strcmp("--basic", argv[i]) == 0 && i+1 < argc ) {
basic = 1;
} else if ( strcmp("--prestart", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.restart = atoi( argv[++i] );
} else if ( strcmp("--patol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->precond_par.atol );
}else if ( strcmp("--prtol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->precond_par.rtol );
} else if ( strcmp("--piters", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.maxiter = atoi( argv[++i] );
} else if ( strcmp("--ppattern", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.pattern = atoi( argv[++i] );
} else if ( strcmp("--psweeps", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.sweeps = atoi( argv[++i] );
} else if ( strcmp("--plevels", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.levels = atoi( argv[++i] );
} else if ( strcmp("--blocksize", argv[i]) == 0 && i+1 < argc ) {
opts->blocksize = atoi( argv[++i] );
} else if ( strcmp("--alignment", argv[i]) == 0 && i+1 < argc ) {
opts->alignment = atoi( argv[++i] );
} else if ( strcmp("--verbose", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.verbose = atoi( argv[++i] );
} else if ( strcmp("--maxiter", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.maxiter = atoi( argv[++i] );
} else if ( strcmp("--atol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->solver_par.atol );
} else if ( strcmp("--rtol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->solver_par.rtol );
} else if ( strcmp("--ev", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.num_eigenvalues = atoi( argv[++i] );
} else if ( strcmp("--version", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.version = atoi( argv[++i] );
}
// ----- usage
else if ( strcmp("-h", argv[i]) == 0 ||
strcmp("--help", argv[i]) == 0 ) {
fprintf( stderr, usage_sparse, argv[0] );
} else {
*matrices = i;
break;
}
}
if( basic == 1 ){
if ( opts->solver_par.solver == Magma_CGMERGE ) {
opts->solver_par.solver = Magma_CG;
}
else if ( opts->solver_par.solver == Magma_PCGMERGE) {
opts->solver_par.solver = Magma_PCG;
}
else if ( opts->solver_par.solver == Magma_BICGSTABMERGE ) {
opts->solver_par.solver = Magma_BICGSTAB;
}
else if ( opts->solver_par.solver == Magma_PBICGSTAB ) {
opts->solver_par.solver = Magma_PBICGSTAB;
}
else if ( opts->solver_par.solver == Magma_TFQMRMERGE ) {
opts->solver_par.solver = Magma_TFQMR;
}
else if ( opts->solver_par.solver == Magma_PTFQMRMERGE) {
opts->solver_par.solver = Magma_PTFQMR;
}
else if ( opts->solver_par.solver == Magma_CGSMERGE ) {
opts->solver_par.solver = Magma_CGS;
}
else if ( opts->solver_par.solver == Magma_PCGSMERGE) {
opts->solver_par.solver = Magma_PCGS;
}
else if ( opts->solver_par.solver == Magma_QMRMERGE ) {
opts->solver_par.solver = Magma_QMR;
}
else if ( opts->solver_par.solver == Magma_PQMRMERGE) {
opts->solver_par.solver = Magma_PQMR;
}
else if ( opts->solver_par.solver == Magma_QMRMERGE ) {
opts->solver_par.solver = Magma_QMR;
}
else if ( opts->solver_par.solver == Magma_PCGMERGE) {
opts->solver_par.solver = Magma_PCG;
}
else if ( opts->solver_par.solver == Magma_IDRMERGE) {
opts->solver_par.solver = Magma_IDR;
}
else if ( opts->solver_par.solver == Magma_PIDRMERGE) {
opts->solver_par.solver = Magma_PIDR;
}
else if ( opts->solver_par.solver == Magma_BOMBARDMERGE) {
opts->solver_par.solver = Magma_BOMBARD;
}
}
// make sure preconditioner is NONE for unpreconditioned systems
if ( opts->solver_par.solver != Magma_PCG &&
opts->solver_par.solver != Magma_PCGMERGE &&
opts->solver_par.solver != Magma_PGMRES &&
opts->solver_par.solver != Magma_PBICGSTAB &&
opts->solver_par.solver != Magma_PBICGSTABMERGE &&
opts->solver_par.solver != Magma_ITERREF &&
opts->solver_par.solver != Magma_PIDR &&
opts->solver_par.solver != Magma_PIDRMERGE &&
opts->solver_par.solver != Magma_PCGS &&
opts->solver_par.solver != Magma_PCGSMERGE &&
opts->solver_par.solver != Magma_PTFQMR &&
opts->solver_par.solver != Magma_PQMRMERGE &&
opts->solver_par.solver != Magma_PTFQMRMERGE &&
opts->solver_par.solver != Magma_PQMR &&
opts->solver_par.solver != Magma_PBICG &&
opts->solver_par.solver != Magma_LSQR &&
opts->solver_par.solver != Magma_LOBPCG ){
opts->precond_par.solver = Magma_NONE;
}
// ensure to take a symmetric preconditioner for the PCG
if ( ( opts->solver_par.solver == Magma_PCG || opts->solver_par.solver == Magma_PCGMERGE )
&& opts->precond_par.solver == Magma_ILU )
opts->precond_par.solver = Magma_ICC;
if ( ( opts->solver_par.solver == Magma_PCG || opts->solver_par.solver == Magma_PCGMERGE )
&& opts->precond_par.solver == Magma_PARILU )
opts->precond_par.solver = Magma_PARIC;
return info;
}
|
maxhutch/magma
|
sparse-iter/control/magma_sutil_sparse.cpp
|
C++
|
bsd-3-clause
| 21,167 |
#!/usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use JSON::PP;
my $base = "http://gameai.skullspace.ca/api/";
sub failure {
print("!! " . shift(@_) . "\n");
exit(1);
}
sub info {
print("** " . shift(@_) . "\n");
}
sub parse_card {
my $abbr = shift(@_);
my %card = ("abbr" => $abbr);
my $suit = substr($abbr, 0, 1);
if ($suit eq "C") {
$card{"suit"} = "CLUBS";
}
elsif ($suit eq "D") {
$card{"suit"} = "DIAMONDS";
}
elsif ($suit eq "H") {
$card{"suit"} = "HEARTS";
}
else {
$card{"suit"} = "SPADES";
}
$card{"value"} = int(substr($abbr, 1, 2));
return %card;
}
sub rawapi {
my $method = shift(@_);
my (%params) = @_;
# Collect parameters into a JSON object.
my $json = JSON::PP->new;
my $json_params = $json->encode(\%params);
# Create the URL of the endpoint.
my $url = $base . $method . "/";
# Create a new HTTP request to the endpoint.
my $req = HTTP::Request->new(POST => $url);
# Set up the HTTP request's properties.
$req->header("Content-type" => "application/json");
# Set the HTTP request's body.
$req->content($json_params);
# Send the HTTP request.
my $con = LWP::UserAgent->new;
my $res = $con->request($req);
# Check for errors.
if (!$res->is_success) {
failure("An unknown error occurred during the API call.");
}
# Read the HTTP response code.
if ($res->code != 200) {
failure("The server responded with a status code other than 200.");
}
# Read the HTTP response body.
return $json->decode($res->decoded_content);
}
sub api {
my $method = shift(@_);
my (%params) = @_;
my $json = rawapi($method, %params);
if ($json->{"result"} eq "failure") {
failure($json->{"reason"});
}
return $json;
}
sub main {
my (@argv) = @_;
# Ensure we've been given a name and a password.
my $name;
my $pass;
if (@argv != 2) {
print("Enter your bot's name: ");
$name = <STDIN>;
chomp($name);
print("Enter your bot's password: ");
$pass = <STDIN>;
chomp($pass);
}
else {
$name = $argv[0];
$pass = $argv[1];
}
# Register the name, which will have no effect if you've already done it.
rawapi("register", ("name" => $name, "password" => $pass));
# Login with the name and password.
info("Logging in to the server...");
my $json = api("login", ("name" => $name, "password" => $pass));
info("Logged in.");
# Store the session from the login for future use.
my $session = $json->{"session"};
info("Received session '$session'.");
while (1) {
# Ask to be given an opponent to play against.
info("Attempting to start a new game...");
$json = api("new-game", ("session" => $session));
# If there's nobody to play against, start the loop from the top after
# waiting 5 seconds.
if ($json->{"result"} eq "retry") {
print("?? " . $json->{"reason"} . "\n");
sleep(5);
next;
}
# Create an object to represent the cards we have been dealt.
my @cards = @{$json->{"cards"}};
info("We have started a new game, and have been dealt: " . join(", ", @cards) . ".");
# Run the game AI.
new_game($session, @cards);
# Cleanup from our game.
info("Our role in this game is over, but we need to be sure the server has ended the game before we start a new one.");
info("If we try to start a new game without the old one being done, the server will reject our request.");
while (1) {
info("Waiting for our game to be over...");
$json = api("status", ("session" => $session));
if (!defined $json->{"game"}) {
last;
}
sleep(1);
}
info("The server has ended our game.");
}
}
sub new_game {
my $session = shift(@_);
my @hand = @_;
# Make a bid, which we'll do randomly, by choosing a number between 1 and
# 13.
my $bid = int(1 + rand(13));
# Register our bid with the server.
info("Attempting to bid " . $bid . ".");
api("bid", ("session" => $session, "bid" => $bid));
info("Our bid has been accepted.");
# Check the status repeatedly, and if it's our turn play a card, until all
# cards have been played and the game ends.
while (@hand) {
# Always wait 1 second, it may not seem like much but it helps avoid
# pinning the client's CPU and flooding the server.
sleep(1);
# Request the game's status from the server.
info("Requesting the status of our game...");
my $json = api("status", ("session" => $session));
info("Status received.");
# If the game has ended prematurely, due to a forfeit from your opponent
# or some other reason, rejoice and find a new opponent.
if (!defined $json->{"game"}) {
info("Our game appears to have ended.");
return;
}
# If we're still in the bidding process, it's nobody's turn.
if (!defined $json->{"your-turn"}) {
info("Our game is still in the bidding phase, we need to wait for our opponent.");
next;
}
# If not it's not our turn yet, jump back to the top of the loop to
# check the status again.
if (not $json->{"your-turn"}) {
info("It is currently our opponent's turn, we need to wait for our opponent.");
next;
}
# Finally, it's our turn. First, we have to determine if another card
# was played first in this round. If so, it restricts our choices.
my @allowed_cards;
if (!defined $json->{"opponent-current-card"}) {
# We can play any card we want, since we're going first in this
# round. So all the cards in our hand are allowed.
@allowed_cards = @hand;
info("We have the lead this round, so we may choose any card.");
}
else {
# We can only play cards that match the suit of the lead card, since
# we're going second in this round. Gather together all the cards in
# our hand that have the appropriate suit.
@allowed_cards = ();
my %lead_card = parse_card($json->{"opponent-current-card"});
info("Our opponent has lead this round, so we must try to play a card that matches the lead card's suit: " . $lead_card{"suit"} . ".");
foreach my $card (@hand) {
my %card = parse_card($card);
if ($card{"suit"} eq $lead_card{"suit"}) {
push(@allowed_cards, $card{"abbr"});
}
}
# Check if we actually found any cards in our hand with the
# appropriate suit. If we don't have any, there are no restrictions
# on the card we can then play.
if (!@allowed_cards) {
info("We have no " . $lead_card{"suit"} . " in our hand, so we can play any suit we choose.");
@allowed_cards = @hand;
}
}
# Among the cards that we have determined are valid, according to the
# rules, choose one to play at random.
my $idx = int(rand(@allowed_cards));
my $card = $allowed_cards[$idx];
info("We have randomly chosen " . $card . ".");
# Now that the card has been chosen, play it.
info("Attempting to play " . $card . "...");
api("play", ("session" => $session, "card" => $card));
info("Card has been played.");
# Remove the card from our hand.
my @new_hand = ();
foreach my $card_in_hand (@hand) {
if ($card_in_hand ne $card) {
push(@new_hand, $card_in_hand);
}
}
@hand = @new_hand;
}
}
main(@ARGV);
|
mogigoma/gameai-2014-09
|
sdk/perl/GameAI.pl
|
Perl
|
bsd-3-clause
| 8,313 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.robust.robust_linear_model.RLMResults.pvalues — statsmodels v0.10.2 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.robust.robust_linear_model.RLMResults.remove_data" href="statsmodels.robust.robust_linear_model.RLMResults.remove_data.html" />
<link rel="prev" title="statsmodels.robust.robust_linear_model.RLMResults.predict" href="statsmodels.robust.robust_linear_model.RLMResults.predict.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.robust.robust_linear_model.RLMResults.remove_data.html" title="statsmodels.robust.robust_linear_model.RLMResults.remove_data"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.robust.robust_linear_model.RLMResults.predict.html" title="statsmodels.robust.robust_linear_model.RLMResults.predict"
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="../rlm.html" >Robust Linear Models</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.robust.robust_linear_model.RLMResults.html" accesskey="U">statsmodels.robust.robust_linear_model.RLMResults</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-robust-robust-linear-model-rlmresults-pvalues">
<h1>statsmodels.robust.robust_linear_model.RLMResults.pvalues<a class="headerlink" href="#statsmodels-robust-robust-linear-model-rlmresults-pvalues" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.robust.robust_linear_model.RLMResults.pvalues">
<code class="sig-prename descclassname">RLMResults.</code><code class="sig-name descname">pvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/robust/robust_linear_model.html#RLMResults.pvalues"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.robust.robust_linear_model.RLMResults.pvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>The two-tailed p values for the t-stats of the params.</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.robust.robust_linear_model.RLMResults.predict.html"
title="previous chapter">statsmodels.robust.robust_linear_model.RLMResults.predict</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.robust.robust_linear_model.RLMResults.remove_data.html"
title="next chapter">statsmodels.robust.robust_linear_model.RLMResults.remove_data</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.robust.robust_linear_model.RLMResults.pvalues.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.2.1.
</div>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.10.2/generated/statsmodels.robust.robust_linear_model.RLMResults.pvalues.html
|
HTML
|
bsd-3-clause
| 7,703 |
// $Id$
//
// Copyright (C) 2007-2013 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <boost/cstdint.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
namespace RDKit {
namespace AtomPairs {
unsigned int numPiElectrons(const Atom *atom) {
PRECONDITION(atom, "no atom");
unsigned int res = 0;
if (atom->getIsAromatic()) {
res = 1;
} else if (atom->getHybridization() != Atom::SP3) {
unsigned int val = static_cast<unsigned int>(atom->getExplicitValence());
val -= atom->getNumExplicitHs();
CHECK_INVARIANT(val >= atom->getDegree(),
"explicit valence exceeds atom degree");
res = val - atom->getDegree();
}
return res;
}
boost::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract,
bool includeChirality) {
PRECONDITION(atom, "no atom");
boost::uint32_t code;
unsigned int numBranches = 0;
if (atom->getDegree() > branchSubtract) {
numBranches = atom->getDegree() - branchSubtract;
}
code = numBranches % maxNumBranches;
unsigned int nPi = numPiElectrons(atom) % maxNumPi;
code |= nPi << numBranchBits;
unsigned int typeIdx = 0;
unsigned int nTypes = 1 << numTypeBits;
while (typeIdx < nTypes) {
if (atomNumberTypes[typeIdx] ==
static_cast<unsigned int>(atom->getAtomicNum())) {
break;
} else if (atomNumberTypes[typeIdx] >
static_cast<unsigned int>(atom->getAtomicNum())) {
typeIdx = nTypes;
break;
}
++typeIdx;
}
if (typeIdx == nTypes) --typeIdx;
code |= typeIdx << (numBranchBits + numPiBits);
if (includeChirality) {
std::string cipCode;
if (atom->getPropIfPresent(common_properties::_CIPCode, cipCode)) {
boost::uint32_t offset = numBranchBits + numPiBits + numTypeBits;
if (cipCode == "R") {
code |= 1 << offset;
} else if (cipCode == "S") {
code |= 2 << offset;
}
}
}
POSTCONDITION(code < (1 << (codeSize + (includeChirality ? 2 : 0))),
"code exceeds number of bits");
return code;
};
boost::uint32_t getAtomPairCode(boost::uint32_t codeI, boost::uint32_t codeJ,
unsigned int dist, bool includeChirality) {
PRECONDITION(dist < maxPathLen, "dist too long");
boost::uint32_t res = dist;
res |= std::min(codeI, codeJ) << numPathBits;
res |= std::max(codeI, codeJ)
<< (numPathBits + codeSize + (includeChirality ? numChiralBits : 0));
return res;
}
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(boost::uint32_t i, boost::uint32_t j,
boost::uint32_t nAtoms,
const std::vector<boost::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
unsigned int dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<boost::uint32_t>(bitId));
}
}
SparseIntVect<boost::int32_t> *getAtomPairFingerprint(
const ROMol &mol, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<boost::int32_t> *getAtomPairFingerprint(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(
1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<boost::int32_t> *getHashedAtomPairFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(nBits);
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int32_t> *sres = getHashedAtomPairFingerprint(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
boost::uint64_t getTopologicalTorsionCode(
const std::vector<boost::uint32_t> &pathCodes, bool includeChirality) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
int shiftSize = codeSize + (includeChirality ? numChiralBits : 0);
boost::uint64_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[pathCodes.size() - i - 1])
<< (shiftSize * i);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[i]) << (shiftSize * i);
}
}
return res;
}
size_t getTopologicalTorsionHash(
const std::vector<boost::uint32_t> &pathCodes) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
boost::uint32_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[pathCodes.size() - i - 1]);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[i]);
}
}
return res;
}
SparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
//
// mmm, bug compatible.
sz -= 1;
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(mol.getNumAtoms());
PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<boost::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (PATH_TYPE::const_iterator pIt = path.begin(); pIt < path.end();
++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
getTopologicalTorsionCode(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<boost::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = getTopologicalTorsionHash(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // end of local namespace
SparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int64_t> *sres =
new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
|
adalke/rdkit
|
Code/GraphMol/Fingerprints/AtomPairs.cpp
|
C++
|
bsd-3-clause
| 21,277 |
---
id: 5900f3bc1000cf542c50fecf
title: 'Problema 80: Expansão de algarismos da raiz quadrada'
challengeType: 5
forumTopicId: 302194
dashedName: problem-80-square-root-digital-expansion
---
# --description--
É do conhecimento geral que se a raiz quadrada de um número natural não é um número inteiro, então é irracional. A expansão decimal de tais raízes quadradas é infinita sem qualquer tipo de padrão de repetição.
A raiz quadrada de dois é `1.41421356237309504880...`. A soma dos algarismos das primeiras cem casas decimais é `475`.
Para os primeiros `n` números naturais, encontre o total das somas dos algarismos das primeiras cem casas decimais para todas as raízes quadradas irracionais.
# --hints--
`sqrtDigitalExpansion(2)` deve retornar um número.
```js
assert(typeof sqrtDigitalExpansion(2) === 'number');
```
`sqrtDigitalExpansion(2)` deve retornar `475`.
```js
assert.strictEqual(sqrtDigitalExpansion(2), 475);
```
`sqrtDigitalExpansion(50)` deve retornar `19543`.
```js
assert.strictEqual(sqrtDigitalExpansion(50), 19543);
```
`sqrtDigitalExpansion(100)` deve retornar `40886`.
```js
assert.strictEqual(sqrtDigitalExpansion(100), 40886);
```
# --seed--
## --seed-contents--
```js
function sqrtDigitalExpansion(n) {
return true;
}
sqrtDigitalExpansion(2);
```
# --solutions--
```js
function sqrtDigitalExpansion(n) {
function sumDigits(number) {
let sum = 0;
while (number > 0n) {
let digit = number % 10n;
sum += parseInt(digit, 10);
number = number / 10n;
}
return sum;
}
function power(numberA, numberB) {
let result = 1n;
for (let b = 0; b < numberB; b++) {
result = result * BigInt(numberA);
}
return result;
}
// Based on http://www.afjarvis.staff.shef.ac.uk/maths/jarvisspec02.pdf
function expandSquareRoot(number, numDigits) {
let a = 5n * BigInt(number);
let b = 5n;
const boundaryWithNeededDigits = power(10, numDigits + 1);
while (b < boundaryWithNeededDigits) {
if (a >= b) {
a = a - b;
b = b + 10n;
} else {
a = a * 100n;
b = (b / 10n) * 100n + 5n;
}
}
return b / 100n;
}
let result = 0;
let nextPerfectRoot = 1;
const requiredDigits = 100;
for (let i = 1; i <= n; i++) {
if (nextPerfectRoot ** 2 === i) {
nextPerfectRoot++;
continue;
}
result += sumDigits(expandSquareRoot(i, requiredDigits));
}
return result;
}
```
|
FreeCodeCamp/FreeCodeCamp
|
curriculum/challenges/portuguese/10-coding-interview-prep/project-euler/problem-80-square-root-digital-expansion.md
|
Markdown
|
bsd-3-clause
| 2,471 |
/*
----------------------
BeDC License
----------------------
Copyright 2002, The BeDC team.
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 BeDC team 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 TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _DC_STRINGS_H_
#define _DC_STRINGS_H_
#include <String.h>
// String constants
enum
{
// Hub window
STR_HUB_WINDOW_TITLE = 0,
// Hub window -> Buttons
STR_HUB_CONNECT,
STR_HUB_REFRESH,
STR_HUB_NEXT50,
STR_HUB_PREV50,
// Hub window -> List view
STR_SERVER_NAME,
STR_SERVER_ADDR,
STR_SERVER_DESC,
STR_SERVER_USERS,
// Hub window -> Status
STR_STATUS_IDLE,
STR_STATUS_CONNECTING,
STR_STATUS_CONNECTED,
STR_STATUS_CONNECT_ERROR,
STR_STATUS_SEND_ERROR,
STR_STATUS_RECV_ERROR,
STR_STATUS_NUM_SERVERS,
// Main window -> Menus
STR_MENU_FILE,
STR_MENU_FILE_ABOUT,
STR_MENU_FILE_CLOSE,
STR_MENU_EDIT,
STR_MENU_EDIT_PREFS,
STR_MENU_WINDOWS,
STR_MENU_WINDOWS_HUB,
// Prefernces window
STR_PREFS_TITLE,
STR_PREFS_GENERAL,
STR_PREFS_GENERAL_PERSONAL,
STR_PREFS_GENERAL_CONNECTION_SETTINGS,
STR_PREFS_GENERAL_NICK,
STR_PREFS_GENERAL_EMAIL,
STR_PREFS_GENERAL_DESC,
STR_PREFS_GENERAL_CONNECTION,
STR_PREFS_GENERAL_ACTIVE,
STR_PREFS_GENERAL_PASSIVE,
STR_PREFS_GENERAL_IP,
STR_PREFS_GENERAL_PORT,
STR_PREFS_COLORS,
STR_PREFS_COLORS_SYSTEM,
STR_PREFS_COLORS_TEXT,
STR_PREFS_COLORS_ERROR,
STR_PREFS_COLORS_REMOTE_NICK,
STR_PREFS_COLORS_LOCAL_NICK,
STR_PREFS_COLORS_PRIVATE_TEXT,
// For the user list view
STR_VIEW_NAME = STR_SERVER_NAME, // Reuse ;)
STR_VIEW_SPEED = STR_PREFS_COLORS_PRIVATE_TEXT + 1,
STR_VIEW_DESC,
STR_VIEW_EMAIL,
STR_VIEW_SHARED,
STR_VIEW_CHAT,
STR_VIEW_CLOSE,
STR_OK,
STR_CANCEL,
STR_ERROR,
STR_USERS,
STR_LANGUAGE,
STR_REVERT,
STR_ALERT_BAD_NICK,
// Messages
STR_MSG_SYSTEM,
STR_MSG_ERROR,
STR_MSG_CONNECTING_TO,
STR_MSG_CONNECTED,
STR_MSG_CONNECT_ERROR,
STR_MSG_RECONNECTING,
STR_MSG_DISCONNECTED_FROM_SERVER,
STR_MSG_INVALID_NICK,
STR_MSG_USER_LOGGED_IN,
STR_MSG_USER_LOGGED_OUT,
STR_MSG_REDIRECTING,
STR_MSG_HUB_IS_FULL,
STR_MSG_USER_NOT_FOUND,
STR_MSG_UNKNOWN_COMMAND,
// This is a LONG string that contains the WHOLE /help text
STR_MSG_HELP,
STR_NUM // Place holder
};
// Key shortcuts for menu items
enum
{
KEY_FILE_ABOUT = 0,
KEY_FILE_CLOSE,
KEY_EDIT_PREFS,
KEY_WINDOWS_HUB,
KEY_NUM
};
enum
{
DC_LANG_ENGLISH = 0,
DC_LANG_SWEDISH,
DC_LANG_FINNISH,
DC_LANG_GERMAN,
DC_LANG_NORWEGIAN,
DC_LANG_POLISH,
DC_LANG_RUSSIAN,
DC_LANG_NUM // Place holder
};
extern const char * DC_LANGUAGES[DC_LANG_NUM];
const char * DCStr(int);
char DCKey(int);
void DCSetLanguage(int);
int DCGetLanguage();
BString DCUTF8(const char * str);
BString DCMS(const char * str);
#endif // _DC_STRINGS_H_
|
HaikuArchives/BeDC
|
source/DCStrings.h
|
C
|
bsd-3-clause
| 4,105 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Ldap
*/
namespace Zend\Ldap\Collection;
use Zend\Ldap;
use Zend\Ldap\Exception;
use Zend\Stdlib\ErrorHandler;
/**
* Zend\Ldap\Collection\DefaultIterator is the default collection iterator implementation
* using ext/ldap
*
* @category Zend
* @package Zend_Ldap
*/
class DefaultIterator implements \Iterator, \Countable
{
const ATTRIBUTE_TO_LOWER = 1;
const ATTRIBUTE_TO_UPPER = 2;
const ATTRIBUTE_NATIVE = 3;
/**
* LDAP Connection
*
* @var \Zend\Ldap\Ldap
*/
protected $ldap = null;
/**
* Result identifier resource
*
* @var resource
*/
protected $resultId = null;
/**
* Current result entry identifier
*
* @var resource
*/
protected $current = null;
/**
* Number of items in query result
*
* @var integer
*/
protected $itemCount = -1;
/**
* The method that will be applied to the attribute's names.
*
* @var integer|callable
*/
protected $attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
/**
* Constructor.
*
* @param \Zend\Ldap\Ldap $ldap
* @param resource $resultId
* @throws \Zend\Ldap\Exception\LdapException if no entries was found.
* @return DefaultIterator
*/
public function __construct(Ldap\Ldap $ldap, $resultId)
{
$this->ldap = $ldap;
$this->resultId = $resultId;
$resource = $ldap->getResource();
ErrorHandler::start();
$this->itemCount = ldap_count_entries($resource, $resultId);
ErrorHandler::stop();
if ($this->itemCount === false) {
throw new Exception\LdapException($this->ldap, 'counting entries');
}
}
public function __destruct()
{
$this->close();
}
/**
* Closes the current result set
*
* @return bool
*/
public function close()
{
$isClosed = false;
if (is_resource($this->resultId)) {
ErrorHandler::start();
$isClosed = ldap_free_result($this->resultId);
ErrorHandler::stop();
$this->resultId = null;
$this->current = null;
}
return $isClosed;
}
/**
* Gets the current LDAP connection.
*
* @return \Zend\Ldap\Ldap
*/
public function getLDAP()
{
return $this->ldap;
}
/**
* Sets the attribute name treatment.
*
* Can either be one of the following constants
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_LOWER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_UPPER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_NATIVE
* or a valid callback accepting the attribute's name as it's only
* argument and returning the new attribute's name.
*
* @param integer|callable $attributeNameTreatment
* @return DefaultIterator Provides a fluent interface
*/
public function setAttributeNameTreatment($attributeNameTreatment)
{
if (is_callable($attributeNameTreatment)) {
if (is_string($attributeNameTreatment) && !function_exists($attributeNameTreatment)) {
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
} elseif (is_array($attributeNameTreatment)
&& !method_exists($attributeNameTreatment[0], $attributeNameTreatment[1])
) {
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
} else {
$this->attributeNameTreatment = $attributeNameTreatment;
}
} else {
$attributeNameTreatment = (int)$attributeNameTreatment;
switch ($attributeNameTreatment) {
case self::ATTRIBUTE_TO_LOWER:
case self::ATTRIBUTE_TO_UPPER:
case self::ATTRIBUTE_NATIVE:
$this->attributeNameTreatment = $attributeNameTreatment;
break;
default:
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
break;
}
}
return $this;
}
/**
* Returns the currently set attribute name treatment
*
* @return integer|callable
*/
public function getAttributeNameTreatment()
{
return $this->attributeNameTreatment;
}
/**
* Returns the number of items in current result
* Implements Countable
*
* @return int
*/
public function count()
{
return $this->itemCount;
}
/**
* Return the current result item
* Implements Iterator
*
* @return array|null
* @throws \Zend\Ldap\Exception\LdapException
*/
public function current()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (!is_resource($this->current)) {
return null;
}
$entry = array('dn' => $this->key());
$ber_identifier = null;
$resource = $this->ldap->getResource();
ErrorHandler::start();
$name = ldap_first_attribute(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
while ($name) {
ErrorHandler::start();
$data = ldap_get_values_len($resource, $this->current, $name);
ErrorHandler::stop();
if (!$data) {
$data = array();
}
if (isset($data['count'])) {
unset($data['count']);
}
switch ($this->attributeNameTreatment) {
case self::ATTRIBUTE_TO_LOWER:
$attrName = strtolower($name);
break;
case self::ATTRIBUTE_TO_UPPER:
$attrName = strtoupper($name);
break;
case self::ATTRIBUTE_NATIVE:
$attrName = $name;
break;
default:
$attrName = call_user_func($this->attributeNameTreatment, $name);
break;
}
$entry[$attrName] = $data;
ErrorHandler::start();
$name = ldap_next_attribute(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
}
ksort($entry, SORT_LOCALE_STRING);
return $entry;
}
/**
* Return the result item key
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
* @return string|null
*/
public function key()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (is_resource($this->current)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$currentDn = ldap_get_dn($resource, $this->current);
ErrorHandler::stop();
if ($currentDn === false) {
throw new Exception\LdapException($this->ldap, 'getting dn');
}
return $currentDn;
} else {
return null;
}
}
/**
* Move forward to next result item
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function next()
{
$code = 0;
if (is_resource($this->current) && $this->itemCount > 0) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_next_entry($resource, $this->current);
ErrorHandler::stop();
if ($this->current === false) {
$msg = $this->ldap->getLastError($code);
if ($code === Exception\LdapException::LDAP_SIZELIMIT_EXCEEDED) {
// we have reached the size limit enforced by the server
return;
} elseif ($code > Exception\LdapException::LDAP_SUCCESS) {
throw new Exception\LdapException($this->ldap, 'getting next entry (' . $msg . ')');
}
}
} else {
$this->current = false;
}
}
/**
* Rewind the Iterator to the first result item
* Implements Iterator
*
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function rewind()
{
if (is_resource($this->resultId)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_first_entry($resource, $this->resultId);
ErrorHandler::stop();
if ($this->current === false
&& $this->ldap->getLastErrorCode() > Exception\LdapException::LDAP_SUCCESS
) {
throw new Exception\LdapException($this->ldap, 'getting first entry');
}
}
}
/**
* Check if there is a current result item
* after calls to rewind() or next()
* Implements Iterator
*
* @return boolean
*/
public function valid()
{
return (is_resource($this->current));
}
}
|
OtsList/OtsList.eu-AAC-for-OpenTibia
|
vendor/ZF2/library/Zend/Ldap/Collection/DefaultIterator.php
|
PHP
|
bsd-3-clause
| 9,869 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\HalfproductSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="halfproduct-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_product') ?>
<?= $form->field($model, 'kode') ?>
<?= $form->field($model, 'nama') ?>
<?= $form->field($model, 'package') ?>
<?= $form->field($model, 'panjang') ?>
<?php // echo $form->field($model, 'lebar') ?>
<?php // echo $form->field($model, 'berat') ?>
<?php // echo $form->field($model, 'flag') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
hendrihmwn/propensiA08
|
views/halfproduct/_search.php
|
PHP
|
bsd-3-clause
| 923 |
WakaTime#

[](https://ci.appveyor.com/project/salaros/wakatime-sharp/branch/master)

==========


[](https://social.msdn.microsoft.com/Forums/vstudio/en-US/7035edc6-97fc-49ee-8eee-2fa4d040a63b/)
[](https://social.msdn.microsoft.com/Forums/vstudio/en-US/7035edc6-97fc-49ee-8eee-2fa4d040a63b/)
A core implementation of all WakaTime C#-driven plugins for IDE such as Xamarin Studio, Monodevelop, Visual Studio, Visual Studio for Mac, Notepad++, Unity etc
These plugins will help to collect metrics, insights and time tracking automatically generated directly from your programming activity.
https://wakatime.com
|
CodeCavePro/wakatime-sharp
|
README.md
|
Markdown
|
bsd-3-clause
| 1,158 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioHurtHandler : MonoBehaviour {
// Static reference to singleton object
public static AudioHurtHandler instance;
public AudioClip[] myClip;
// Use this for initialization
void Start ()
{
instance = gameObject.GetComponent<AudioHurtHandler>();
}
public void playSound ()
{
audio.PlayOneShot(myClip[Random.Range(0,myClip.Length)]);
//wait ();
}
IEnumerator wait()
{
yield return new WaitForSeconds(1);
}
}
|
Socapex/polyGamesHackathon
|
Assets/Scripts/AudioHurtHandler.cs
|
C#
|
bsd-3-clause
| 533 |
<?php namespace estvoyage\risingsun\comparison\unary\container\payload;
use estvoyage\risingsun\{ container, comparison, ointeger, block };
class disjunction
implements
comparison\unary\container\payload
{
private
$operand,
$recipient
;
function __construct($operand, comparison\recipient $recipient)
{
$this->operand = $operand;
$this->recipient = $recipient;
}
function containerIteratorEngineControllerForUnaryComparisonAtPositionIs(comparison\unary $comparison, ointeger $position, container\iterator\engine\controller $controller)
{
$comparison
->recipientOfComparisonWithOperandIs(
$this->operand,
new comparison\recipient\block(
new block\functor(
function($nboolean) use ($controller)
{
$this->recipient->nbooleanIs($nboolean);
(new comparison\unary\with\true\boolean)
->recipientOfComparisonWithOperandIs(
$nboolean,
new comparison\recipient\functor\ok(
function() use ($controller)
{
$controller->remainingIterationsInContainerIteratorEngineAreUseless();
}
)
)
;
}
)
)
)
;
}
}
|
estvoyage/risingsun
|
src/comparison/unary/container/payload/disjunction.php
|
PHP
|
bsd-3-clause
| 1,166 |
<?php
namespace UForm\Form\Element;
use UForm\Filtering\FilterChain;
use UForm\Form\Element;
/**
* Element that intends to contain other elements.
* It only aims to be a common parent for Group and Collection
*
* In some ways it is opposed to the Primary element that cant contain other elements
*
* @see UForm\Form\Element\Container\Group
* @see UForm\Form\Element\Container\Collection
* @see UForm\Form\Element\Container\Primary
* @semanticType container
*/
abstract class Container extends Element
{
public function __construct($name = null)
{
parent::__construct($name);
$this->addSemanticType('container');
}
/**
* Get an element by its name
* @param $name
* @return Element
*/
abstract public function getElement($name);
/**
* Get the elements contained in this container.
* Values are required because a collection requires values to be generated
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return Element[] the elements contained in this container
*/
abstract public function getElements($values = null);
/**
* Get an element located directly in this element. There is an exception for unnamed elements :
* we will search inside directElements of unnamed elements
* @param string $name name of the element to get
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return null|Element|Container the element found or null if the element does not exist
*/
public function getDirectElement($name, $values = null)
{
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
return $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$element = $elm->getDirectElement($name);
if ($element) {
return $element;
}
}
}
return null;
}
/**
* Get direct elements with the given name
* @param $name
* @param null $values
* @return Element[]
*/
public function getDirectElements($name, $values = null)
{
$elements = [];
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
$elements[] = $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$elements += $elm->getDirectElements($name, $values);
}
}
return $elements;
}
/**
* check if this element contains at least one element that is an instance of the given type
* @param string $className the name of the class to search for
* @return bool true if the instance was found
*/
public function hasDirectElementInstance($className)
{
foreach ($this->getElements() as $el) {
if (is_a($el, $className)) {
return true;
}
}
return false;
}
/**
* Check if this element contains at least one element with the given semantic type
* @param string $type the type to search for
* @return bool true if the semantic type was found
*/
public function hasDirectElementSemanticType($type)
{
foreach ($this->getElements() as $el) {
if ($el->hasSemanticType($type)) {
return true;
}
}
return false;
}
public function prepareFilterChain(FilterChain $filterChain)
{
parent::prepareFilterChain($filterChain);
foreach ($this->getElements() as $v) {
$v->prepareFilterChain($filterChain);
}
}
/**
* @inheritdoc
*/
public function setParent(Container $parent)
{
$r = parent::setParent($parent);
foreach ($this->getElements() as $element) {
$element->refreshParent();
}
return $r;
}
}
|
gsouf/UForm
|
src/UForm/Form/Element/Container.php
|
PHP
|
bsd-3-clause
| 4,172 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 03 10:16:39 2013
@author: Grahesh
"""
import pandas
from qstkutil import DataAccess as da
import numpy as np
import math
import copy
import qstkutil.qsdateutil as du
import datetime as dt
import qstkutil.DataAccess as da
import qstkutil.tsutil as tsu
import qstkstudy.EventProfiler as ep
"""
Accepts a list of symbols along with start and end date
Returns the Event Matrix which is a pandas Datamatrix
Event matrix has the following structure :
|IBM |GOOG|XOM |MSFT| GS | JP |
(d1)|nan |nan | 1 |nan |nan | 1 |
(d2)|nan | 1 |nan |nan |nan |nan |
(d3)| 1 |nan | 1 |nan | 1 |nan |
(d4)|nan | 1 |nan | 1 |nan |nan |
...................................
...................................
Also, d1 = start date
nan = no information about any event.
1 = status bit(positively confirms the event occurence)
"""
# Get the data from the data store
storename = "NSEData" # get data from our daily prices source
# Available field names: open, close, high, low, close, actual_close, volume
closefield = "close"
volumefield = "volume"
window = 10
def getHalfYearEndDates(timestamps):
newTS=[]
tempYear=timestamps[0].year
flag=1
for x in range(0, len(timestamps)-1):
if(timestamps[x].year==tempYear):
if(timestamps[x].month==4 and flag==1):
newTS.append(timestamps[x-1])
flag=0
if(timestamps[x].month==10):
newTS.append(timestamps[x-1])
tempYear=timestamps[x].year+1
flag=1
return newTS
def findEvents(symbols, startday,endday, marketSymbol,verbose=False):
# Reading the Data for the list of Symbols.
timeofday=dt.timedelta(hours=16)
timestamps = du.getNSEdays(startday,endday,timeofday)
endOfHalfYear=getHalfYearEndDates(timestamps)
dataobj = da.DataAccess('NSEData')
if verbose:
print __name__ + " reading data"
# Reading the Data
close = dataobj.get_data(timestamps, symbols, closefield)
# Completing the Data - Removing the NaN values from the Matrix
close = (close.fillna(method='ffill')).fillna(method='backfill')
# Calculating Daily Returns for the Market
tsu.returnize0(close.values)
# Calculating the Returns of the Stock Relative to the Market
# So if a Stock went up 5% and the Market rised 3%. The the return relative to market is 2%
mktneutDM = close - close[marketSymbol]
np_eventmat = copy.deepcopy(mktneutDM)
for sym in symbols:
for time in timestamps:
np_eventmat[sym][time]=np.NAN
if verbose:
print __name__ + " finding events"
# Generating the Event Matrix
# Event described is : Analyzing half year events for given stocks.
for symbol in symbols:
for i in endOfHalfYear:
np_eventmat[symbol][i] = 1.0 #overwriting by the bit, marking the event
return np_eventmat
#################################################
################ MAIN CODE ######################
#################################################
symbols = np.loadtxt('NSE500port.csv',dtype='S13',comments='#', skiprows=1)
# You might get a message about some files being missing, don't worry about it.
#symbols =['SPY','BFRE','ATCS','RSERF','GDNEF','LAST','ATTUF','JBFCF','CYVA','SPF','XPO','EHECF','TEMO','AOLS','CSNT','REMI','GLRP','AIFLY','BEE','DJRT','CHSTF','AICAF']
#symbols=['NSE','3MINDIA.NS','AARTIIND.NS','ABAN.NS','ABB.NS','ABGSHIP.NS','ABIRLANUV.NS','ACC.NS','ADANIENT.NS','ADANIPORT.NS','ADANIPOWE.NS','ADVANTA.NS','ALLCARGO.NS','AIAENG.NS','AIL.NS','AZKOINDIA.NS']
startday = dt.datetime(2011,1,1)
endday = dt.datetime(2012,1,1)
eventMatrix = findEvents(symbols,startday,endday,marketSymbol='NSE500',verbose=True)
eventMatrix.to_csv('eventmatrix.csv', sep=',')
eventProfiler = ep.EventProfiler(eventMatrix,startday,endday,lookback_days=20,lookforward_days=20,verbose=True)
eventProfiler.study(filename="HalfYearEventStudy.jpg",plotErrorBars=True,plotMarketNeutral=True,plotEvents=False,marketSymbol='NSE500')
|
grahesh/Stock-Market-Event-Analysis
|
Examples/Event Analysis/Half-Yearly End/Half_Year_End_Analysis.py
|
Python
|
bsd-3-clause
| 4,522 |
<?php
include_once 'dynamic_db_connection.php';
/**
* This is the model class for table "THEME_MANAGEMENT".
*
* The followings are the available columns in table 'THEME_MANAGEMENT':
* @property string $PID
* @property string $THEME
*/
class Theme_Management extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Theme_Management the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'THEME_MANAGEMENT';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('THEME', 'length', 'max'=>20),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('USER_ID,ID, THEME', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'USER_ID' => 'Userid',
'THEME' => 'Theme',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('USER_ID',$this->USER_ID,true);
$criteria->compare('THEME',$this->THEME,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
|
Rathilesh/FMS_V1
|
protected/models/Theme_Management.php
|
PHP
|
bsd-3-clause
| 2,079 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pypush2.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pypush2.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/pypush2"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pypush2"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
jonathonw/pypush2
|
docs/Makefile
|
Makefile
|
bsd-3-clause
| 7,669 |
/*
* Copyright (c) 2012 The Native Client 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 "native_client/src/include/portability_string.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_platform.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/trusted/service_runtime/nacl_syscall_asm_symbols.h"
#include "native_client/src/trusted/service_runtime/nacl_globals.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/service_runtime/sel_memory.h"
#include "native_client/src/trusted/service_runtime/springboard.h"
#include "native_client/src/trusted/service_runtime/arch/x86/sel_ldr_x86.h"
#include "native_client/src/trusted/service_runtime/arch/x86_64/tramp_64.h"
static uintptr_t AddDispatchThunk(uintptr_t *next_addr,
uintptr_t target_routine) {
struct NaClPatchInfo patch_info;
struct NaClPatch jmp_target;
jmp_target.target = (((uintptr_t) &NaClDispatchThunk_jmp_target)
- sizeof(uintptr_t));
jmp_target.value = target_routine;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &jmp_target;
patch_info.num_abs64 = 1;
patch_info.dst = *next_addr;
patch_info.src = (uintptr_t) &NaClDispatchThunk;
patch_info.nbytes = ((uintptr_t) &NaClDispatchThunkEnd
- (uintptr_t) &NaClDispatchThunk);
NaClApplyPatchToMemory(&patch_info);
*next_addr += patch_info.nbytes;
return patch_info.dst;
}
int NaClMakeDispatchThunk(struct NaClApp *nap) {
int retval = 0; /* fail */
int error;
void *thunk_addr = NULL;
uintptr_t next_addr;
uintptr_t dispatch_thunk = 0;
uintptr_t get_tls_fast_path1 = 0;
uintptr_t get_tls_fast_path2 = 0;
NaClLog(2, "Entered NaClMakeDispatchThunk\n");
if (0 != nap->dispatch_thunk) {
NaClLog(LOG_ERROR, " dispatch_thunk already initialized!\n");
return 1;
}
if (0 != (error = NaCl_page_alloc_randomized(&thunk_addr,
NACL_MAP_PAGESIZE))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_page_alloc failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
NaClLog(2, "NaClMakeDispatchThunk: got addr 0x%"NACL_PRIxPTR"\n",
(uintptr_t) thunk_addr);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_READ | PROT_WRITE))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_mprotect r/w failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
NaClFillMemoryRegionWithHalt(thunk_addr, NACL_MAP_PAGESIZE);
next_addr = (uintptr_t) thunk_addr;
dispatch_thunk =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClSyscallSeg);
get_tls_fast_path1 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath1);
get_tls_fast_path2 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath2);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_EXEC|PROT_READ))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_mprotect r/x failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
retval = 1;
cleanup:
if (0 == retval) {
if (NULL != thunk_addr) {
NaCl_page_free(thunk_addr, NACL_MAP_PAGESIZE);
thunk_addr = NULL;
}
} else {
nap->dispatch_thunk = dispatch_thunk;
nap->get_tls_fast_path1 = get_tls_fast_path1;
nap->get_tls_fast_path2 = get_tls_fast_path2;
}
return retval;
}
/*
* Install a syscall trampoline at target_addr. NB: Thread-safe.
*/
void NaClPatchOneTrampolineCall(uintptr_t call_target_addr,
uintptr_t target_addr) {
struct NaClPatchInfo patch_info;
struct NaClPatch call_target;
NaClLog(6, "call_target_addr = 0x%"NACL_PRIxPTR"\n", call_target_addr);
CHECK(0 != call_target_addr);
call_target.target = (((uintptr_t) &NaCl_trampoline_call_target)
- sizeof(uintptr_t));
call_target.value = call_target_addr;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &call_target;
patch_info.num_abs64 = 1;
patch_info.dst = target_addr;
patch_info.src = (uintptr_t) &NaCl_trampoline_code;
patch_info.nbytes = ((uintptr_t) &NaCl_trampoline_code_end
- (uintptr_t) &NaCl_trampoline_code);
NaClApplyPatchToMemory(&patch_info);
}
void NaClPatchOneTrampoline(struct NaClApp *nap,
uintptr_t target_addr) {
uintptr_t call_target_addr;
call_target_addr = nap->dispatch_thunk;
NaClPatchOneTrampolineCall(call_target_addr, target_addr);
}
void NaClFillMemoryRegionWithHalt(void *start, size_t size) {
CHECK(!(size % NACL_HALT_LEN));
/* Tell valgrind that this memory is accessible and undefined */
NACL_MAKE_MEM_UNDEFINED(start, size);
memset(start, NACL_HALT_OPCODE, size);
}
void NaClFillTrampolineRegion(struct NaClApp *nap) {
NaClFillMemoryRegionWithHalt(
(void *) (nap->mem_start + NACL_TRAMPOLINE_START),
NACL_TRAMPOLINE_SIZE);
}
void NaClLoadSpringboard(struct NaClApp *nap) {
/*
* There is no springboard for x86-64.
*/
UNREFERENCED_PARAMETER(nap);
}
|
leighpauls/k2cro4
|
native_client/src/trusted/service_runtime/arch/x86_64/sel_ldr_x86_64.c
|
C
|
bsd-3-clause
| 5,566 |
// 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 "platform/fonts/shaping/RunSegmenter.h"
#include "platform/fonts/ScriptRunIterator.h"
#include "platform/fonts/SmallCapsIterator.h"
#include "platform/fonts/SymbolsIterator.h"
#include "platform/fonts/UTF16TextIterator.h"
#include "platform/text/Character.h"
#include "wtf/Assertions.h"
namespace blink {
RunSegmenter::RunSegmenter(const UChar* buffer, unsigned bufferSize, FontOrientation runOrientation, FontVariant variant)
: m_bufferSize(bufferSize)
, m_candidateRange({ 0, 0, USCRIPT_INVALID_CODE, OrientationIterator::OrientationKeep, SmallCapsIterator::SmallCapsSameCase })
, m_scriptRunIterator(adoptPtr(new ScriptRunIterator(buffer, bufferSize)))
, m_orientationIterator(runOrientation == FontOrientation::VerticalMixed ? adoptPtr(new OrientationIterator(buffer, bufferSize, runOrientation)) : nullptr)
, m_smallCapsIterator(variant == FontVariantSmallCaps ? adoptPtr(new SmallCapsIterator(buffer, bufferSize)) : nullptr)
, m_symbolsIterator(adoptPtr(new SymbolsIterator(buffer, bufferSize)))
, m_lastSplit(0)
, m_scriptRunIteratorPosition(0)
, m_orientationIteratorPosition(runOrientation == FontOrientation::VerticalMixed ? 0 : m_bufferSize)
, m_smallCapsIteratorPosition(variant == FontVariantSmallCaps ? 0 : m_bufferSize)
, m_symbolsIteratorPosition(0)
, m_atEnd(false)
{
}
void RunSegmenter::consumeScriptIteratorPastLastSplit()
{
ASSERT(m_scriptRunIterator);
if (m_scriptRunIteratorPosition <= m_lastSplit && m_scriptRunIteratorPosition < m_bufferSize) {
while (m_scriptRunIterator->consume(m_scriptRunIteratorPosition, m_candidateRange.script)) {
if (m_scriptRunIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeOrientationIteratorPastLastSplit()
{
if (m_orientationIterator && m_orientationIteratorPosition <= m_lastSplit && m_orientationIteratorPosition < m_bufferSize) {
while (m_orientationIterator->consume(&m_orientationIteratorPosition, &m_candidateRange.renderOrientation)) {
if (m_orientationIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeSmallCapsIteratorPastLastSplit()
{
if (m_smallCapsIterator && m_smallCapsIteratorPosition <= m_lastSplit && m_smallCapsIteratorPosition < m_bufferSize) {
while (m_smallCapsIterator->consume(&m_smallCapsIteratorPosition, &m_candidateRange.smallCapsBehavior)) {
if (m_smallCapsIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeSymbolsIteratorPastLastSplit()
{
ASSERT(m_symbolsIterator);
if (m_symbolsIteratorPosition <= m_lastSplit && m_symbolsIteratorPosition < m_bufferSize) {
while (m_symbolsIterator->consume(&m_symbolsIteratorPosition, &m_candidateRange.fontFallbackPriority)) {
if (m_symbolsIteratorPosition > m_lastSplit)
return;
}
}
}
bool RunSegmenter::consume(RunSegmenterRange* nextRange)
{
if (m_atEnd || !m_bufferSize)
return false;
consumeScriptIteratorPastLastSplit();
consumeOrientationIteratorPastLastSplit();
consumeSmallCapsIteratorPastLastSplit();
consumeSymbolsIteratorPastLastSplit();
if (m_scriptRunIteratorPosition <= m_orientationIteratorPosition
&& m_scriptRunIteratorPosition <= m_smallCapsIteratorPosition
&& m_scriptRunIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_scriptRunIteratorPosition;
}
if (m_orientationIteratorPosition <= m_scriptRunIteratorPosition
&& m_orientationIteratorPosition <= m_smallCapsIteratorPosition
&& m_orientationIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_orientationIteratorPosition;
}
if (m_smallCapsIteratorPosition <= m_scriptRunIteratorPosition
&& m_smallCapsIteratorPosition <= m_orientationIteratorPosition
&& m_smallCapsIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_smallCapsIteratorPosition;
}
if (m_symbolsIteratorPosition <= m_scriptRunIteratorPosition
&& m_symbolsIteratorPosition <= m_orientationIteratorPosition
&& m_symbolsIteratorPosition <= m_smallCapsIteratorPosition) {
m_lastSplit = m_symbolsIteratorPosition;
}
m_candidateRange.start = m_candidateRange.end;
m_candidateRange.end = m_lastSplit;
*nextRange = m_candidateRange;
m_atEnd = m_lastSplit == m_bufferSize;
return true;
}
} // namespace blink
|
was4444/chromium.src
|
third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
|
C++
|
bsd-3-clause
| 4,699 |
{% macro vital(addon, type) %}
<div class="vital">
{% if type in ('updated', 'created') %}
<span class="updated">
{% if type == 'updated' %}
{# L10n: {0} is a date. #}
{{ _('Updated {0}')|f(addon.last_updated|datetime) }}
{% else %}
{# L10n: {0} is a date. #}
{{ _('Added {0}')|f(addon.created|datetime) }}
{% endif %}
</span>
{% elif type in ('downloads', 'adu') %}
{% if type == 'downloads' %}
<span class="downloads adu">
{% trans cnt=addon.weekly_downloads,
num=addon.weekly_downloads|numberfmt %}
{{ num }} weekly download
{% pluralize %}
{{ num }} weekly downloads
{% endtrans %}
</span>
{% else %}
<span class="adu">
{% set adu=addon.average_daily_users %}
{% trans cnt=adu, num=adu|numberfmt %}
{{ num }} user
{% pluralize %}
{{ num }} users
{% endtrans %}
</span>
{% endif %}
{% endif %}
</div>
{% endmacro %}
{% macro addon_heading(addon, version) %}
<h1{{ addon.name|locale_html }}>
{{ addon.name }}
{% if version %}
<span class="version">{{ version.version }}</span>
{% endif %}
</h1>
{% endmacro %}
{% macro sort_vital(addon, field) %}
{% if field in ('popular', 'downloads') or not addon.show_adu() %}
<div class="adu downloads">
{% with num=addon.weekly_downloads %}
{# L10n: {0} is the number of downloads. #}
{{ ngettext('{0} weekly download', '{0} weekly downloads',
num)|f(num|numberfmt) }}
{% endwith %}
</div>
{% else %}
<div class="adu">
{% with num=addon.average_daily_users %}
{# L10n: {0} is the number of users. #}
{{ ngettext('{0} user', '{0} users', num)|f(num|numberfmt) }}
{% endwith %}
</div>
{% endif %}
{% if field in ('created', 'updated') %}
<div class="updated">
{% if field == 'created' %}
{# L10n: {0} is a date. #}
{{ _('Added {0}')|f(addon.created|datetime) }}
{% else %}
{# L10n: {0} is a date. #}
{{ _('Updated {0}')|f(addon.last_updated|datetime) }}
{% endif %}
</div>
{% endif %}
{% endmacro %}
|
jinankjain/zamboni
|
apps/addons/templates/addons/macros.html
|
HTML
|
bsd-3-clause
| 2,302 |
<!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 (1.8.0_101) on Sat Aug 20 05:41:48 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.search.Sorting (Solr 6.2.0 API)</title>
<meta name="date" content="2016-08-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.search.Sorting (Solr 6.2.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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="../../../../../org/apache/solr/search/Sorting.html" title="class in org.apache.solr.search">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="../../../../../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?org/apache/solr/search/class-use/Sorting.html" target="_top">Frames</a></li>
<li><a href="Sorting.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 org.apache.solr.search.Sorting" class="title">Uses of Class<br>org.apache.solr.search.Sorting</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.search.Sorting</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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="../../../../../org/apache/solr/search/Sorting.html" title="class in org.apache.solr.search">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="../../../../../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?org/apache/solr/search/class-use/Sorting.html" target="_top">Frames</a></li>
<li><a href="Sorting.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 ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
berkeleybop/bbop-manager-golr
|
solr/docs/solr-core/org/apache/solr/search/class-use/Sorting.html
|
HTML
|
bsd-3-clause
| 4,916 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin="">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.vector_ar.svar_model.SVARResults.summary — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.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 crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.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>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.svar_ma_rep" href="statsmodels.tsa.vector_ar.svar_model.SVARResults.svar_ma_rep.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.svar_model.SVARResults.sirf_errband_mc" href="statsmodels.tsa.vector_ar.svar_model.SVARResults.sirf_errband_mc.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.summary" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.11.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.vector_ar.svar_model.SVARResults.summary </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../vector_ar.html" class="md-tabs__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.html" class="md-tabs__link">statsmodels.tsa.vector_ar.svar_model.SVARResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.11.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.summary.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-vector-ar-svar-model-svarresults-summary--page-root">statsmodels.tsa.vector_ar.svar_model.SVARResults.summary<a class="headerlink" href="#generated-statsmodels-tsa-vector-ar-svar-model-svarresults-summary--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.tsa.vector_ar.svar_model.SVARResults.summary">
<code class="sig-prename descclassname">SVARResults.</code><code class="sig-name descname">summary</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.tsa.vector_ar.svar_model.SVARResults.summary" title="Permalink to this definition">¶</a></dt>
<dd><p>Compute console output summary of estimates</p>
<dl class="field-list">
<dt class="field-odd">Returns</dt>
<dd class="field-odd"><dl>
<dt><strong>summary</strong><span class="classifier"><code class="xref py py-obj docutils literal notranslate"><span class="pre">VARSummary</span></code></span></dt><dd></dd>
</dl>
</dd>
</dl>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.sirf_errband_mc.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.vector_ar.svar_model.SVARResults.sirf_errband_mc </span>
</div>
</a>
<a href="statsmodels.tsa.vector_ar.svar_model.SVARResults.svar_ma_rep.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.vector_ar.svar_model.SVARResults.svar_ma_rep </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Jan 22, 2020.
<br/>
Created using
<a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.11.0/generated/statsmodels.tsa.vector_ar.svar_model.SVARResults.summary.html
|
HTML
|
bsd-3-clause
| 17,978 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.discrete.discrete_model.CountResults.llf — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.discrete.discrete_model.CountResults.llnull" href="statsmodels.discrete.discrete_model.CountResults.llnull.html" />
<link rel="prev" title="statsmodels.discrete.discrete_model.CountResults.fittedvalues" href="statsmodels.discrete.discrete_model.CountResults.fittedvalues.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.discrete.discrete_model.CountResults.llf" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.13.0</span>
<span class="md-header-nav__topic"> statsmodels.discrete.discrete_model.CountResults.llf </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../discretemod.html" class="md-tabs__link">Regression with Discrete Dependent Variable</a></li>
<li class="md-tabs__item"><a href="statsmodels.discrete.discrete_model.CountResults.html" class="md-tabs__link">statsmodels.discrete.discrete_model.CountResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.13.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li>
<li class="md-nav__item">
<a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.discrete.discrete_model.CountResults.llf.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-discrete-discrete-model-countresults-llf--page-root">statsmodels.discrete.discrete_model.CountResults.llf<a class="headerlink" href="#generated-statsmodels-discrete-discrete-model-countresults-llf--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py attribute">
<dt class="sig sig-object py" id="statsmodels.discrete.discrete_model.CountResults.llf">
<span class="sig-prename descclassname"><span class="pre">CountResults.</span></span><span class="sig-name descname"><span class="pre">llf</span></span><a class="headerlink" href="#statsmodels.discrete.discrete_model.CountResults.llf" title="Permalink to this definition">¶</a></dt>
<dd><p>Log-likelihood of model</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.discrete.discrete_model.CountResults.fittedvalues.html" title="statsmodels.discrete.discrete_model.CountResults.fittedvalues"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.discrete.discrete_model.CountResults.fittedvalues </span>
</div>
</a>
<a href="statsmodels.discrete.discrete_model.CountResults.llnull.html" title="statsmodels.discrete.discrete_model.CountResults.llnull"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.discrete.discrete_model.CountResults.llnull </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 06, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.0.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.13.0/generated/statsmodels.discrete.discrete_model.CountResults.llf.html
|
HTML
|
bsd-3-clause
| 18,257 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.genmod.families.family.InverseGaussian.loglike — statsmodels 0.9.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" 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="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.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.loglike_obs" href="statsmodels.genmod.families.family.InverseGaussian.loglike_obs.html" />
<link rel="prev" title="statsmodels.genmod.families.family.InverseGaussian.fitted" href="statsmodels.genmod.families.family.InverseGaussian.fitted.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>
</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.loglike_obs.html" title="statsmodels.genmod.families.family.InverseGaussian.loglike_obs"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.InverseGaussian.fitted.html" title="statsmodels.genmod.families.family.InverseGaussian.fitted"
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-loglike">
<h1>statsmodels.genmod.families.family.InverseGaussian.loglike<a class="headerlink" href="#statsmodels-genmod-families-family-inversegaussian-loglike" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.genmod.families.family.InverseGaussian.loglike">
<code class="descclassname">InverseGaussian.</code><code class="descname">loglike</code><span class="sig-paren">(</span><em>endog</em>, <em>mu</em>, <em>var_weights=1.0</em>, <em>freq_weights=1.0</em>, <em>scale=1.0</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.genmod.families.family.InverseGaussian.loglike" title="Permalink to this definition">¶</a></dt>
<dd><p>The log-likelihood function in terms of the fitted mean response.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>endog</strong> (<em>array</em>) – Usually the endogenous response variable.</li>
<li><strong>mu</strong> (<em>array</em>) – Usually but not always the fitted mean response variable.</li>
<li><strong>var_weights</strong> (<em>array-like</em>) – 1d array of variance (analytic) weights. The default is 1.</li>
<li><strong>freq_weights</strong> (<em>array-like</em>) – 1d array of frequency weights. The default is 1.</li>
<li><strong>scale</strong> (<em>float</em>) – The scale parameter. The default is 1.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>ll</strong> – The value of the loglikelihood evaluated at
(endog, mu, var_weights, freq_weights, scale) as defined below.</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body"><p class="first last">float</p>
</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<p>Where <span class="math notranslate nohighlight">\(ll_i\)</span> is the by-observation log-likelihood:</p>
<div class="math notranslate nohighlight">
\[ll = \sum(ll_i * freq\_weights_i)\]</div>
<p><code class="docutils literal notranslate"><span class="pre">ll_i</span></code> is defined for each family. endog and mu are not restricted
to <code class="docutils literal notranslate"><span class="pre">endog</span></code> and <code class="docutils literal notranslate"><span class="pre">mu</span></code> respectively. For instance, you could call
both <code class="docutils literal notranslate"><span class="pre">loglike(endog,</span> <span class="pre">endog)</span></code> and <code class="docutils literal notranslate"><span class="pre">loglike(endog,</span> <span class="pre">mu)</span></code> to get the
log-likelihood ratio.</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.fitted.html"
title="previous chapter">statsmodels.genmod.families.family.InverseGaussian.fitted</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.InverseGaussian.loglike_obs.html"
title="next chapter">statsmodels.genmod.families.family.InverseGaussian.loglike_obs</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.loglike.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4.
</div>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
0.9.0/generated/statsmodels.genmod.families.family.InverseGaussian.loglike.html
|
HTML
|
bsd-3-clause
| 8,756 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=campus_rec',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
|
henrybagus/seminar
|
config/db.php
|
PHP
|
bsd-3-clause
| 183 |
require_dependency 'spree/calculator'
module Spree
class PaymentCalculator::PerItem < Calculator
preference :amount, :decimal, :default => 0
attr_accessible :preferred_amount
def self.description
I18n.t(:flat_rate_per_item)
end
def compute(object=nil)
return 0 if object.nil?
self.preferred_amount * object.line_items.reduce(0) do |sum, value|
if !matching_products || matching_products.include?(value.product)
value_to_add = value.quantity
else
value_to_add = 0
end
sum + value_to_add
end
end
# Returns all products that match this calculator, but only if the calculator
# is attached to a promotion. If attached to a ShippingMethod, nil is returned.
def matching_products
# Regression check for #1596
# Calculator::PerItem can be used in two cases.
# The first is in a typical promotion, providing a discount per item of a particular item
# The second is a ShippingMethod, where it applies to an entire order
#
# Shipping methods do not have promotions attached, but promotions do
# Therefore we must check for promotions
if self.calculable.respond_to?(:promotion)
self.calculable.promotion.rules.map(&:products).flatten
end
end
end
end
|
damianogiacomello/spree_payment_calculator
|
app/model/spree/payment_calculator/per_item.rb
|
Ruby
|
bsd-3-clause
| 1,325 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Dojo
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: SubFormTest.php 24594 2012-01-05 21:27:01Z matthew $
*/
// Call Zend_Dojo_Form_SubFormTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
define("PHPUnit_MAIN_METHOD", "Zend_Dojo_Form_SubFormTest::main");
}
/** Zend_Dojo_Form_SubForm */
require_once 'Zend/Dojo/Form/SubForm.php';
/** Zend_View */
require_once 'Zend/View.php';
/**
* Test class for Zend_Dojo_SubForm
*
* @category Zend
* @package Zend_Dojo
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Dojo
* @group Zend_Dojo_Form
*/
class Zend_Dojo_Form_SubFormTest extends PHPUnit_Framework_TestCase
{
/**
* Runs the test methods of this class.
*
* @return void
*/
public static function main()
{
$suite = new PHPUnit_Framework_TestSuite("Zend_Dojo_Form_SubFormTest");
$result = PHPUnit_TextUI_TestRunner::run($suite);
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*
* @return void
*/
public function setUp()
{
$this->form = new Zend_Dojo_Form_SubForm();
$this->form->addElement('TextBox', 'foo')
->addDisplayGroup(array('foo'), 'dg')
->setView(new Zend_View());
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*
* @return void
*/
public function tearDown()
{
}
public function testDojoFormDecoratorPathShouldBeRegisteredByDefault()
{
$paths = $this->form->getPluginLoader('decorator')->getPaths('Zend_Dojo_Form_Decorator');
$this->assertTrue(is_array($paths));
}
public function testDojoFormElementPathShouldBeRegisteredByDefault()
{
$paths = $this->form->getPluginLoader('element')->getPaths('Zend_Dojo_Form_Element');
$this->assertTrue(is_array($paths));
}
public function testDojoFormElementDecoratorPathShouldBeRegisteredByDefault()
{
$paths = $this->form->foo->getPluginLoader('decorator')->getPaths('Zend_Dojo_Form_Decorator');
$this->assertTrue(is_array($paths));
}
public function testDojoFormDisplayGroupDecoratorPathShouldBeRegisteredByDefault()
{
$paths = $this->form->dg->getPluginLoader()->getPaths('Zend_Dojo_Form_Decorator');
$this->assertTrue(is_array($paths));
}
public function testDefaultDisplayGroupClassShouldBeDojoDisplayGroupByDefault()
{
$this->assertEquals('Zend_Dojo_Form_DisplayGroup', $this->form->getDefaultDisplayGroupClass());
}
public function testDefaultDecoratorsShouldIncludeContentPane()
{
$this->assertNotNull($this->form->getDecorator('ContentPane'));
}
public function testShouldRegisterDojoViewHelperPath()
{
$view = $this->form->getView();
$loader = $view->getPluginLoader('helper');
$paths = $loader->getPaths('Zend_Dojo_View_Helper');
$this->assertTrue(is_array($paths));
}
}
// Call Zend_Dojo_Form_SubFormTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Dojo_Form_SubFormTest::main") {
Zend_Dojo_Form_SubFormTest::main();
}
|
karthiksekarnz/educulas
|
tests/Zend/Dojo/Form/SubFormTest.php
|
PHP
|
bsd-3-clause
| 4,160 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.sandbox.regression.gmm.IVGMMResults.summary — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.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 id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.regression.gmm.IVGMMResults.t_test" href="statsmodels.sandbox.regression.gmm.IVGMMResults.t_test.html" />
<link rel="prev" title="statsmodels.sandbox.regression.gmm.IVGMMResults.save" href="statsmodels.sandbox.regression.gmm.IVGMMResults.save.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.sandbox.regression.gmm.IVGMMResults.summary" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.11.1</span>
<span class="md-header-nav__topic"> statsmodels.sandbox.regression.gmm.IVGMMResults.summary </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../gmm.html" class="md-tabs__link">Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.sandbox.regression.gmm.IVGMMResults.html" class="md-tabs__link">statsmodels.sandbox.regression.gmm.IVGMMResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.11.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../duration.html" class="md-nav__link">Methods for Survival and Duration Analysis</a>
</li>
<li class="md-nav__item">
<a href="../nonparametric.html" class="md-nav__link">Nonparametric Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">nonparametric</span></code></a>
</li>
<li class="md-nav__item">
<a href="../gmm.html" class="md-nav__link">Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a>
</li>
<li class="md-nav__item">
<a href="../miscmodels.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">miscmodels</span></code></a>
</li>
<li class="md-nav__item">
<a href="../multivariate.html" class="md-nav__link">Multivariate Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">multivariate</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.regression.gmm.IVGMMResults.summary.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-sandbox-regression-gmm-ivgmmresults-summary--page-root">statsmodels.sandbox.regression.gmm.IVGMMResults.summary<a class="headerlink" href="#generated-statsmodels-sandbox-regression-gmm-ivgmmresults-summary--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.sandbox.regression.gmm.IVGMMResults.summary">
<code class="sig-prename descclassname">IVGMMResults.</code><code class="sig-name descname">summary</code><span class="sig-paren">(</span><em class="sig-param">yname=None</em>, <em class="sig-param">xname=None</em>, <em class="sig-param">title=None</em>, <em class="sig-param">alpha=0.05</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.regression.gmm.IVGMMResults.summary" title="Permalink to this definition">¶</a></dt>
<dd><p>Summarize the Regression Results</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>yname</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Default is <cite>y</cite></p>
</dd>
<dt><strong>xname</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#list" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">list</span></code></a>[<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>], <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Default is <cite>var_##</cite> for ## in p the number of regressors</p>
</dd>
<dt><strong>title</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Title for the top table. If not None, then this replaces the
default title</p>
</dd>
<dt><strong>alpha</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>significance level for the confidence intervals</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl>
<dt><strong>smry</strong><span class="classifier"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Summary</span></code> <code class="xref py py-obj docutils literal notranslate"><span class="pre">instance</span></code></span></dt><dd><p>this holds the summary tables and text, which can be printed or
converted to various output formats.</p>
</dd>
</dl>
</dd>
</dl>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><a class="reference internal" href="statsmodels.iolib.summary.Summary.html#statsmodels.iolib.summary.Summary" title="statsmodels.iolib.summary.Summary"><code class="xref py py-obj docutils literal notranslate"><span class="pre">statsmodels.iolib.summary.Summary</span></code></a></dt><dd><p>class to hold summary results</p>
</dd>
</dl>
</div>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.sandbox.regression.gmm.IVGMMResults.save.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.regression.gmm.IVGMMResults.save </span>
</div>
</a>
<a href="statsmodels.sandbox.regression.gmm.IVGMMResults.t_test.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.regression.gmm.IVGMMResults.t_test </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 21, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 2.4.2.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.11.1/generated/statsmodels.sandbox.regression.gmm.IVGMMResults.summary.html
|
HTML
|
bsd-3-clause
| 20,784 |
//
// AppDelegate.h
// DemoApp
//
// Created by Stephen Anderson on 8/27/13.
// Copyright (c) 2013 Product & Technology. All rights reserved.
//
#import <UIKit/UIKit.h>
@class ViewController;
@class AdObserver;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (strong, nonatomic) AdObserver *adObserver;
@end
|
xadrnd/xad-ios-sdk
|
DemoApp/DemoApp/AppDelegate.h
|
C
|
bsd-3-clause
| 451 |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Nov 22 2016 05:57:16).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
@protocol DVTFileSystemRepresentationProviding
- (void)dvt_provideFileSystemRepresentationToBlock:(void (^)(char *, unsigned long long))arg1;
@end
|
plu/FBSimulatorControl
|
PrivateHeaders/DVTFoundation/DVTFileSystemRepresentationProviding-Protocol.h
|
C
|
bsd-3-clause
| 333 |
#flash-messages {position: absolute;}
#flash-messages .success ul, .notice ul, .error ul { list-style: none; margin: 0; padding: 0; }
#flash-messages .success ul li, .notice ul li, .error ul li { float: none; display: block; }
#flash-messages .success ul, .notice ul, .error ul { list-style: none; margin: 0; padding: 0; font-weight: bold; }
#flash-messages .success ul li, .notice ul li, .error ul li { float: none; display: block; text-align: center;}
#flash-messages div.success, div.notice, div.error {
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-moz-box-shadow: 0 2px 4px #ccc;
-webkit-box-shadow: 0 2px 4px #ccc;
box-shadow: 0 2px 4px #ccc;
position: relative;
z-index: 1;
}
#flash-messages span.close {
position: absolute;
top: 1px;
right: 6px;
cursor: pointer;
font-weight: bold;
}
|
sgarciab/SAB
|
media/css/flash-messenger.css
|
CSS
|
bsd-3-clause
| 837 |
# dpconverge
|
whitews/dpconverge
|
README.md
|
Markdown
|
bsd-3-clause
| 13 |
import {InputWidget, InputWidgetView} from "./input_widget"
import {input} from "core/dom"
import * as p from "core/properties"
import {bk_input} from "styles/widgets/inputs"
export class TextInputView extends InputWidgetView {
model: TextInput
protected input_el: HTMLInputElement
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.name.change, () => this.input_el.name = this.model.name || "")
this.connect(this.model.properties.value.change, () => this.input_el.value = this.model.value)
this.connect(this.model.properties.disabled.change, () => this.input_el.disabled = this.model.disabled)
this.connect(this.model.properties.placeholder.change, () => this.input_el.placeholder = this.model.placeholder)
}
render(): void {
super.render()
this.input_el = input({
type: "text",
class: bk_input,
name: this.model.name,
value: this.model.value,
disabled: this.model.disabled,
placeholder: this.model.placeholder,
})
this.input_el.addEventListener("change", () => this.change_input())
this.group_el.appendChild(this.input_el)
}
change_input(): void {
this.model.value = this.input_el.value
super.change_input()
}
}
export namespace TextInput {
export type Attrs = p.AttrsOf<Props>
export type Props = InputWidget.Props & {
value: p.Property<string>
placeholder: p.Property<string>
}
}
export interface TextInput extends TextInput.Attrs {}
export class TextInput extends InputWidget {
properties: TextInput.Props
constructor(attrs?: Partial<TextInput.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.default_view = TextInputView
this.define<TextInput.Props>({
value: [ p.String, "" ],
placeholder: [ p.String, "" ],
})
}
}
TextInput.initClass()
|
timsnyder/bokeh
|
bokehjs/src/lib/models/widgets/text_input.ts
|
TypeScript
|
bsd-3-clause
| 1,868 |
#
# https://github.com/andreyk0/haskell-on-arm
#
# User: debian
# Passwd: /dev/null
#
FROM scratch
ADD jessie.tgz /
ADD qemu-arm-static /usr/bin/qemu-arm-static
CMD ["/bin/bash"]
|
andreyk0/haskell-on-arm
|
docker/armhf-debian-jessie/Dockerfile
|
Dockerfile
|
bsd-3-clause
| 180 |
#!/usr/bin/python
# Copyright (c) 2016 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.
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
import sys
sys.path += ['../..']
import gencerts
DATE_A = '150101120000Z'
DATE_B = '150102120000Z'
DATE_C = '180101120000Z'
DATE_D = '180102120000Z'
root = gencerts.create_self_signed_root_certificate('Root')
root.set_validity_range(DATE_A, DATE_D)
int_ac = gencerts.create_intermediate_certificate('Intermediate', root)
int_ac.set_validity_range(DATE_A, DATE_C)
int_ad = gencerts.create_intermediate_certificate('Intermediate', root)
int_ad.set_validity_range(DATE_A, DATE_D)
int_ad.set_key(int_ac.get_key())
int_bc = gencerts.create_intermediate_certificate('Intermediate', root)
int_bc.set_validity_range(DATE_B, DATE_C)
int_bc.set_key(int_ac.get_key())
int_bd = gencerts.create_intermediate_certificate('Intermediate', root)
int_bd.set_validity_range(DATE_B, DATE_D)
int_bd.set_key(int_ac.get_key())
target = gencerts.create_end_entity_certificate('Target', int_ac)
target.set_validity_range(DATE_A, DATE_D)
gencerts.write_chain('The root', [root], out_pem='root.pem')
gencerts.write_chain('Intermediate with validity range A..C',
[int_ac], out_pem='int_ac.pem')
gencerts.write_chain('Intermediate with validity range A..D',
[int_ad], out_pem='int_ad.pem')
gencerts.write_chain('Intermediate with validity range B..C',
[int_bc], out_pem='int_bc.pem')
gencerts.write_chain('Intermediate with validity range B..D',
[int_bd], out_pem='int_bd.pem')
gencerts.write_chain('The target', [target], out_pem='target.pem')
|
endlessm/chromium-browser
|
net/data/path_builder_unittest/validity_date_prioritization/generate-certs.py
|
Python
|
bsd-3-clause
| 1,833 |
<?php
include_once "../../includes/easyparliament/init.php";
if (($date = get_http_var('d')) && preg_match('#^\d\d\d\d-\d\d-\d\d$#', $date)) {
$this_page = 'hansard_date';
$PAGE->set_hansard_headings(array('date'=>$date));
$URL = new URL($this_page);
$db = new ParlDB;
$q = $db->query("SELECT MIN(hdate) AS hdate FROM hansard WHERE hdate > '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['next'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Next day',
'title' => $title
);
}
$q = $db->query("SELECT MAX(hdate) AS hdate FROM hansard WHERE hdate < '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['prev'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Previous day',
'title' => $title
);
}
# $year = substr($date, 0, 4);
# $URL = new URL($hansardmajors[1]['page_year']);
# $URL->insert(array('y'=>$year));
# $nextprevdata['up'] = array (
# 'body' => "All of $year",
# 'title' => '',
# 'url' => $URL->generate()
# );
$DATA->set_page_metadata($this_page, 'nextprev', $nextprevdata);
$PAGE->page_start();
$PAGE->stripe_start();
include_once INCLUDESPATH . 'easyparliament/recess.php';
$time = strtotime($date);
$dayofweek = date('w', $time);
$recess = recess_prettify(date('j', $time), date('n', $time), date('Y', $time), 1);
if ($recess[0]) {
print '<p>The Houses of Parliament are in their ' . $recess[0] . ' at this time.</p>';
} elseif ($dayofweek == 0 || $dayofweek == 6) {
print '<p>The Houses of Parliament do not meet at weekends.</p>';
} else {
$data = array(
'date' => $date
);
foreach (array_keys($hansardmajors) as $major) {
$URL = new URL($hansardmajors[$major]['page_all']);
$URL->insert(array('d'=>$date));
$data[$major] = array('listurl'=>$URL->generate());
}
major_summary($data);
}
$PAGE->stripe_end(array(
array (
'type' => 'nextprev'
),
));
$PAGE->page_end();
} else {
header("Location: http://" . DOMAIN . "/");
exit;
}
|
palfrey/twfy
|
www/docs/hansard/index.php
|
PHP
|
bsd-3-clause
| 2,395 |
/*
* Copyright 2019 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/dawn/GrDawnBuffer.h"
#include "src/gpu/dawn/GrDawnStagingBuffer.h"
#include "src/gpu/dawn/GrDawnGpu.h"
namespace {
wgpu::BufferUsage GrGpuBufferTypeToDawnUsageBit(GrGpuBufferType type) {
switch (type) {
case GrGpuBufferType::kVertex:
return wgpu::BufferUsage::Vertex;
case GrGpuBufferType::kIndex:
return wgpu::BufferUsage::Index;
case GrGpuBufferType::kXferCpuToGpu:
return wgpu::BufferUsage::CopySrc;
case GrGpuBufferType::kXferGpuToCpu:
return wgpu::BufferUsage::CopyDst;
default:
SkASSERT(!"buffer type not supported by Dawn");
return wgpu::BufferUsage::Vertex;
}
}
}
GrDawnBuffer::GrDawnBuffer(GrDawnGpu* gpu, size_t sizeInBytes, GrGpuBufferType type,
GrAccessPattern pattern)
: INHERITED(gpu, sizeInBytes, type, pattern) {
wgpu::BufferDescriptor bufferDesc;
bufferDesc.size = sizeInBytes;
bufferDesc.usage = GrGpuBufferTypeToDawnUsageBit(type) | wgpu::BufferUsage::CopyDst;
fBuffer = this->getDawnGpu()->device().CreateBuffer(&bufferDesc);
this->registerWithCache(SkBudgeted::kYes);
}
GrDawnBuffer::~GrDawnBuffer() {
}
void GrDawnBuffer::onMap() {
if (this->wasDestroyed()) {
return;
}
GrStagingBuffer::Slice slice = getGpu()->allocateStagingBufferSlice(this->size());
fStagingBuffer = static_cast<GrDawnStagingBuffer*>(slice.fBuffer)->buffer();
fStagingOffset = slice.fOffset;
fMapPtr = slice.fData;
}
void GrDawnBuffer::onUnmap() {
if (this->wasDestroyed()) {
return;
}
fMapPtr = nullptr;
getDawnGpu()->getCopyEncoder()
.CopyBufferToBuffer(fStagingBuffer, fStagingOffset, fBuffer, 0, this->size());
}
bool GrDawnBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
if (this->wasDestroyed()) {
return false;
}
this->onMap();
memcpy(fMapPtr, src, srcSizeInBytes);
this->onUnmap();
return true;
}
GrDawnGpu* GrDawnBuffer::getDawnGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrDawnGpu*>(this->getGpu());
}
|
endlessm/chromium-browser
|
third_party/skia/src/gpu/dawn/GrDawnBuffer.cpp
|
C++
|
bsd-3-clause
| 2,347 |
<?php
/*
* 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 software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.org>.
*/
namespace Doctrine\ORM\Mapping;
/**
* A MappingException indicates that something is wrong with the mapping setup.
*
* @since 2.0
*/
class MappingException extends \Doctrine\ORM\ORMException
{
public static function pathRequired()
{
return new self("Specifying the paths to your entities is required ".
"in the AnnotationDriver to retrieve all class names.");
}
public static function identifierRequired($entityName)
{
return new self("No identifier/primary key specified for Entity '$entityName'."
. " Every Entity must have an identifier/primary key.");
}
public static function invalidInheritanceType($entityName, $type)
{
return new self("The inheritance type '$type' specified for '$entityName' does not exist.");
}
public static function generatorNotAllowedWithCompositeId()
{
return new self("Id generators can't be used with a composite id.");
}
public static function missingFieldName()
{
return new self("The association mapping misses the 'fieldName' attribute.");
}
public static function missingTargetEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'targetEntity' attribute.");
}
public static function missingSourceEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'sourceEntity' attribute.");
}
public static function mappingFileNotFound($entityName, $fileName)
{
return new self("No mapping file found named '$fileName' for class '$entityName'.");
}
public static function mappingNotFound($className, $fieldName)
{
return new self("No mapping found for field '$fieldName' on class '$className'.");
}
public static function oneToManyRequiresMappedBy($fieldName)
{
return new self("OneToMany mapping on field '$fieldName' requires the 'mappedBy' attribute.");
}
public static function joinTableRequired($fieldName)
{
return new self("The mapping of field '$fieldName' requires an the 'joinTable' attribute.");
}
/**
* Called if a required option was not found but is required
*
* @param string $field which field cannot be processed?
* @param string $expectedOption which option is required
* @param string $hint Can optionally be used to supply a tip for common mistakes,
* e.g. "Did you think of the plural s?"
* @return MappingException
*/
static function missingRequiredOption($field, $expectedOption, $hint = '')
{
$message = "The mapping of field '{$field}' is invalid: The option '{$expectedOption}' is required.";
if ( ! empty($hint)) {
$message .= ' (Hint: ' . $hint . ')';
}
return new self($message);
}
/**
* Generic exception for invalid mappings.
*
* @param string $fieldName
*/
public static function invalidMapping($fieldName)
{
return new self("The mapping of field '$fieldName' is invalid.");
}
/**
* Exception for reflection exceptions - adds the entity name,
* because there might be long classnames that will be shortened
* within the stacktrace
*
* @param string $entity The entity's name
* @param \ReflectionException $previousException
*/
public static function reflectionFailure($entity, \ReflectionException $previousException)
{
return new self('An error occurred in ' . $entity, 0, $previousException);
}
public static function joinColumnMustPointToMappedField($className, $joinColumn)
{
return new self('The column ' . $joinColumn . ' must be mapped to a field in class '
. $className . ' since it is referenced by a join column of another class.');
}
public static function classIsNotAValidEntityOrMappedSuperClass($className)
{
return new self('Class '.$className.' is not a valid entity or mapped super class.');
}
public static function propertyTypeIsRequired($className, $propertyName)
{
return new self("The attribute 'type' is required for the column description of property ".$className."::\$".$propertyName.".");
}
public static function tableIdGeneratorNotImplemented($className)
{
return new self("TableIdGenerator is not yet implemented for use with class ".$className);
}
/**
*
* @param string $entity The entity's name
* @param string $fieldName The name of the field that was already declared
*/
public static function duplicateFieldMapping($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function duplicateAssociationMapping($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function singleIdNotAllowedOnCompositePrimaryKey($entity) {
return new self('Single id is not allowed on composite primary key in entity '.$entity);
}
public static function unsupportedOptimisticLockingType($entity, $fieldName, $unsupportedType) {
return new self('Locking type "'.$unsupportedType.'" (specified in "'.$entity.'", field "'.$fieldName.'") '
.'is not supported by Doctrine.'
);
}
public static function fileMappingDriversRequireConfiguredDirectoryPath($path = null)
{
if ( ! empty($path)) {
$path = '[' . $path . ']';
}
return new self(
'File mapping drivers must have a valid directory path, ' .
'however the given path ' . $path . ' seems to be incorrect!'
);
}
/**
* Throws an exception that indicates that a class used in a discriminator map does not exist.
* An example would be an outdated (maybe renamed) classname.
*
* @param string $className The class that could not be found
* @param string $owningClass The class that declares the discriminator map.
* @return self
*/
public static function invalidClassInDiscriminatorMap($className, $owningClass) {
return new self(
"Entity class '$className' used in the discriminator map of class '$owningClass' ".
"does not exist."
);
}
public static function missingDiscriminatorMap($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator map was defined.");
}
public static function missingDiscriminatorColumn($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator column was defined.");
}
public static function invalidDiscriminatorColumnType($className, $type)
{
return new self("Discriminator column type on entity class '$className' is not allowed to be '$type'. 'string' or 'integer' type variables are suggested!");
}
public static function cannotVersionIdField($className, $fieldName)
{
return new self("Setting Id field '$fieldName' as versionale in entity class '$className' is not supported.");
}
/**
* @param string $className
* @param string $columnName
* @return self
*/
public static function duplicateColumnName($className, $columnName)
{
return new self("Duplicate definition of column '".$columnName."' on entity '".$className."' in a field or discriminator column mapping.");
}
}
|
notmessenger/ZF-REST-API
|
library/Doctrine/ORM/Mapping/MappingException.php
|
PHP
|
bsd-3-clause
| 8,678 |
# Try to find hwloc libraries and headers.
#
# Usage of this module:
#
# find_package(hwloc)
#
# Variables defined by this module:
#
# HWLOC_FOUND System has hwloc libraries and headers
# HWLOC_LIBRARIES The hwloc library
# HWLOC_INCLUDE_DIRS The location of HWLOC headers
find_path(
HWLOC_PREFIX
NAMES include/hwloc.h
)
if (NOT HWLOC_PREFIX AND NOT $ENV{HWLOC_BASE} STREQUAL "")
set(HWLOC_PREFIX $ENV{HWLOC_BASE})
endif()
message(STATUS "Searching for hwloc library in path " ${HWLOC_PREFIX})
find_library(
HWLOC_LIBRARIES
NAMES hwloc
HINTS ${HWLOC_PREFIX}/lib
)
find_path(
HWLOC_INCLUDE_DIRS
NAMES hwloc.h
HINTS ${HWLOC_PREFIX}/include
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
HWLOC DEFAULT_MSG
HWLOC_LIBRARIES
HWLOC_INCLUDE_DIRS
)
mark_as_advanced(
HWLOC_LIBRARIES
HWLOC_INCLUDE_DIRS
)
if (HWLOC_FOUND)
if (NOT $ENV{HWLOC_LIB} STREQUAL "")
# set(HWLOC_LIBRARIES "$ENV{HWLOC_LIB}")
endif()
message(STATUS "hwloc includes: " ${HWLOC_INCLUDE_DIRS})
message(STATUS "hwloc libraries: " ${HWLOC_LIBRARIES})
endif()
|
fuchsto/dyloc
|
CMakeExt/hwloc.cmake
|
CMake
|
bsd-3-clause
| 1,128 |
/*
* Copyright (c) 2016, Salesforce.com, 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.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemAssert;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* COUNT, GROUP, UNION.
*
* @author rzhang
*/
public class MetricUnionTransform implements Transform {
//~ Static fields/initializers *******************************************************************************************************************
/** The metric name for this transform is result. */
public static final String RESULT_METRIC_NAME = "result";
//~ Instance fields ******************************************************************************************************************************
private final ValueReducer valueUnionReducer;
private final String defaultScope;
private final String defaultMetricName;
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new ReduceTransform object.
*
* @param valueUnionReducer valueReducerOrMapping The valueMapping.
*/
protected MetricUnionTransform(ValueReducer valueUnionReducer) {
this.defaultScope = TransformFactory.Function.UNION.name();
this.defaultMetricName = TransformFactory.DEFAULT_METRIC_NAME;
this.valueUnionReducer = valueUnionReducer;
}
//~ Methods **************************************************************************************************************************************
@Override
public String getResultScopeName() {
return defaultScope;
}
/**
* If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
*
* @param metrics The metrics to transform.
*
* @return The transformed metrics.
*/
@Override
public List<Metric> transform(List<Metric> metrics) {
return union(metrics);
}
/**
* Performs a columnar union of metrics.
*
* @param metrics The metrics to merge.
*
* @return The merged metrics.
*/
public List<Metric> union(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
if (metrics.isEmpty()) {
return metrics;
}
Metric newMetric = reduce(metrics);
Map<Long, String> reducedDatapoints = newMetric.getDatapoints();
Set<Long> sharedTimestamps = reducedDatapoints.keySet();
Map<Long, String> unionDatapoints = new TreeMap<Long, String>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> entry : metric.getDatapoints().entrySet()) {
if (!sharedTimestamps.contains(entry.getKey())) {
unionDatapoints.put(entry.getKey(), entry.getValue());
}
}
}
newMetric.addDatapoints(unionDatapoints);
return Arrays.asList(newMetric);
}
/**
* Reduce transform for the list of metrics.
*
* @param metrics The list of metrics to reduce.
*
* @return The reduced metric.
*/
protected Metric reduce(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
/*
* if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
*/
MetricDistiller distiller = new MetricDistiller();
distiller.distill(metrics);
Map<Long, List<String>> collated = collate(metrics);
Map<Long, String> minDatapoints = reduce(collated, metrics);
String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
Metric newMetric = new Metric(defaultScope, newMetricName);
newMetric.setDisplayName(distiller.getDisplayName());
newMetric.setUnits(distiller.getUnits());
newMetric.setTags(distiller.getTags());
newMetric.setDatapoints(minDatapoints);
return newMetric;
}
private Map<Long, List<String>> collate(List<Metric> metrics) {
Map<Long, List<String>> collated = new HashMap<Long, List<String>>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> point : metric.getDatapoints().entrySet()) {
if (!collated.containsKey(point.getKey())) {
collated.put(point.getKey(), new ArrayList<String>());
}
collated.get(point.getKey()).add(point.getValue());
}
}
return collated;
}
private Map<Long, String> reduce(Map<Long, List<String>> collated, List<Metric> metrics) {
Map<Long, String> reducedDatapoints = new HashMap<>();
for (Map.Entry<Long, List<String>> entry : collated.entrySet()) {
if (entry.getValue().size() < metrics.size()) {
continue;
}
reducedDatapoints.put(entry.getKey(), this.valueUnionReducer.reduce(entry.getValue()));
}
return reducedDatapoints;
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
throw new UnsupportedOperationException("Union transform can't be used with constants!");
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new UnsupportedOperationException("Union doesn't need list of list");
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
|
rmelick/Argus
|
ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/MetricUnionTransform.java
|
Java
|
bsd-3-clause
| 7,287 |
// 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 "net/url_request/url_fetcher_core.h"
#include <stdint.h>
#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/tracked_objects.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_file_element_reader.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_fetcher_response_writer.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_throttler_manager.h"
namespace {
const int kBufferSize = 4096;
const int kUploadProgressTimerInterval = 100;
bool g_ignore_certificate_requests = false;
void EmptyCompletionCallback(int result) {}
} // namespace
namespace net {
// URLFetcherCore::Registry ---------------------------------------------------
URLFetcherCore::Registry::Registry() {}
URLFetcherCore::Registry::~Registry() {}
void URLFetcherCore::Registry::AddURLFetcherCore(URLFetcherCore* core) {
DCHECK(!ContainsKey(fetchers_, core));
fetchers_.insert(core);
}
void URLFetcherCore::Registry::RemoveURLFetcherCore(URLFetcherCore* core) {
DCHECK(ContainsKey(fetchers_, core));
fetchers_.erase(core);
}
void URLFetcherCore::Registry::CancelAll() {
while (!fetchers_.empty())
(*fetchers_.begin())->CancelURLRequest(ERR_ABORTED);
}
// URLFetcherCore -------------------------------------------------------------
// static
base::LazyInstance<URLFetcherCore::Registry>
URLFetcherCore::g_registry = LAZY_INSTANCE_INITIALIZER;
URLFetcherCore::URLFetcherCore(URLFetcher* fetcher,
const GURL& original_url,
URLFetcher::RequestType request_type,
URLFetcherDelegate* d)
: fetcher_(fetcher),
original_url_(original_url),
request_type_(request_type),
delegate_(d),
delegate_task_runner_(base::ThreadTaskRunnerHandle::Get()),
load_flags_(LOAD_NORMAL),
response_code_(URLFetcher::RESPONSE_CODE_INVALID),
buffer_(new IOBuffer(kBufferSize)),
url_request_data_key_(NULL),
was_fetched_via_proxy_(false),
upload_content_set_(false),
upload_range_offset_(0),
upload_range_length_(0),
referrer_policy_(
URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
is_chunked_upload_(false),
was_cancelled_(false),
stop_on_redirect_(false),
stopped_on_redirect_(false),
automatically_retry_on_5xx_(true),
num_retries_on_5xx_(0),
max_retries_on_5xx_(0),
num_retries_on_network_changes_(0),
max_retries_on_network_changes_(0),
current_upload_bytes_(-1),
current_response_bytes_(0),
total_response_bytes_(-1) {
CHECK(original_url_.is_valid());
}
void URLFetcherCore::Start() {
DCHECK(delegate_task_runner_.get());
DCHECK(request_context_getter_.get()) << "We need an URLRequestContext!";
if (network_task_runner_.get()) {
DCHECK_EQ(network_task_runner_,
request_context_getter_->GetNetworkTaskRunner());
} else {
network_task_runner_ = request_context_getter_->GetNetworkTaskRunner();
}
DCHECK(network_task_runner_.get()) << "We need an IO task runner";
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
}
void URLFetcherCore::Stop() {
if (delegate_task_runner_.get()) // May be NULL in tests.
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
delegate_ = NULL;
fetcher_ = NULL;
if (!network_task_runner_.get())
return;
if (network_task_runner_->RunsTasksOnCurrentThread()) {
CancelURLRequest(ERR_ABORTED);
} else {
network_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::CancelURLRequest, this, ERR_ABORTED));
}
}
void URLFetcherCore::SetUploadData(const std::string& upload_content_type,
const std::string& upload_content) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK(upload_content_type_.empty());
// Empty |upload_content_type| is allowed iff the |upload_content| is empty.
DCHECK(upload_content.empty() || !upload_content_type.empty());
upload_content_type_ = upload_content_type;
upload_content_ = upload_content;
upload_content_set_ = true;
}
void URLFetcherCore::SetUploadFilePath(
const std::string& upload_content_type,
const base::FilePath& file_path,
uint64 range_offset,
uint64 range_length,
scoped_refptr<base::TaskRunner> file_task_runner) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK_EQ(upload_range_offset_, 0ULL);
DCHECK_EQ(upload_range_length_, 0ULL);
DCHECK(upload_content_type_.empty());
DCHECK(!upload_content_type.empty());
upload_content_type_ = upload_content_type;
upload_file_path_ = file_path;
upload_range_offset_ = range_offset;
upload_range_length_ = range_length;
upload_file_task_runner_ = file_task_runner;
upload_content_set_ = true;
}
void URLFetcherCore::SetUploadStreamFactory(
const std::string& upload_content_type,
const URLFetcher::CreateUploadStreamCallback& factory) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK(upload_content_type_.empty());
upload_content_type_ = upload_content_type;
upload_stream_factory_ = factory;
upload_content_set_ = true;
}
void URLFetcherCore::SetChunkedUpload(const std::string& content_type) {
if (!is_chunked_upload_) {
AssertHasNoUploadData();
DCHECK(upload_content_type_.empty());
}
// Empty |content_type| is not allowed here, because it is impossible
// to ensure non-empty upload content as it is not yet supplied.
DCHECK(!content_type.empty());
upload_content_type_ = content_type;
upload_content_.clear();
is_chunked_upload_ = true;
}
void URLFetcherCore::AppendChunkToUpload(const std::string& content,
bool is_last_chunk) {
DCHECK(delegate_task_runner_.get());
DCHECK(network_task_runner_.get());
network_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::CompleteAddingUploadDataChunk, this, content,
is_last_chunk));
}
void URLFetcherCore::SetLoadFlags(int load_flags) {
load_flags_ = load_flags;
}
int URLFetcherCore::GetLoadFlags() const {
return load_flags_;
}
void URLFetcherCore::SetReferrer(const std::string& referrer) {
referrer_ = referrer;
}
void URLFetcherCore::SetReferrerPolicy(
URLRequest::ReferrerPolicy referrer_policy) {
referrer_policy_ = referrer_policy;
}
void URLFetcherCore::SetExtraRequestHeaders(
const std::string& extra_request_headers) {
extra_request_headers_.Clear();
extra_request_headers_.AddHeadersFromString(extra_request_headers);
}
void URLFetcherCore::AddExtraRequestHeader(const std::string& header_line) {
extra_request_headers_.AddHeaderFromString(header_line);
}
void URLFetcherCore::SetRequestContext(
URLRequestContextGetter* request_context_getter) {
DCHECK(!request_context_getter_.get());
DCHECK(request_context_getter);
request_context_getter_ = request_context_getter;
}
void URLFetcherCore::SetFirstPartyForCookies(
const GURL& first_party_for_cookies) {
DCHECK(first_party_for_cookies_.is_empty());
first_party_for_cookies_ = first_party_for_cookies;
}
void URLFetcherCore::SetURLRequestUserData(
const void* key,
const URLFetcher::CreateDataCallback& create_data_callback) {
DCHECK(key);
DCHECK(!create_data_callback.is_null());
url_request_data_key_ = key;
url_request_create_data_callback_ = create_data_callback;
}
void URLFetcherCore::SetStopOnRedirect(bool stop_on_redirect) {
stop_on_redirect_ = stop_on_redirect;
}
void URLFetcherCore::SetAutomaticallyRetryOn5xx(bool retry) {
automatically_retry_on_5xx_ = retry;
}
void URLFetcherCore::SetMaxRetriesOn5xx(int max_retries) {
max_retries_on_5xx_ = max_retries;
}
int URLFetcherCore::GetMaxRetriesOn5xx() const {
return max_retries_on_5xx_;
}
base::TimeDelta URLFetcherCore::GetBackoffDelay() const {
return backoff_delay_;
}
void URLFetcherCore::SetAutomaticallyRetryOnNetworkChanges(int max_retries) {
max_retries_on_network_changes_ = max_retries;
}
void URLFetcherCore::SaveResponseToFileAtPath(
const base::FilePath& file_path,
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
SaveResponseWithWriter(scoped_ptr<URLFetcherResponseWriter>(
new URLFetcherFileWriter(file_task_runner, file_path)));
}
void URLFetcherCore::SaveResponseToTemporaryFile(
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
SaveResponseWithWriter(scoped_ptr<URLFetcherResponseWriter>(
new URLFetcherFileWriter(file_task_runner, base::FilePath())));
}
void URLFetcherCore::SaveResponseWithWriter(
scoped_ptr<URLFetcherResponseWriter> response_writer) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
response_writer_ = response_writer.Pass();
}
HttpResponseHeaders* URLFetcherCore::GetResponseHeaders() const {
return response_headers_.get();
}
// TODO(panayiotis): socket_address_ is written in the IO thread,
// if this is accessed in the UI thread, this could result in a race.
// Same for response_headers_ above and was_fetched_via_proxy_ below.
HostPortPair URLFetcherCore::GetSocketAddress() const {
return socket_address_;
}
bool URLFetcherCore::WasFetchedViaProxy() const {
return was_fetched_via_proxy_;
}
const GURL& URLFetcherCore::GetOriginalURL() const {
return original_url_;
}
const GURL& URLFetcherCore::GetURL() const {
return url_;
}
const URLRequestStatus& URLFetcherCore::GetStatus() const {
return status_;
}
int URLFetcherCore::GetResponseCode() const {
return response_code_;
}
const ResponseCookies& URLFetcherCore::GetCookies() const {
return cookies_;
}
void URLFetcherCore::ReceivedContentWasMalformed() {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (network_task_runner_.get()) {
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::NotifyMalformedContent, this));
}
}
bool URLFetcherCore::GetResponseAsString(
std::string* out_response_string) const {
URLFetcherStringWriter* string_writer =
response_writer_ ? response_writer_->AsStringWriter() : NULL;
if (!string_writer)
return false;
*out_response_string = string_writer->data();
UMA_HISTOGRAM_MEMORY_KB("UrlFetcher.StringResponseSize",
(string_writer->data().length() / 1024));
return true;
}
bool URLFetcherCore::GetResponseAsFilePath(bool take_ownership,
base::FilePath* out_response_path) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
URLFetcherFileWriter* file_writer =
response_writer_ ? response_writer_->AsFileWriter() : NULL;
if (!file_writer)
return false;
*out_response_path = file_writer->file_path();
if (take_ownership) {
// Intentionally calling a file_writer_ method directly without posting
// the task to network_task_runner_.
//
// This is for correctly handling the case when file_writer_->DisownFile()
// is soon followed by URLFetcherCore::Stop(). We have to make sure that
// DisownFile takes effect before Stop deletes file_writer_.
//
// This direct call should be thread-safe, since DisownFile itself does no
// file operation. It just flips the state to be referred in destruction.
file_writer->DisownFile();
}
return true;
}
void URLFetcherCore::OnReceivedRedirect(URLRequest* request,
const RedirectInfo& redirect_info,
bool* defer_redirect) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (stop_on_redirect_) {
stopped_on_redirect_ = true;
url_ = redirect_info.new_url;
response_code_ = request_->GetResponseCode();
was_fetched_via_proxy_ = request_->was_fetched_via_proxy();
request->Cancel();
OnReadCompleted(request, 0);
}
}
void URLFetcherCore::OnResponseStarted(URLRequest* request) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_->status().is_success()) {
response_code_ = request_->GetResponseCode();
response_headers_ = request_->response_headers();
socket_address_ = request_->GetSocketAddress();
was_fetched_via_proxy_ = request_->was_fetched_via_proxy();
total_response_bytes_ = request_->GetExpectedContentSize();
}
ReadResponse();
}
void URLFetcherCore::OnCertificateRequested(
URLRequest* request,
SSLCertRequestInfo* cert_request_info) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (g_ignore_certificate_requests) {
request->ContinueWithCertificate(NULL);
} else {
request->Cancel();
}
}
void URLFetcherCore::OnReadCompleted(URLRequest* request,
int bytes_read) {
DCHECK(request == request_);
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!stopped_on_redirect_)
url_ = request->url();
URLRequestThrottlerManager* throttler_manager =
request->context()->throttler_manager();
if (throttler_manager)
url_throttler_entry_ = throttler_manager->RegisterRequestUrl(url_);
do {
if (!request_->status().is_success() || bytes_read <= 0)
break;
current_response_bytes_ += bytes_read;
InformDelegateDownloadProgress();
const int result =
WriteBuffer(new DrainableIOBuffer(buffer_.get(), bytes_read));
if (result < 0) {
// Write failed or waiting for write completion.
return;
}
} while (request_->Read(buffer_.get(), kBufferSize, &bytes_read));
const URLRequestStatus status = request_->status();
if (status.is_success())
request_->GetResponseCookies(&cookies_);
// See comments re: HEAD requests in ReadResponse().
if (!status.is_io_pending() || request_type_ == URLFetcher::HEAD) {
status_ = status;
ReleaseRequest();
// No more data to write.
const int result = response_writer_->Finish(
base::Bind(&URLFetcherCore::DidFinishWriting, this));
if (result != ERR_IO_PENDING)
DidFinishWriting(result);
}
}
void URLFetcherCore::CancelAll() {
g_registry.Get().CancelAll();
}
int URLFetcherCore::GetNumFetcherCores() {
return g_registry.Get().size();
}
void URLFetcherCore::SetIgnoreCertificateRequests(bool ignored) {
g_ignore_certificate_requests = ignored;
}
URLFetcherCore::~URLFetcherCore() {
// |request_| should be NULL. If not, it's unsafe to delete it here since we
// may not be on the IO thread.
DCHECK(!request_.get());
}
void URLFetcherCore::StartOnIOThread() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!response_writer_)
response_writer_.reset(new URLFetcherStringWriter);
const int result = response_writer_->Initialize(
base::Bind(&URLFetcherCore::DidInitializeWriter, this));
if (result != ERR_IO_PENDING)
DidInitializeWriter(result);
}
void URLFetcherCore::StartURLRequest() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_cancelled_) {
// Since StartURLRequest() is posted as a *delayed* task, it may
// run after the URLFetcher was already stopped.
return;
}
DCHECK(request_context_getter_.get());
DCHECK(!request_.get());
g_registry.Get().AddURLFetcherCore(this);
current_response_bytes_ = 0;
request_ = request_context_getter_->GetURLRequestContext()->CreateRequest(
original_url_, DEFAULT_PRIORITY, this);
request_->set_stack_trace(stack_trace_);
int flags = request_->load_flags() | load_flags_;
if (is_chunked_upload_)
request_->EnableChunkedUpload();
request_->SetLoadFlags(flags);
request_->SetReferrer(referrer_);
request_->set_referrer_policy(referrer_policy_);
request_->set_first_party_for_cookies(first_party_for_cookies_.is_empty() ?
original_url_ : first_party_for_cookies_);
if (url_request_data_key_ && !url_request_create_data_callback_.is_null()) {
request_->SetUserData(url_request_data_key_,
url_request_create_data_callback_.Run());
}
switch (request_type_) {
case URLFetcher::GET:
break;
case URLFetcher::POST:
case URLFetcher::PUT:
case URLFetcher::PATCH: {
// Upload content must be set.
DCHECK(is_chunked_upload_ || upload_content_set_);
request_->set_method(
request_type_ == URLFetcher::POST ? "POST" :
request_type_ == URLFetcher::PUT ? "PUT" : "PATCH");
if (!upload_content_type_.empty()) {
extra_request_headers_.SetHeader(HttpRequestHeaders::kContentType,
upload_content_type_);
}
if (!upload_content_.empty()) {
scoped_ptr<UploadElementReader> reader(new UploadBytesElementReader(
upload_content_.data(), upload_content_.size()));
request_->set_upload(
ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
} else if (!upload_file_path_.empty()) {
scoped_ptr<UploadElementReader> reader(
new UploadFileElementReader(upload_file_task_runner_.get(),
upload_file_path_,
upload_range_offset_,
upload_range_length_,
base::Time()));
request_->set_upload(
ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
} else if (!upload_stream_factory_.is_null()) {
scoped_ptr<UploadDataStream> stream = upload_stream_factory_.Run();
DCHECK(stream);
request_->set_upload(stream.Pass());
}
current_upload_bytes_ = -1;
// TODO(kinaba): http://crbug.com/118103. Implement upload callback in the
// layer and avoid using timer here.
upload_progress_checker_timer_.reset(
new base::RepeatingTimer<URLFetcherCore>());
upload_progress_checker_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kUploadProgressTimerInterval),
this,
&URLFetcherCore::InformDelegateUploadProgress);
break;
}
case URLFetcher::HEAD:
request_->set_method("HEAD");
break;
case URLFetcher::DELETE_REQUEST:
request_->set_method("DELETE");
break;
default:
NOTREACHED();
}
if (!extra_request_headers_.IsEmpty())
request_->SetExtraRequestHeaders(extra_request_headers_);
request_->Start();
}
void URLFetcherCore::DidInitializeWriter(int result) {
if (result != OK) {
CancelURLRequest(result);
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
StartURLRequestWhenAppropriate();
}
void URLFetcherCore::StartURLRequestWhenAppropriate() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_cancelled_)
return;
DCHECK(request_context_getter_.get());
int64 delay = 0;
if (!original_url_throttler_entry_.get()) {
URLRequestThrottlerManager* manager =
request_context_getter_->GetURLRequestContext()->throttler_manager();
if (manager) {
original_url_throttler_entry_ =
manager->RegisterRequestUrl(original_url_);
}
}
if (original_url_throttler_entry_.get()) {
delay = original_url_throttler_entry_->ReserveSendingTimeForNextRequest(
GetBackoffReleaseTime());
}
if (delay == 0) {
StartURLRequest();
} else {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartURLRequest, this),
base::TimeDelta::FromMilliseconds(delay));
}
}
void URLFetcherCore::CancelURLRequest(int error) {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_.get()) {
request_->CancelWithError(error);
ReleaseRequest();
}
// Set the error manually.
// Normally, calling URLRequest::CancelWithError() results in calling
// OnReadCompleted() with bytes_read = -1 via an asynchronous task posted by
// URLRequestJob::NotifyDone(). But, because the request was released
// immediately after being canceled, the request could not call
// OnReadCompleted() which overwrites |status_| with the error status.
status_.set_status(URLRequestStatus::CANCELED);
status_.set_error(error);
// Release the reference to the request context. There could be multiple
// references to URLFetcher::Core at this point so it may take a while to
// delete the object, but we cannot delay the destruction of the request
// context.
request_context_getter_ = NULL;
first_party_for_cookies_ = GURL();
url_request_data_key_ = NULL;
url_request_create_data_callback_.Reset();
was_cancelled_ = true;
}
void URLFetcherCore::OnCompletedURLRequest(
base::TimeDelta backoff_delay) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
// Save the status and backoff_delay so that delegates can read it.
if (delegate_) {
backoff_delay_ = backoff_delay;
InformDelegateFetchIsComplete();
}
}
void URLFetcherCore::InformDelegateFetchIsComplete() {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchComplete(fetcher_);
}
void URLFetcherCore::NotifyMalformedContent() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (url_throttler_entry_.get()) {
int status_code = response_code_;
if (status_code == URLFetcher::RESPONSE_CODE_INVALID) {
// The status code will generally be known by the time clients
// call the |ReceivedContentWasMalformed()| function (which ends up
// calling the current function) but if it's not, we need to assume
// the response was successful so that the total failure count
// used to calculate exponential back-off goes up.
status_code = 200;
}
url_throttler_entry_->ReceivedContentWasMalformed(status_code);
}
}
void URLFetcherCore::DidFinishWriting(int result) {
if (result != OK) {
CancelURLRequest(result);
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
// If the file was successfully closed, then the URL request is complete.
RetryOrCompleteUrlFetch();
}
void URLFetcherCore::RetryOrCompleteUrlFetch() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
base::TimeDelta backoff_delay;
// Checks the response from server.
if (response_code_ >= 500 ||
status_.error() == ERR_TEMPORARILY_THROTTLED) {
// When encountering a server error, we will send the request again
// after backoff time.
++num_retries_on_5xx_;
// Note that backoff_delay may be 0 because (a) the
// URLRequestThrottlerManager and related code does not
// necessarily back off on the first error, (b) it only backs off
// on some of the 5xx status codes, (c) not all URLRequestContexts
// have a throttler manager.
base::TimeTicks backoff_release_time = GetBackoffReleaseTime();
backoff_delay = backoff_release_time - base::TimeTicks::Now();
if (backoff_delay < base::TimeDelta())
backoff_delay = base::TimeDelta();
if (automatically_retry_on_5xx_ &&
num_retries_on_5xx_ <= max_retries_on_5xx_) {
StartOnIOThread();
return;
}
} else {
backoff_delay = base::TimeDelta();
}
// Retry if the request failed due to network changes.
if (status_.error() == ERR_NETWORK_CHANGED &&
num_retries_on_network_changes_ < max_retries_on_network_changes_) {
++num_retries_on_network_changes_;
// Retry soon, after flushing all the current tasks which may include
// further network change observers.
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
return;
}
request_context_getter_ = NULL;
first_party_for_cookies_ = GURL();
url_request_data_key_ = NULL;
url_request_create_data_callback_.Reset();
bool posted = delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::OnCompletedURLRequest, this, backoff_delay));
// If the delegate message loop does not exist any more, then the delegate
// should be gone too.
DCHECK(posted || !delegate_);
}
void URLFetcherCore::ReleaseRequest() {
upload_progress_checker_timer_.reset();
request_.reset();
g_registry.Get().RemoveURLFetcherCore(this);
}
base::TimeTicks URLFetcherCore::GetBackoffReleaseTime() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!original_url_throttler_entry_.get())
return base::TimeTicks();
base::TimeTicks original_url_backoff =
original_url_throttler_entry_->GetExponentialBackoffReleaseTime();
base::TimeTicks destination_url_backoff;
if (url_throttler_entry_.get() &&
original_url_throttler_entry_.get() != url_throttler_entry_.get()) {
destination_url_backoff =
url_throttler_entry_->GetExponentialBackoffReleaseTime();
}
return original_url_backoff > destination_url_backoff ?
original_url_backoff : destination_url_backoff;
}
void URLFetcherCore::CompleteAddingUploadDataChunk(
const std::string& content, bool is_last_chunk) {
if (was_cancelled_) {
// Since CompleteAddingUploadDataChunk() is posted as a *delayed* task, it
// may run after the URLFetcher was already stopped.
return;
}
DCHECK(is_chunked_upload_);
DCHECK(request_.get());
DCHECK(!content.empty());
request_->AppendChunkToUpload(content.data(),
static_cast<int>(content.length()),
is_last_chunk);
}
int URLFetcherCore::WriteBuffer(scoped_refptr<DrainableIOBuffer> data) {
while (data->BytesRemaining() > 0) {
const int result = response_writer_->Write(
data.get(),
data->BytesRemaining(),
base::Bind(&URLFetcherCore::DidWriteBuffer, this, data));
if (result < 0) {
if (result != ERR_IO_PENDING)
DidWriteBuffer(data, result);
return result;
}
data->DidConsume(result);
}
return OK;
}
void URLFetcherCore::DidWriteBuffer(scoped_refptr<DrainableIOBuffer> data,
int result) {
if (result < 0) { // Handle errors.
CancelURLRequest(result);
response_writer_->Finish(base::Bind(&EmptyCompletionCallback));
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
// Continue writing.
data->DidConsume(result);
if (WriteBuffer(data) < 0)
return;
// Finished writing buffer_. Read some more, unless the request has been
// cancelled and deleted.
DCHECK_EQ(0, data->BytesRemaining());
if (request_.get())
ReadResponse();
}
void URLFetcherCore::ReadResponse() {
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
int bytes_read = 0;
if (request_->status().is_success() &&
(request_type_ != URLFetcher::HEAD)) {
if (!request_->Read(buffer_.get(), kBufferSize, &bytes_read))
bytes_read = -1; // Match OnReadCompleted() interface contract.
}
OnReadCompleted(request_.get(), bytes_read);
}
void URLFetcherCore::InformDelegateUploadProgress() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_.get()) {
int64 current = request_->GetUploadProgress().position();
if (current_upload_bytes_ != current) {
current_upload_bytes_ = current;
int64 total = -1;
if (!is_chunked_upload_) {
total = static_cast<int64>(request_->GetUploadProgress().size());
// Total may be zero if the UploadDataStream::Init has not been called
// yet. Don't send the upload progress until the size is initialized.
if (!total)
return;
}
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::InformDelegateUploadProgressInDelegateThread,
this, current, total));
}
}
}
void URLFetcherCore::InformDelegateUploadProgressInDelegateThread(
int64 current, int64 total) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchUploadProgress(fetcher_, current, total);
}
void URLFetcherCore::InformDelegateDownloadProgress() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
// TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is fixed.
tracked_objects::ScopedTracker tracking_profile2(
FROM_HERE_WITH_EXPLICIT_FUNCTION(
"455952 delegate_task_runner_->PostTask()"));
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::InformDelegateDownloadProgressInDelegateThread,
this, current_response_bytes_, total_response_bytes_));
}
void URLFetcherCore::InformDelegateDownloadProgressInDelegateThread(
int64 current, int64 total) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchDownloadProgress(fetcher_, current, total);
}
void URLFetcherCore::AssertHasNoUploadData() const {
DCHECK(!upload_content_set_);
DCHECK(upload_content_.empty());
DCHECK(upload_file_path_.empty());
DCHECK(upload_stream_factory_.is_null());
}
} // namespace net
|
ltilve/chromium
|
net/url_request/url_fetcher_core.cc
|
C++
|
bsd-3-clause
| 30,529 |
<?php
class SortWeightRegistry {
public static $override_default_sort = true;
public static $relations = array();
public static $default_sorts = array(); // original default_sort
public static $add_weight_columns = array();
public static $direction = 'ASC'; // ASC || DESC
public static $module_path;
public static function set_module_path($directory)
{
self::$module_path = $directory;
}
public static function decorate($class, $relationName = null) {
if(!isset(self::$relations[$class]))
{
self::$relations[$class] = array();
}
// if relationName is false, enable the sorting on object iteslf (skip SortWeight map)
if(!class_exists($class) || !$sng = new $class())
{
user_error('Unknown class passed (' . $class .')', E_USER_WARNING);
}
elseif($relationName === null )
{
user_error('You must provide the Component to order for ' . $class, E_USER_WARNING);
}
elseif(!$sng->hasMethod($relationName) || !$component = $sng->$relationName())
{
user_error('Component "' . $relationName . '" must exist on ' . $class,E_USER_WARNING);
}
elseif(isset(self::$relations[$class][$relationName]))
{
user_error('Component "' . $relationName . '" already decorates ' . $class,E_USER_WARNING);
}
else
{
$relationClass = ($component->is_a('ComponentSet')) ?
$component->childClass : $component->class;
self::$relations[$class][$relationName] = $relationClass;
$current_sort = Object::get_static($relationClass, 'default_sort');
if(self::$override_default_sort || empty($current_sort))
{
Object::set_static($relationClass,'default_sort','[SortWeight]');
if($current_sort != '[SortWeight]')
{
self::$default_sorts[$relationClass] = $current_sort;
}
}
if(!Object::has_extension($relationClass,'SortWeightDecoration'))
{
Object::add_extension($relationClass,'SortWeightDecoration');
}
return;
}
return user_error('SortWeight decoration failed for ' . __CLASS__ . '::' . __FUNCTION__ . "(\"$class\",\"$relationName\")",E_USER_WARNING);
}
}
|
briceburg/silverstripe-sortweight
|
code/SortWeightRegistry.php
|
PHP
|
bsd-3-clause
| 2,131 |
// Copyright 2018 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_GFX_MOJOM_RRECT_F_MOJOM_TRAITS_H_
#define UI_GFX_MOJOM_RRECT_F_MOJOM_TRAITS_H_
#include "ui/gfx/geometry/mojom/geometry_mojom_traits.h"
#include "ui/gfx/mojom/rrect_f.mojom-shared.h"
#include "ui/gfx/rrect_f.h"
#include "ui/gfx/rrect_f_builder.h"
namespace mojo {
namespace {
gfx::mojom::RRectFType GfxRRectFTypeToMojo(gfx::RRectF::Type type) {
switch (type) {
case gfx::RRectF::Type::kEmpty:
return gfx::mojom::RRectFType::kEmpty;
case gfx::RRectF::Type::kRect:
return gfx::mojom::RRectFType::kRect;
case gfx::RRectF::Type::kSingle:
return gfx::mojom::RRectFType::kSingle;
case gfx::RRectF::Type::kSimple:
return gfx::mojom::RRectFType::kSimple;
case gfx::RRectF::Type::kOval:
return gfx::mojom::RRectFType::kOval;
case gfx::RRectF::Type::kComplex:
return gfx::mojom::RRectFType::kComplex;
}
NOTREACHED();
return gfx::mojom::RRectFType::kEmpty;
}
gfx::RRectF::Type MojoRRectFTypeToGfx(gfx::mojom::RRectFType type) {
switch (type) {
case gfx::mojom::RRectFType::kEmpty:
return gfx::RRectF::Type::kEmpty;
case gfx::mojom::RRectFType::kRect:
return gfx::RRectF::Type::kRect;
case gfx::mojom::RRectFType::kSingle:
return gfx::RRectF::Type::kSingle;
case gfx::mojom::RRectFType::kSimple:
return gfx::RRectF::Type::kSimple;
case gfx::mojom::RRectFType::kOval:
return gfx::RRectF::Type::kOval;
case gfx::mojom::RRectFType::kComplex:
return gfx::RRectF::Type::kComplex;
}
NOTREACHED();
return gfx::RRectF::Type::kEmpty;
}
} // namespace
template <>
struct StructTraits<gfx::mojom::RRectFDataView, gfx::RRectF> {
static gfx::mojom::RRectFType type(const gfx::RRectF& input) {
return GfxRRectFTypeToMojo(input.GetType());
}
static gfx::RectF rect(const gfx::RRectF& input) { return input.rect(); }
static gfx::Vector2dF upper_left(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kUpperLeft);
}
static gfx::Vector2dF upper_right(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kUpperRight);
}
static gfx::Vector2dF lower_right(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kLowerRight);
}
static gfx::Vector2dF lower_left(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kLowerLeft);
}
static bool Read(gfx::mojom::RRectFDataView data, gfx::RRectF* out) {
gfx::RRectF::Type type(MojoRRectFTypeToGfx(data.type()));
gfx::RectF rect;
if (!data.ReadRect(&rect))
return false;
if (type <= gfx::RRectF::Type::kRect) {
*out = gfx::RRectFBuilder().set_rect(rect).Build();
return true;
}
gfx::Vector2dF upper_left;
if (!data.ReadUpperLeft(&upper_left))
return false;
if (type <= gfx::RRectF::Type::kSimple) {
*out = gfx::RRectFBuilder()
.set_rect(rect)
.set_radius(upper_left.x(), upper_left.y())
.Build();
return true;
}
gfx::Vector2dF upper_right;
gfx::Vector2dF lower_right;
gfx::Vector2dF lower_left;
if (!data.ReadUpperRight(&upper_right) ||
!data.ReadLowerRight(&lower_right) ||
!data.ReadLowerLeft(&lower_left)) {
return false;
}
*out = gfx::RRectFBuilder()
.set_rect(rect)
.set_upper_left(upper_left.x(), upper_left.y())
.set_upper_right(upper_right.x(), upper_right.y())
.set_lower_right(lower_right.x(), lower_right.y())
.set_lower_left(lower_left.x(), lower_left.y())
.Build();
return true;
}
};
} // namespace mojo
#endif // UI_GFX_MOJOM_RRECT_F_MOJOM_TRAITS_H_
|
endlessm/chromium-browser
|
ui/gfx/mojom/rrect_f_mojom_traits.h
|
C
|
bsd-3-clause
| 3,912 |
// Copyright 2016 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 "components/password_manager/core/browser/sql_table_builder.h"
#include <algorithm>
#include <set>
#include <utility>
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "sql/database.h"
#include "sql/transaction.h"
namespace password_manager {
namespace {
// Appends |name| to |list_of_names|, separating items with ", ".
void Append(const std::string& name, std::string* list_of_names) {
if (list_of_names->empty())
*list_of_names = name;
else
*list_of_names += ", " + name;
}
} // namespace
// static
unsigned constexpr SQLTableBuilder::kInvalidVersion;
struct SQLTableBuilder::Column {
std::string name;
std::string type;
// Whether this column is the table's PRIMARY KEY.
bool is_primary_key;
// Whether this column is part of the table's UNIQUE constraint.
bool part_of_unique_key;
// The first version this column is part of.
unsigned min_version;
// The last version this column is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
// Renaming of a column is stored as a sequence of one removed and one added
// column in |columns_|. To distinguish it from an unrelated removal and
// addition, the following bit is set to true for the added columns which
// are part of renaming. Those columns will get the data of their
// predecessors. If the bit is false, the column will be filled with the
// default value on creation.
bool gets_previous_data;
};
struct SQLTableBuilder::Index {
// The name of this index.
std::string name;
// The names of columns this index is built from.
std::vector<std::string> columns;
// The first version this index is part of.
unsigned min_version;
// The last version this index is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
};
SQLTableBuilder::SQLTableBuilder(const std::string& table_name)
: table_name_(table_name) {}
SQLTableBuilder::~SQLTableBuilder() = default;
void SQLTableBuilder::AddColumn(std::string name, std::string type) {
DCHECK(FindLastColumnByName(name) == columns_.rend());
columns_.push_back({std::move(name), std::move(type), false, false,
sealed_version_ + 1, kInvalidVersion, false});
}
void SQLTableBuilder::AddPrimaryKeyColumn(std::string name) {
for (const Column& column : columns_) {
DCHECK(!column.is_primary_key);
}
AddColumn(std::move(name), "INTEGER");
columns_.back().is_primary_key = true;
}
void SQLTableBuilder::AddColumnToUniqueKey(std::string name, std::string type) {
AddColumn(std::move(name), std::move(type));
columns_.back().part_of_unique_key = true;
}
void SQLTableBuilder::RenameColumn(const std::string& old_name,
const std::string& new_name) {
auto old_column = FindLastColumnByName(old_name);
DCHECK(old_column != columns_.rend());
if (old_name == new_name) // The easy case.
return;
DCHECK(FindLastColumnByName(new_name) == columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&old_name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, old_name);
}));
if (sealed_version_ != kInvalidVersion &&
old_column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just replaced, it needs to be kept for generating the migration code.
Column new_column = {new_name,
old_column->type,
old_column->is_primary_key,
old_column->part_of_unique_key,
sealed_version_ + 1,
kInvalidVersion,
true};
old_column->max_version = sealed_version_;
auto past_old =
old_column.base(); // Points one element after |old_column|.
columns_.insert(past_old, std::move(new_column));
} else {
// This column was just introduced in the currently unsealed version. To
// rename it, it is enough just to modify the entry in columns_.
old_column->name = new_name;
}
}
// Removes column |name|. |name| must have been added in the past.
void SQLTableBuilder::DropColumn(const std::string& name) {
auto column = FindLastColumnByName(name);
DCHECK(column != columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, name);
}));
if (sealed_version_ != kInvalidVersion &&
column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just deleted, it needs to be kept for generating the migration code.
column->max_version = sealed_version_;
} else {
// This column was just introduced in the currently unsealed version. It
// can be just erased from |columns_|.
columns_.erase(
--(column.base())); // base() points one element after |column|.
}
}
void SQLTableBuilder::AddIndex(std::string name,
std::vector<std::string> columns) {
DCHECK(!columns.empty());
// Check if all entries of |columns| are unique.
DCHECK_EQ(std::set<std::string>(columns.begin(), columns.end()).size(),
columns.size());
// |name| must not have been added before.
DCHECK(FindLastIndexByName(name) == indices_.rend());
// Check that all referenced columns are present in the last version by making
// sure that the inner predicate applies to all columns names in |columns|.
DCHECK(std::all_of(
columns.begin(), columns.end(), [this](const std::string& column_name) {
// Check if there is any column with the required name which is also
// present in the latest version. Note that we don't require the last
// version to be sealed.
return std::any_of(columns_.begin(), columns_.end(),
[&column_name](const Column& column) {
return column.name == column_name &&
column.max_version == kInvalidVersion;
});
}));
indices_.push_back({std::move(name), std::move(columns), sealed_version_ + 1,
kInvalidVersion});
}
std::string SQLTableBuilder::ComputeConstraints(unsigned version) const {
std::string unique_key;
for (const Column& column : columns_) {
// Ignore dropped columns.
if (column.max_version < version)
continue;
// Ignore columns columns from future versions.
if (column.min_version > version)
continue;
if (column.part_of_unique_key)
Append(column.name, &unique_key);
}
std::string constraints;
if (!unique_key.empty())
Append("UNIQUE (" + unique_key + ")", &constraints);
return constraints;
}
unsigned SQLTableBuilder::SealVersion() {
return ++sealed_version_;
}
bool SQLTableBuilder::MigrateFrom(
unsigned old_version,
sql::Database* db,
const base::RepeatingCallback<bool(sql::Database*, unsigned)>&
post_migration_step_callback) const {
for (; old_version < sealed_version_; ++old_version) {
if (!MigrateToNextFrom(old_version, db))
return false;
if (post_migration_step_callback &&
!post_migration_step_callback.Run(db, old_version + 1))
return false;
}
return true;
}
bool SQLTableBuilder::CreateTable(sql::Database* db) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
if (db->DoesTableExist(table_name_.c_str()))
return true;
std::string constraints = ComputeConstraints(sealed_version_);
DCHECK(!constraints.empty() || std::any_of(columns_.begin(), columns_.end(),
[](const Column& column) {
return column.is_primary_key;
}));
std::string names; // Names and types of the current columns.
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column)) {
std::string suffix;
if (column.is_primary_key)
suffix = " PRIMARY KEY AUTOINCREMENT";
Append(column.name + " " + column.type + suffix, &names);
}
}
std::vector<std::string>
create_index_sqls; // CREATE INDEX statements for the current indices.
for (const Index& index : indices_) {
if (IsIndexInLastVersion(index)) {
create_index_sqls.push_back(base::StringPrintf(
"CREATE INDEX %s ON %s (%s)", index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str()));
}
}
std::string create_table_statement =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)", table_name_.c_str(),
names.c_str())
: base::StringPrintf("CREATE TABLE %s (%s, %s)", table_name_.c_str(),
names.c_str(), constraints.c_str());
sql::Transaction transaction(db);
return transaction.Begin() && db->Execute(create_table_statement.c_str()) &&
std::all_of(create_index_sqls.begin(), create_index_sqls.end(),
[&db](const std::string& sql) {
return db->Execute(sql.c_str());
}) &&
transaction.Commit();
}
std::string SQLTableBuilder::ListAllColumnNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column))
Append(column.name, &result);
}
return result;
}
std::string SQLTableBuilder::ListAllNonuniqueKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) &&
!(column.is_primary_key || column.part_of_unique_key))
Append(column.name + "=?", &result);
}
return result;
}
std::string SQLTableBuilder::ListAllUniqueKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) && column.part_of_unique_key) {
if (!result.empty())
result += " AND ";
result += column.name + "=?";
}
}
return result;
}
std::vector<base::StringPiece> SQLTableBuilder::AllPrimaryKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::vector<base::StringPiece> result;
result.reserve(columns_.size());
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) && column.is_primary_key) {
result.emplace_back(column.name);
}
}
DCHECK(result.size() < 2);
return result;
}
size_t SQLTableBuilder::NumberOfColumns() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return base::checked_cast<size_t>(std::count_if(
columns_.begin(), columns_.end(),
[this](const Column& column) { return IsColumnInLastVersion(column); }));
}
bool SQLTableBuilder::MigrateToNextFrom(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK_GE(old_version, 0u);
DCHECK(IsVersionLastAndSealed(sealed_version_));
// Names of columns from old version, values of which are copied. This
// contains only the names without their types.
std::string old_names_of_existing_columns_without_types;
// Names of columns in new version, except for added ones.
std::string new_names_of_existing_columns;
// Names of columns in new version, except for added ones. This contains only
// the names without their types.
std::string new_names_of_existing_columns_without_types;
std::vector<std::string>
names_of_new_columns_list; // Names of added columns.
// A temporary table will be needed if some columns are dropped or renamed,
// because that is not supported by a single SQLite command.
bool needs_temp_table = false;
bool has_primary_key = false;
for (auto column = columns_.begin(); column != columns_.end(); ++column) {
if (column->max_version == old_version) {
// This column was deleted after |old_version|. It can have two reasons:
needs_temp_table = true;
auto next_column = std::next(column);
if (next_column != columns_.end() && next_column->gets_previous_data) {
// (1) The column is being renamed.
DCHECK_EQ(column->type, next_column->type);
DCHECK_NE(column->name, next_column->name);
Append(column->name, &old_names_of_existing_columns_without_types);
Append(next_column->name + " " + next_column->type,
&new_names_of_existing_columns);
Append(next_column->name, &new_names_of_existing_columns_without_types);
++column; // Avoid processing next_column in the next loop.
} else {
// (2) The column is being dropped.
}
} else if (column->min_version == old_version + 1) {
// This column was added after old_version.
if (column->is_primary_key || column->part_of_unique_key)
needs_temp_table = true;
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
names_of_new_columns_list.push_back(column->name + " " + column->type +
suffix);
} else if (column->min_version <= old_version &&
(column->max_version == kInvalidVersion ||
column->max_version > old_version)) {
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
// This column stays.
Append(column->name, &old_names_of_existing_columns_without_types);
Append(column->name + " " + column->type + suffix,
&new_names_of_existing_columns);
Append(column->name, &new_names_of_existing_columns_without_types);
}
}
if (old_names_of_existing_columns_without_types.empty()) {
// Table didn't exist in this version, and nothing to migrate.
return true;
}
if (needs_temp_table) {
// Following the instructions from
// https://www.sqlite.org/lang_altertable.html#otheralter, this code works
// around the fact that SQLite does not allow dropping or renaming
// columns. Instead, a new table is constructed, with the new column
// names, and data from all but dropped columns from the current table are
// copied into it. After that, the new table is renamed to the current
// one.
std::string constraints = ComputeConstraints(old_version + 1);
DCHECK(has_primary_key || !constraints.empty());
// Foreign key constraints are not enabled for the login database, so no
// PRAGMA foreign_keys=off needed.
const std::string temp_table_name = "temp_" + table_name_;
std::string names_of_all_columns = new_names_of_existing_columns;
for (const std::string& new_column : names_of_new_columns_list) {
Append(new_column, &names_of_all_columns);
}
std::string create_table_statement =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)",
temp_table_name.c_str(),
names_of_all_columns.c_str())
: base::StringPrintf(
"CREATE TABLE %s (%s, %s)", temp_table_name.c_str(),
names_of_all_columns.c_str(), constraints.c_str());
sql::Transaction transaction(db);
if (!(transaction.Begin() && db->Execute(create_table_statement.c_str()) &&
db->Execute(base::StringPrintf(
"INSERT OR REPLACE INTO %s (%s) SELECT %s FROM %s",
temp_table_name.c_str(),
new_names_of_existing_columns_without_types.c_str(),
old_names_of_existing_columns_without_types.c_str(),
table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("DROP TABLE %s", table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("ALTER TABLE %s RENAME TO %s",
temp_table_name.c_str(),
table_name_.c_str())
.c_str()) &&
transaction.Commit())) {
return false;
}
} else if (!names_of_new_columns_list.empty()) {
// If no new table has been created, we need to add the new columns here if
// any.
sql::Transaction transaction(db);
if (!(transaction.Begin() &&
std::all_of(names_of_new_columns_list.begin(),
names_of_new_columns_list.end(),
[this, &db](const std::string& name) {
return db->Execute(
base::StringPrintf("ALTER TABLE %s ADD COLUMN %s",
table_name_.c_str(),
name.c_str())
.c_str());
}) &&
transaction.Commit())) {
return false;
}
}
return MigrateIndicesToNextFrom(old_version, db);
}
bool SQLTableBuilder::MigrateIndicesToNextFrom(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK(IsVersionLastAndSealed(sealed_version_));
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
for (const auto& index : indices_) {
std::string sql;
if (index.max_version <= old_version) {
// Index is not supposed to exist in the new version.
sql = base::StringPrintf("DROP INDEX IF EXISTS %s", index.name.c_str());
} else if (index.min_version <= old_version + 1) {
// Index is supposed to exist in the new version.
sql = base::StringPrintf("CREATE INDEX IF NOT EXISTS %s ON %s (%s)",
index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str());
} else {
continue;
}
if (!db->Execute(sql.c_str()))
return false;
}
return transaction.Commit();
}
std::vector<SQLTableBuilder::Column>::reverse_iterator
SQLTableBuilder::FindLastColumnByName(const std::string& name) {
return std::find_if(
columns_.rbegin(), columns_.rend(),
[&name](const Column& column) { return name == column.name; });
}
std::vector<SQLTableBuilder::Index>::reverse_iterator
SQLTableBuilder::FindLastIndexByName(const std::string& name) {
return std::find_if(
indices_.rbegin(), indices_.rend(),
[&name](const Index& index) { return name == index.name; });
}
bool SQLTableBuilder::IsVersionLastAndSealed(unsigned version) const {
// Is |version| the last sealed one?
if (sealed_version_ != version)
return false;
// Is the current version the last sealed one? In other words, is there
// neither a column or index added past the sealed version (min_version >
// sealed) nor deleted one version after the sealed (max_version == sealed)?
return std::none_of(columns_.begin(), columns_.end(),
[this](const Column& column) {
return column.min_version > sealed_version_ ||
column.max_version == sealed_version_;
}) &&
std::none_of(indices_.begin(), indices_.end(),
[this](const Index& index) {
return index.min_version > sealed_version_ ||
index.max_version == sealed_version_;
});
}
bool SQLTableBuilder::IsColumnInLastVersion(const Column& column) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return (column.min_version <= sealed_version_ &&
(column.max_version == kInvalidVersion ||
column.max_version >= sealed_version_));
}
bool SQLTableBuilder::IsIndexInLastVersion(const Index& index) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return (index.min_version <= sealed_version_ &&
(index.max_version == kInvalidVersion ||
index.max_version >= sealed_version_));
}
} // namespace password_manager
|
endlessm/chromium-browser
|
components/password_manager/core/browser/sql_table_builder.cc
|
C++
|
bsd-3-clause
| 21,095 |
# Copyright (c) 2017 David Sorokin <[email protected]>
#
# Licensed under BSD3. See the LICENSE.txt file in the root of this distribution.
from simulation.aivika.modeler.model import *
from simulation.aivika.modeler.port import *
from simulation.aivika.modeler.stream import *
from simulation.aivika.modeler.data_type import *
from simulation.aivika.modeler.pdf import *
def uniform_random_stream(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with random delays distributed uniformly."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomUniformStream ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def uniform_int_random_stream(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with integer random delays distributed uniformly."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomUniformIntStream ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def triangular_random_stream(transact_type, min_delay, median_delay, max_delay):
"""Return a new stream of transacts with random delays having the triangular distribution."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomTriangularStream ' + str(min_delay) + ' ' + str(median_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def normal_random_stream(transact_type, mean_delay, delay_deviation):
"""Return a new stream of transacts with random delays having the normal distribution."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomNormalStream ' + str(mean_delay) + ' ' + str(delay_deviation)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def lognormal_random_stream(transact_type, normal_mean_delay, normal_delay_deviation):
"""Return a new stream of transacts with random delays having the lognormal distribution.
The numerical parameters are related to the normal distribution that
this distribution is derived from.
"""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomLogNormalStream ' + str(normal_mean_delay) + ' ' + str(normal_delay_deviation)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def exponential_random_stream(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the exponential distribution with the specified mean (a reciprocal of the rate)."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomExponentialStream ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def erlang_random_stream(transact_type, scale, shape):
"""Return a new stream of transacts with random delays having the Erlang distribution with the specified scale (a reciprocal of the rate) and shape parameters."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomErlangStream ' + str(scale) + ' ' + str(shape)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def poisson_random_stream(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the Poisson distribution with the specified mean."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomPoissonStream ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def binomial_random_stream(transact_type, probability, trials):
"""Return a new stream of transacts with random delays having the binomial distribution with the specified probability and trials."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomBinomialStream ' + str(probability) + ' ' + str(trials)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def gamma_random_stream(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Gamma distribution by the specified shape and scale."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomGammaStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def beta_random_stream(transact_type, alpha, beta):
"""Return a new stream of transacts with random delays having the Beta distribution by the specified shape parameters (alpha and beta)."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomBetaStream ' + str(alpha) + ' ' + str(beta)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def weibull_random_stream(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Weibull distribution by the specified shape and scale."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomWeibullStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def discrete_random_stream(transact_type, pdf):
"""Return a new stream of transacts with random delays having the discrete distribution by the specified probability density function."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomDiscreteStream ' + encode_pdf(pdf)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
|
dsorokin/aivika-modeler
|
simulation/aivika/modeler/stream_random.py
|
Python
|
bsd-3-clause
| 7,405 |
# apis_v1/documentation_source/voter_star_on_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_star_on_save_doc_template_values(url_root):
"""
Show documentation about voterStarOnSave
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'What is the type of ballot item for which we are saving the \'on\' status? '
'(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this ballot_item '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both. '
'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)',
},
{
'name': 'ballot_item_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this ballot_item across all networks '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both. '
'NOTE: In the future we might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. Missing voter_id while trying to save.',
},
{
'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStarOnSave',
'api_slug': 'voterStarOnSave',
'api_introduction':
"Save or create private 'star on' state for the current voter for a measure, an office or candidate.",
'try_now_link': 'apis_v1:voterStarOnSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
|
wevote/WebAppPublic
|
apis_v1/documentation_source/voter_star_on_save_doc.py
|
Python
|
bsd-3-clause
| 4,125 |
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'],
function (Property, Model, declare, jsonSchemaValidator) {
// module:
// dstore/extensions/JsonSchema
// summary:
// This module generates a dstore schema from a JSON Schema to enabled validation of objects
// and property changes with JSON Schema
return function (jsonSchema) {
// create the schema that can be used by dstore/Model
var modelSchema = {};
var properties = jsonSchema.properties || jsonSchema;
// the validation function, this can be used for all the properties
function checkForErrors() {
var value = this.valueOf();
var key = this.name;
// get the current value and test it against the property's definition
var validation = jsonSchemaValidator.validate(value, properties[key]);
// set any errors
var errors = validation.errors;
if (errors) {
// assign the property names to the errors
for (var i = 0; i < errors.length; i++) {
errors[i].property = key;
}
}
return errors;
}
// iterate through the schema properties, creating property validators
for (var i in properties) {
var jsDefinition = properties[i];
var definition = modelSchema[i] = new Property({
checkForErrors: checkForErrors
});
if (typeof jsDefinition.type === 'string') {
// copy the type so it can be used for coercion
definition.type = jsDefinition.type;
}
if (typeof jsDefinition['default'] === 'string') {
// and copy the default
definition['default'] = jsDefinition['default'];
}
}
return declare(Model, {
schema: modelSchema
});
};
});
|
ibm-js/angular-delite-example
|
bower_components/dstore/extensions/jsonSchema.js
|
JavaScript
|
bsd-3-clause
| 1,633 |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace SqliteExpressionsTest.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
|
NServiceKit/NServiceKit.OrmLite
|
src/XamarinTests/SqliteExpressionsTest.iOS/Main.cs
|
C#
|
bsd-3-clause
| 514 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Competitions;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
|
rsmats13/UMBDT
|
module/Competitions/Module.php
|
PHP
|
bsd-3-clause
| 1,135 |
#include "stdafx.h"
#include "CGGuildApply.h"
BOOL CGGuildApply::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
iStream.Read( (CHAR*)(m_GuildName), m_GuildNameSize );
}
iStream.Read( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
iStream.Read( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
BOOL CGGuildApply::Write( SocketOutputStream& oStream ) const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
oStream.Write( (CHAR*)(m_GuildName), m_GuildNameSize );
}
oStream.Write( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
oStream.Write( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
UINT CGGuildApply::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return CGGuildApplyHandler::Execute( this, pPlayer );
__LEAVE_FUNCTION
return FALSE;
}
|
viticm/web-pap
|
server/Common/Packets/CGGuildApply.cpp
|
C++
|
bsd-3-clause
| 1,209 |
<?php namespace Laravella\Ravel\Facades;
Class Facade
{
protected static $resolvedInstance;
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
throw new \RuntimeException("Facade does not implement getFacadeAccessor method.");
}
/**
* Resolve the facade root instance from the container.
*
* @param string $name
* @return mixed
*/
protected static function resolveFacadeInstance($name)
{
if (is_object($name)) return $name;
if (isset(static::$resolvedInstance[$name]))
{
return static::$resolvedInstance[$name];
}
$NP = ucfirst($name);
$classInstance = "Laravella\\Ravel\\$NP\\$NP";
return static::$resolvedInstance[$name] = new $classInstance;
}
public static function resolveMethod($method, $args)
{
$instance = static::resolveFacadeInstance(static::getFacadeAccessor());
return call_user_func_array(array($instance, $method), $args);
}
public static function __callStatic($method, $args)
{
return static::resolveMethod($method, $args);
}
public function __call($method, $args)
{
return static::resolveMethod($method, $args);
}
}
|
laravella/ravel
|
src/Laravella/Ravel/Facades/Facade.php
|
PHP
|
bsd-3-clause
| 1,183 |
import numpy as np
from nose.tools import (assert_true, assert_false, assert_equal,
assert_almost_equal)
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_)
from dipy.sims.voxel import (_check_directions, SingleTensor, MultiTensor,
multi_tensor_odf, all_tensor_evecs, add_noise,
single_tensor, sticks_and_ball, multi_tensor_dki,
kurtosis_element, DKI_signal)
from dipy.core.geometry import (vec2vec_rotmat, sphere2cart)
from dipy.data import get_data, get_sphere
from dipy.core.gradients import gradient_table
from dipy.io.gradients import read_bvals_bvecs
fimg, fbvals, fbvecs = get_data('small_64D')
bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)
# 2 shells for techniques that requires multishell data
bvals_2s = np.concatenate((bvals, bvals * 2), axis=0)
bvecs_2s = np.concatenate((bvecs, bvecs), axis=0)
gtab_2s = gradient_table(bvals_2s, bvecs_2s)
def diff2eigenvectors(dx, dy, dz):
""" numerical derivatives 2 eigenvectors
"""
u = np.array([dx, dy, dz])
u = u / np.linalg.norm(u)
R = vec2vec_rotmat(basis[:, 0], u)
eig0 = u
eig1 = np.dot(R, basis[:, 1])
eig2 = np.dot(R, basis[:, 2])
eigs = np.zeros((3, 3))
eigs[:, 0] = eig0
eigs[:, 1] = eig1
eigs[:, 2] = eig2
return eigs, R
def test_check_directions():
# Testing spherical angles for two principal coordinate axis
angles = [(0, 0)] # axis z
sticks = _check_directions(angles)
assert_array_almost_equal(sticks, [[0, 0, 1]])
angles = [(0, 90)] # axis z again (phi can be anything it theta is zero)
sticks = _check_directions(angles)
assert_array_almost_equal(sticks, [[0, 0, 1]])
angles = [(90, 0)] # axis x
sticks = _check_directions(angles)
assert_array_almost_equal(sticks, [[1, 0, 0]])
# Testing if directions are already given in cartesian coordinates
angles = [(0, 0, 1)]
sticks = _check_directions(angles)
assert_array_almost_equal(sticks, [[0, 0, 1]])
# Testing more than one direction simultaneously
angles = np.array([[90, 0], [30, 0]])
sticks = _check_directions(angles)
ref_vec = [np.sin(np.pi*30/180), 0, np.cos(np.pi*30/180)]
assert_array_almost_equal(sticks, [[1, 0, 0], ref_vec])
# Testing directions not aligned to planes x = 0, y = 0, or z = 0
the1 = 0
phi1 = 90
the2 = 30
phi2 = 45
angles = np.array([(the1, phi1), (the2, phi2)])
sticks = _check_directions(angles)
ref_vec1 = (np.sin(np.pi*the1/180) * np.cos(np.pi*phi1/180),
np.sin(np.pi*the1/180) * np.sin(np.pi*phi1/180),
np.cos(np.pi*the1/180))
ref_vec2 = (np.sin(np.pi*the2/180) * np.cos(np.pi*phi2/180),
np.sin(np.pi*the2/180) * np.sin(np.pi*phi2/180),
np.cos(np.pi*the2/180))
assert_array_almost_equal(sticks, [ref_vec1, ref_vec2])
def test_sticks_and_ball():
d = 0.0015
S, sticks = sticks_and_ball(gtab, d=d, S0=1, angles=[(0, 0), ],
fractions=[100], snr=None)
assert_array_equal(sticks, [[0, 0, 1]])
S_st = SingleTensor(gtab, 1, evals=[d, 0, 0], evecs=[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]])
assert_array_almost_equal(S, S_st)
def test_single_tensor():
evals = np.array([1.4, .35, .35]) * 10 ** (-3)
evecs = np.eye(3)
S = SingleTensor(gtab, 100, evals, evecs, snr=None)
assert_array_almost_equal(S[gtab.b0s_mask], 100)
assert_(np.mean(S[~gtab.b0s_mask]) < 100)
from dipy.reconst.dti import TensorModel
m = TensorModel(gtab)
t = m.fit(S)
assert_array_almost_equal(t.fa, 0.707, decimal=3)
def test_multi_tensor():
sphere = get_sphere('symmetric724')
vertices = sphere.vertices
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
e0 = np.array([np.sqrt(2) / 2., np.sqrt(2) / 2., 0])
e1 = np.array([0, np.sqrt(2) / 2., np.sqrt(2) / 2.])
mevecs = [all_tensor_evecs(e0), all_tensor_evecs(e1)]
# odf = multi_tensor_odf(vertices, [0.5, 0.5], mevals, mevecs)
# assert_(odf.shape == (len(vertices),))
# assert_(np.all(odf <= 1) & np.all(odf >= 0))
fimg, fbvals, fbvecs = get_data('small_101D')
bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)
s1 = single_tensor(gtab, 100, mevals[0], mevecs[0], snr=None)
s2 = single_tensor(gtab, 100, mevals[1], mevecs[1], snr=None)
Ssingle = 0.5*s1 + 0.5*s2
S, sticks = MultiTensor(gtab, mevals, S0=100, angles=[(90, 45), (45, 90)],
fractions=[50, 50], snr=None)
assert_array_almost_equal(S, Ssingle)
def test_snr():
np.random.seed(1978)
s = single_tensor(gtab)
# For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR
for snr in [5, 10, 20]:
sigma = 1.0 / snr
for j in range(1000):
s_noise = add_noise(s, snr, 1, noise_type='rician')
assert_array_almost_equal(np.var(s_noise - s), sigma ** 2, decimal=2)
def test_all_tensor_evecs():
e0 = np.array([1/np.sqrt(2), 1/np.sqrt(2), 0])
desired = np.array([[1/np.sqrt(2), 1/np.sqrt(2), 0],
[-1/np.sqrt(2), 1/np.sqrt(2), 0],
[0, 0, 1]]).T
assert_array_almost_equal(all_tensor_evecs(e0), desired)
def test_kurtosis_elements():
""" Testing symmetry of the elements of the KT
As an 4th order tensor, KT has 81 elements. However, due to diffusion
symmetry the KT is fully characterized by 15 independent elements. This
test checks for this property.
"""
# two fiber not aligned to planes x = 0, y = 0, or z = 0
mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087],
[0.00099, 0, 0], [0.00226, 0.00087, 0.00087]])
angles = [(80, 10), (80, 10), (20, 30), (20, 30)]
fie = 0.49 # intra axonal water fraction
frac = [fie * 50, (1-fie) * 50, fie * 50, (1-fie) * 50]
sticks = _check_directions(angles)
mD = np.zeros((len(frac), 3, 3))
for i in range(len(frac)):
R = all_tensor_evecs(sticks[i])
mD[i] = np.dot(np.dot(R, np.diag(mevals[i])), R.T)
# compute global DT
D = np.zeros((3, 3))
for i in range(len(frac)):
D = D + frac[i]*mD[i]
# compute voxel's MD
MD = (D[0][0] + D[1][1] + D[2][2]) / 3
# Reference dictionary with the 15 independent elements.
# Note: The multiplication of the indexes (i+1) * (j+1) * (k+1) * (l+1)
# for of an elements is only equal to this multiplication for another
# element if an only if the element corresponds to an symmetry element.
# Thus indexes multiplication is used as key of the reference dictionary
kt_ref = {1: kurtosis_element(mD, frac, 0, 0, 0, 0),
16: kurtosis_element(mD, frac, 1, 1, 1, 1),
81: kurtosis_element(mD, frac, 2, 2, 2, 2),
2: kurtosis_element(mD, frac, 0, 0, 0, 1),
3: kurtosis_element(mD, frac, 0, 0, 0, 2),
8: kurtosis_element(mD, frac, 0, 1, 1, 1),
24: kurtosis_element(mD, frac, 1, 1, 1, 2),
27: kurtosis_element(mD, frac, 0, 2, 2, 2),
54: kurtosis_element(mD, frac, 1, 2, 2, 2),
4: kurtosis_element(mD, frac, 0, 0, 1, 1),
9: kurtosis_element(mD, frac, 0, 0, 2, 2),
36: kurtosis_element(mD, frac, 1, 1, 2, 2),
6: kurtosis_element(mD, frac, 0, 0, 1, 2),
12: kurtosis_element(mD, frac, 0, 1, 1, 2),
18: kurtosis_element(mD, frac, 0, 1, 2, 2)}
# Testing all 81 possible elements
xyz = [0, 1, 2]
for i in xyz:
for j in xyz:
for k in xyz:
for l in xyz:
key = (i+1) * (j+1) * (k+1) * (l+1)
assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l),
kt_ref[key])
# Testing optional funtion inputs
assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l),
kurtosis_element(mD, frac, i, k, j, l,
D, MD))
def test_DKI_simulations_aligned_fibers():
"""
Testing DKI simulations when aligning the same fiber to different axis.
If biological parameters don't change, kt[0] of a fiber aligned to axis x
has to be equal to kt[1] of a fiber aligned to the axis y and equal to
kt[2] of a fiber aligned to axis z. The same is applicable for dt
"""
# Defining parameters based on Neto Henriques et al., 2015. NeuroImage 111
mevals = np.array([[0.00099, 0, 0], # Intra-cellular
[0.00226, 0.00087, 0.00087]]) # Extra-cellular
frac = [49, 51] # Compartment volume fraction
# axis x
angles = [(90, 0), (90, 0)]
signal_fx, dt_fx, kt_fx = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
# axis y
angles = [(90, 90), (90, 90)]
signal_fy, dt_fy, kt_fy = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
# axis z
angles = [(0, 0), (0, 0)]
signal_fz, dt_fz, kt_fz = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]],
[kt_fy[1], kt_fy[0], kt_fy[2]])
assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]],
[kt_fz[2], kt_fz[0], kt_fz[1]])
assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]],
[dt_fy[2], dt_fy[0], dt_fy[5]])
assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]],
[dt_fz[5], dt_fz[0], dt_fz[2]])
# testing S signal along axis x, y and z
bvals = np.array([0, 0, 0, 1000, 1000, 1000, 2000, 2000, 2000])
bvecs = np.asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1],
[1, 0, 0], [0, 1, 0], [0, 0, 1],
[1, 0, 0], [0, 1, 0], [0, 0, 1]])
gtab_axis = gradient_table(bvals, bvecs)
# axis x
S_fx = DKI_signal(gtab_axis, dt_fx, kt_fx, S0=100)
assert_array_almost_equal(S_fx[0:3], [100, 100, 100]) # test S f0r b=0
# axis y
S_fy = DKI_signal(gtab_axis, dt_fy, kt_fy, S0=100)
assert_array_almost_equal(S_fy[0:3], [100, 100, 100]) # test S f0r b=0
# axis z
S_fz = DKI_signal(gtab_axis, dt_fz, kt_fz, S0=100)
assert_array_almost_equal(S_fz[0:3], [100, 100, 100]) # test S f0r b=0
# test S for b = 1000
assert_array_almost_equal([S_fx[3], S_fx[4], S_fx[5]],
[S_fy[4], S_fy[3], S_fy[5]])
assert_array_almost_equal([S_fx[3], S_fx[4], S_fx[5]],
[S_fz[5], S_fz[3], S_fz[4]])
# test S for b = 2000
assert_array_almost_equal([S_fx[6], S_fx[7], S_fx[8]],
[S_fy[7], S_fy[6], S_fy[8]])
assert_array_almost_equal([S_fx[6], S_fx[7], S_fx[8]],
[S_fz[8], S_fz[6], S_fz[7]])
def test_DKI_crossing_fibers_simulations():
""" Testing DKI simulations of a crossing fiber
"""
# two fiber not aligned to planes x = 0, y = 0, or z = 0
mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087],
[0.00099, 0, 0], [0.00226, 0.00087, 0.00087]])
angles = [(80, 10), (80, 10), (20, 30), (20, 30)]
fie = 0.49
frac = [fie*50, (1 - fie)*50, fie*50, (1 - fie)*50]
signal, dt, kt = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac, snr=None)
# in this simulations dt and kt cannot have zero elements
for i in range(len(dt)):
assert dt[i] != 0
for i in range(len(kt)):
assert kt[i] != 0
# test S, dt and kt relative to the expected values computed from another
# DKI package - UDKI (Neto Henriques et al., 2015)
dt_ref = [1.0576161e-3, 0.1292542e-3, 0.4786179e-3,
0.2667081e-3, 0.1136643e-3, 0.9888660e-3]
kt_ref = [2.3529944, 0.8226448, 2.3011221, 0.2017312, -0.0437535,
0.0404011, 0.0355281, 0.2449859, 0.2157668, 0.3495910,
0.0413366, 0.3461519, -0.0537046, 0.0133414, -0.017441]
assert_array_almost_equal(dt, dt_ref)
assert_array_almost_equal(kt, kt_ref)
assert_array_almost_equal(signal,
DKI_signal(gtab_2s, dt_ref, kt_ref, S0=100,
snr=None),
decimal=5)
if __name__ == "__main__":
test_multi_tensor()
|
oesteban/dipy
|
dipy/sims/tests/test_voxel.py
|
Python
|
bsd-3-clause
| 12,904 |
import Ember from 'ember';
import ajax from 'ic-ajax';
import config from '../config/environment';
import SlydApi from '../utils/slyd-api';
import Timer from '../utils/timer';
import ApplicationUtils from '../mixins/application-utils';
var UUID = Ember.Object.extend(ApplicationUtils, {});
export function initialize(container, application) {
application.deferReadiness();
var hash = {};
hash.type = 'GET';
hash.url = (config.SLYD_URL || window.location.protocol + '//' +
window.location.host) + '/server_capabilities';
ajax(hash).then(function(settings) {
this.set('serverCapabilities', settings['capabilities']);
this.set('serverCustomization', settings['custom']);
container.register('api:capabilities',
Ember.Object.create().setProperties(application.get('serverCapabilities')),
{ instantiate: false });
container.register('app:custom',
Ember.Object.create().setProperties(application.get('serverCustomization')),
{ instantiate: false });
var api = new SlydApi();
api.set('username', settings.username);
api.set('sessionid', new UUID().shortGuid());
api.set('serverCapabilities', container.lookup('api:capabilities'));
api.set('timer', new Timer());
container.register('api:slyd', api, { instantiate: false });
application.inject('route', 'slyd', 'api:slyd');
application.inject('adapter', 'slyd', 'api:slyd');
application.inject('controller', 'slyd', 'api:slyd');
application.inject('component', 'slyd', 'api:slyd');
application.inject('controller', 'customizations', 'app:custom');
application.inject('component', 'customizations', 'app:custom');
application.inject('controller', 'capabilities', 'api:capabilities');
application.inject('route', 'capabilities', 'api:capabilities');
this.advanceReadiness();
}.bind(application));
}
export default {
name: 'register-api',
initialize: initialize
};
|
nju520/portia
|
slyd/app/initializers/register-api.js
|
JavaScript
|
bsd-3-clause
| 2,117 |
# License: BSD 3 clause <https://opensource.org/licenses/BSD-3-Clause>
# Copyright (c) 2016, Fabricio Vargas Matos <[email protected]>
# All rights reserved.
''''
Tune the 3 most promissing algorithms and compare them
'''
# Load libraries
import os
import time
import pandas
import numpy
import matplotlib.pyplot as plt
from pandas.tools.plotting import scatter_matrix
from pandas import DataFrame
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn import cross_validation
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCA, NMF
from sklearn.feature_selection import SelectKBest, chi2
import lib.eda1 as eda1
import lib.eda3 as eda3
#constants
N_DIGITS = 3
NUM_FOLDS = 10
RAND_SEED = 7
SCORING = 'accuracy'
VALIDATION_SIZE = 0.20
N_JOBS = 6
#global variables
start = time.clock()
imageidx = 1
createImages = True
results = []
names = []
params = []
bestResults = []
# RandomForestClassifier
def tuneRF(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune LR (Random Forest Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = RandomForestClassifier()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what I want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'RF', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# ExtraTreesClassifier
def tuneET(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune ET (Extra Trees Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = ExtraTreesClassifier()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'ET', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# Tune scaled SVM
def tuneSVM(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune SVM (Support Vector Machines Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#c_values = [0.1, 1.0, 100.0, 10000.0, 100000.0]
c_values = [10000.0, 100000.0]
kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']
param_grid = dict(C=c_values, kernel=kernel_values)
model = SVC()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'SVM', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
def drawTunedAlgorithmsComparison(results, names, outputPath):
global imageidx
print '\n === Tuned Algorithms Comparison ===\n'
#print bestResults
for x in bestResults:
print x
# Compare Algorithms
if (createImages):
fig = plt.figure()
fig.suptitle('Final Tuned-Algorithms Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
#plt.show()
plt.savefig(outputPath + str(imageidx).zfill(N_DIGITS) + '-Tuned-Algorithm-Comparison.png')
imageidx += 1
plt.close('all')
def set_createImages(value):
global createImages
createImages = value
# ===================================================
# ================== main function ==================
# ===================================================
def run(inputFilePath, outputPath, createImagesFlag, dropColumns):
global start
print '####################################################################'
print '############### Running Exploratory Data Analysis #4 ###############'
print '####################################################################'
print ''
set_createImages(createImagesFlag)
start = time.clock()
eda1.reset_imageidx()
eda1.set_createImages(createImagesFlag)
if not os.path.exists(outputPath):
os.makedirs(outputPath)
# Load dataset
dataframe = eda1.loadDataframe(inputFilePath)
# drop out 'not fair' features
dataframe = eda1.dataCleansing(dataframe, dropColumns)
#Split-out train/validation dataset
X_train, X_validation, Y_train, Y_validation = eda1.splitoutValidationDataset(dataframe)
'''
# tune each algorithm
try:
tuneRF(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune RF"
print "Message: %s" % str(e)
try:
tuneET(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune ET"
print "Message: %s" % str(e)
'''
try:
tuneSVM(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune SVM"
print "Message: %s" % str(e)
#print the results comparing the algorithms with the best tune for each one
drawTunedAlgorithmsComparison(results, names, outputPath)
print '\n<<< THEN END - Running Exploratory Data Analysis #4 >>>'
#RF - Best: 0.853451 using {'max_features': 'log2', 'n_estimators': 1000, 'criterion': 'gini'}
#ET - Best: 0.855320 using {'max_features': None, 'n_estimators': 1000, 'criterion': 'gini'}
|
FabricioMatos/ifes-dropout-machine-learning
|
lib/eda4.py
|
Python
|
bsd-3-clause
| 9,696 |
/* $KAME: fsm.h,v 1.2 2005/05/25 01:49:24 keiichi Exp $ */
/*
* Copyright (C) 2004 WIDE Project. 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 project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _SHISAD_FSM_H_
#define _SHISAD_FSM_H_
/* states for the primary fsm. */
#define MIP6_BUL_REG_FSM_STATE_IDLE 0
#define MIP6_BUL_REG_FSM_STATE_RRINIT 1
#define MIP6_BUL_REG_FSM_STATE_RRREDO 2
#define MIP6_BUL_REG_FSM_STATE_RRDEL 3
#define MIP6_BUL_REG_FSM_STATE_WAITA 4
#define MIP6_BUL_REG_FSM_STATE_WAITAR 5
#define MIP6_BUL_REG_FSM_STATE_WAITD 6
#define MIP6_BUL_REG_FSM_STATE_BOUND 7
#define MIP6_BUL_REG_FSM_STATE_DHAAD 8
/* states for the secondary fsm. */
#define MIP6_BUL_RR_FSM_STATE_START 0
#define MIP6_BUL_RR_FSM_STATE_WAITHC 1
#define MIP6_BUL_RR_FSM_STATE_WAITH 2
#define MIP6_BUL_RR_FSM_STATE_WAITC 3
#define MIP6_BUL_IS_RR_FSM_RUNNING(bul) \
(((bul)->bul_rr_fsm_state == MIP6_BUL_RR_FSM_STATE_WAITHC) \
|| ((bul)->bul_rr_fsm_state == MIP6_BUL_RR_FSM_STATE_WAITH) \
|| ((bul)->bul_rr_fsm_state == MIP6_BUL_RR_FSM_STATE_WAITC))
/* events for the registration fsm. */
#define MIP6_BUL_FSM_EVENT_MOVEMENT 0
#define MIP6_BUL_FSM_EVENT_RETURNING_HOME 1
#define MIP6_BUL_FSM_EVENT_REVERSE_PACKET 2
#define MIP6_BUL_FSM_EVENT_RR_DONE 3
#define MIP6_BUL_FSM_EVENT_RR_FAILED 4
#define MIP6_BUL_FSM_EVENT_BRR 5
#define MIP6_BUL_FSM_EVENT_BACK 6
#define MIP6_BUL_FSM_EVENT_REGISTERED 7
#define MIP6_BUL_FSM_EVENT_DEREGISTERED 8
#define MIP6_BUL_FSM_EVENT_UNKNOWN_HAO 9
#define MIP6_BUL_FSM_EVENT_UNKNOWN_MH 10
#define MIP6_BUL_FSM_EVENT_ICMP6_PARAM_PROB 11
#define MIP6_BUL_FSM_EVENT_EXPIRE_TIMER 12
#define MIP6_BUL_FSM_EVENT_DHAAD_REPLY 13
#define MIP6_BUL_IS_REG_FSM_EVENT(ev) \
(((ev) >= 0) \
&& ((ev) <= MIP6_BUL_FSM_EVENT_DHAAD_REPLY))
/* events for the rr fsm. */
#define MIP6_BUL_FSM_EVENT_START_RR 20
#define MIP6_BUL_FSM_EVENT_START_HOME_RR 21
#define MIP6_BUL_FSM_EVENT_STOP_RR 22
#define MIP6_BUL_FSM_EVENT_HOT 23
#define MIP6_BUL_FSM_EVENT_COT 24
#define MIP6_BUL_IS_RR_FSM_EVENT(ev) \
(((ev) >= MIP6_BUL_FSM_EVENT_START_RR) \
&& (((ev) <= MIP6_BUL_FSM_EVENT_COT)))
/* timeout events */
#define MIP6_BUL_FSM_EVENT_RETRANS_TIMER 30
struct fsm_message {
struct in6_addr *fsmm_src;
struct in6_addr *fsmm_dst;
struct in6_addr *fsmm_hoa;
struct in6_addr *fsmm_rtaddr;
void *fsmm_data;
size_t fsmm_datalen;
};
int bul_kick_fsm_by_mh(struct in6_addr *, struct in6_addr *, struct in6_addr *,
struct in6_addr *, struct ip6_mh *, int);
int bul_kick_fsm(struct binding_update_list *, int, struct fsm_message *);
void bul_retrans_timer(void *);
void bul_expire_timer(void *);
#endif /* !_SHISAD_FSM_H_ */
|
MarginC/kame
|
kame/kame/shisad/fsm.h
|
C
|
bsd-3-clause
| 4,097 |
import numpy as np
from scipy.linalg import norm
from .base import AppearanceLucasKanade
class SimultaneousForwardAdditive(AppearanceLucasKanade):
@property
def algorithm(self):
return 'Simultaneous-FA'
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = self.appearance_model._jacobian.T
# Forward Additive Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute warp Jacobian
dW_dp = self.transform.jacobian(
self.template.mask.true_indices)
# Compute steepest descent images, VI_dW_dp
J = self.residual.steepest_descent_images(
image, dW_dp, forward=(self.template, self.transform,
self.interpolator))
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.steepest_descent_update(
self._J, self.template, IWxp)
# Compute gradient descent parameter updates
delta_p = np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
parameters = self.transform.as_vector() + delta_p[:n_params]
self.transform.from_vector_inplace(parameters)
lk_fitting.parameters.append(parameters)
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
class SimultaneousForwardCompositional(AppearanceLucasKanade):
@property
def algorithm(self):
return 'Simultaneous-FC'
def _set_up(self):
# Compute warp Jacobian
self._dW_dp = self.transform.jacobian(
self.template.mask.true_indices)
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = self.appearance_model._jacobian.T
# Forward Additive Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute steepest descent images, VI_dW_dp
J = self.residual.steepest_descent_images(IWxp, self._dW_dp)
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.steepest_descent_update(
self._J, self.template, IWxp)
# Compute gradient descent parameter updates
delta_p = np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
self.transform.compose_after_from_vector_inplace(delta_p[:n_params])
lk_fitting.parameters.append(self.transform.as_vector())
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
class SimultaneousInverseCompositional(AppearanceLucasKanade):
@property
def algorithm(self):
return 'Simultaneous-IA'
def _set_up(self):
# Compute the Jacobian of the warp
self._dW_dp = self.transform.jacobian(
self.appearance_model.mean.mask.true_indices)
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = -self.appearance_model._jacobian.T
# Baker-Matthews, Inverse Compositional Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute steepest descent images, VT_dW_dp
J = self.residual.steepest_descent_images(self.template,
self._dW_dp)
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.steepest_descent_update(
self._J, IWxp, self.template)
# Compute gradient descent parameter updates
delta_p = -np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
self.transform.compose_after_from_vector_inplace(delta_p[:n_params])
lk_fitting.parameters.append(self.transform.as_vector())
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
|
jabooth/menpo-archive
|
menpo/fit/lucaskanade/appearance/simultaneous.py
|
Python
|
bsd-3-clause
| 8,583 |
package org.cagrid.gme.common.exceptions;
import java.io.IOException;
@SuppressWarnings("serial")
public class SchemaParsingException extends IOException {
public SchemaParsingException() {
super();
}
public SchemaParsingException(String s) {
super(s);
}
}
|
NCIP/cagrid
|
cagrid/Software/core/caGrid/projects/globalModelExchange/src/org/cagrid/gme/common/exceptions/SchemaParsingException.java
|
Java
|
bsd-3-clause
| 296 |
// Copyright 2018 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_EVENTS_ANDROID_EVENT_HANDLER_ANDROID_H_
#define UI_EVENTS_ANDROID_EVENT_HANDLER_ANDROID_H_
#include "ui/events/events_export.h"
namespace ui {
class DragEventAndroid;
class GestureEventAndroid;
class KeyEventAndroid;
class MotionEventAndroid;
// Dispatches events to appropriate targets. The default implementations of
// all of the specific handlers do nothing. Implementations should set
// themselves to the ViewAndroid in the view tree to get the calls routed.
// Use bool return type to stop propagating the call i.e. overriden method
// should return true to indicate that the event was handled and stop
// the processing.
class EVENTS_EXPORT EventHandlerAndroid {
public:
virtual bool OnDragEvent(const DragEventAndroid& event);
virtual bool OnTouchEvent(const MotionEventAndroid& event);
virtual bool OnMouseEvent(const MotionEventAndroid& event);
virtual bool OnMouseWheelEvent(const MotionEventAndroid& event);
virtual bool OnGestureEvent(const GestureEventAndroid& event);
virtual void OnSizeChanged();
virtual void OnPhysicalBackingSizeChanged();
virtual void OnBrowserControlsHeightChanged();
virtual bool OnGenericMotionEvent(const MotionEventAndroid& event);
virtual bool OnKeyUp(const KeyEventAndroid& event);
virtual bool DispatchKeyEvent(const KeyEventAndroid& event);
virtual bool ScrollBy(float delta_x, float delta_y);
virtual bool ScrollTo(float x, float y);
};
} // namespace ui
#endif // UI_EVENTS_ANDROID_EVENT_HANDLER_ANDROID_H_
|
endlessm/chromium-browser
|
ui/events/android/event_handler_android.h
|
C
|
bsd-3-clause
| 1,668 |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDynamic2DLabelMapper.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkDynamic2DLabelMapper - draw text labels at 2D dataset points
// .SECTION Description
// vtkDynamic2DLabelMapper is a mapper that renders text at dataset
// points such that the labels do not overlap.
// Various items can be labeled including point ids, scalars,
// vectors, normals, texture coordinates, tensors, and field data components.
// This mapper assumes that the points are located on the x-y plane
// and that the camera remains perpendicular to that plane with a y-up
// axis (this can be constrained using vtkImageInteractor).
// On the first render, the mapper computes the visiblility of all labels
// at all scales, and queries this information on successive renders.
// This causes the first render to be much slower. The visibility algorithm
// is a greedy approach based on the point id, so the label for a point
// will be drawn unless the label for a point with lower id overlaps it.
// .SECTION Caveats
// Use this filter in combination with vtkSelectVisiblePoints if you want
// to label only points that are visible. If you want to label cells rather
// than points, use the filter vtkCellCenters to generate points at the
// center of the cells. Also, you can use the class vtkIdFilter to
// generate ids as scalars or field data, which can then be labeled.
// .SECTION See Also
// vtkLabeledDataMapper
// .SECTION Thanks
// This algorithm was developed in the paper
// Ken Been and Chee Yap. Dynamic Map Labeling. IEEE Transactions on
// Visualization and Computer Graphics, Vol. 12, No. 5, 2006. pp. 773-780.
#ifndef __vtkDynamic2DLabelMapper_h
#define __vtkDynamic2DLabelMapper_h
#include "vtkRenderingCoreExport.h" // For export macro
#include "vtkLabeledDataMapper.h"
class VTKRENDERINGCORE_EXPORT vtkDynamic2DLabelMapper : public vtkLabeledDataMapper
{
public:
// Description:
// Instantiate object with %%-#6.3g label format. By default, point ids
// are labeled.
static vtkDynamic2DLabelMapper *New();
vtkTypeMacro(vtkDynamic2DLabelMapper, vtkLabeledDataMapper);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the points array name to use to give priority to labels.
// Defaults to "priority".
void SetPriorityArrayName(const char* name);
// Description:
// Whether to reverse the priority order (i.e. low values have high priority).
// Default is off.
vtkSetMacro(ReversePriority, bool);
vtkGetMacro(ReversePriority, bool);
vtkBooleanMacro(ReversePriority, bool);
// Description:
// Set the label height padding as a percentage. The percentage
// is a percentage of your label height.
// Default is 50%.
vtkSetMacro(LabelHeightPadding, float);
vtkGetMacro(LabelHeightPadding, float);
// Description:
// Set the label width padding as a percentage. The percentage
// is a percentage of your label ^height^ (yes, not a typo).
// Default is 50%.
vtkSetMacro(LabelWidthPadding, float);
vtkGetMacro(LabelWidthPadding, float);
// Description:
// Draw non-overlapping labels to the screen.
void RenderOpaqueGeometry(vtkViewport* viewport, vtkActor2D* actor);
void RenderOverlay(vtkViewport *viewport, vtkActor2D *actor);
protected:
vtkDynamic2DLabelMapper();
~vtkDynamic2DLabelMapper();
// Description:
// Calculate the current zoom scale of the viewport.
double GetCurrentScale(vtkViewport *viewport);
float* LabelWidth;
float* LabelHeight;
float* Cutoff;
float ReferenceScale;
float LabelHeightPadding;
float LabelWidthPadding;
bool ReversePriority;
private:
vtkDynamic2DLabelMapper(const vtkDynamic2DLabelMapper&); // Not implemented.
void operator=(const vtkDynamic2DLabelMapper&); // Not implemented.
};
#endif
|
cjh1/vtkmodular
|
Rendering/Core/vtkDynamic2DLabelMapper.h
|
C
|
bsd-3-clause
| 4,627 |
require 'erb'
describe "ERB.new" do
before :all do
@eruby_str = <<'END'
<ul>
<% list = [1,2,3] %>
<% for item in list %>
<% if item %>
<li><%= item %></li>
<% end %>
<% end %>
</ul>
END
@eruby_str2 = <<'END'
<ul>
% list = [1,2,3]
%for item in list
% if item
<li><%= item %>
<% end %>
<% end %>
</ul>
%%%
END
end
it "compiles eRuby script into ruby code when trim mode is 0 or not specified" do
expected = "<ul>\n\n\n\n<li>1</li>\n\n\n\n<li>2</li>\n\n\n\n<li>3</li>\n\n\n</ul>\n"
[0, '', nil].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes '\n' when trim_mode is 1 or '>'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>\n"
[1, '>'].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes spaces at beginning of line and '\n' when trim_mode is 2 or '<>'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>\n"
[2, '<>'].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes spaces around '<%- -%>' when trim_mode is '-'" do
expected = "<ul>\n <li>1 <li>2 <li>3</ul>\n"
input = <<'END'
<ul>
<%- for item in [1,2,3] -%>
<%- if item -%>
<li><%= item -%>
<%- end -%>
<%- end -%>
</ul>
END
ERB.new(input, nil, '-').result.should == expected
end
it "not support '<%-= expr %> even when trim_mode is '-'" do
input = <<'END'
<p>
<%= expr -%>
<%-= expr -%>
</p>
END
lambda { ERB.new(input, nil, '-').result }.should raise_error
end
ruby_bug "#213", "1.8.7" do
it "regards lines starting with '%' as '<% ... %>' when trim_mode is '%'" do
expected = "<ul>\n <li>1\n \n <li>2\n \n <li>3\n \n\n</ul>\n%%\n"
ERB.new(@eruby_str2, nil, "%").result.should == expected
end
end
it "regards lines starting with '%' as '<% ... %>' and remove \"\\n\" when trim_mode is '%>'" do
expected = "<ul>\n <li>1 <li>2 <li>3 </ul>\n%%\n"
ERB.new(@eruby_str2, nil, '%>').result.should == expected
end
it "regard lines starting with '%' as '<% ... %>' and remove \"\\n\" when trim_mode is '%<>'" do
expected = "<ul>\n <li>1\n \n <li>2\n \n <li>3\n \n</ul>\n%%\n"
ERB.new(@eruby_str2, nil, '%<>').result.should == expected
end
it "regard lines starting with '%' as '<% ... %>' and spaces around '<%- -%>' when trim_mode is '%-'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n</ul>\n%%\n"
input = <<'END'
<ul>
%list = [1,2]
%for item in list
<li><%= item %></li>
<% end %></ul>
%%%
END
trim_mode = '%-'
ERB.new(input, nil, '%-').result.should == expected
end
not_compliant_on :rubinius do
it "accepts a safe level as second argument" do
input = "<b><%=- 2+2 %>"
safe_level = 3
lambda { ERB.new(input, safe_level).result }.should_not raise_error
end
end
it "changes '_erbout' variable name in the produced source" do
input = @eruby_str
match_erbout = ERB.new(input, nil, nil).src
match_buf = ERB.new(input, nil, nil, 'buf').src
match_erbout.gsub("_erbout", "buf").should == match_buf
end
it "ignores '<%# ... %>'" do
input = <<'END'
<%# for item in list %>
<b><%#= item %></b>
<%# end %>
END
ERB.new(input).result.should == "\n<b></b>\n\n"
ERB.new(input, nil, '<>').result.should == "<b></b>\n"
end
ruby_version_is ""..."2.0" do
it "remember local variables defined previous one" do
ERB.new(@eruby_str).result
ERB.new("<%= list.inspect %>").result.should == "[1, 2, 3]"
end
end
ruby_version_is "2.0" do
it "forget local variables defined previous one" do
ERB.new(@eruby_str).result
lambda{ ERB.new("<%= list %>").result }.should raise_error(NameError)
end
end
end
|
rubysl/rubysl-erb
|
spec/new_spec.rb
|
Ruby
|
bsd-3-clause
| 3,851 |
/*
* Copyright (C) 2013 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 "config.h"
#include "HTMLMediaSource.h"
namespace WebCore {
URLRegistry* HTMLMediaSource::s_registry = 0;
void HTMLMediaSource::setRegistry(URLRegistry* registry)
{
ASSERT(!s_registry);
s_registry = registry;
}
}
|
klim-iv/phantomjs-qt5
|
src/webkit/Source/WebCore/html/HTMLMediaSource.cpp
|
C++
|
bsd-3-clause
| 1,798 |
/***************************************************************************
* Copyright (C) 2008 by Ralf Kaestner *
* [email protected] *
* *
* 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. *
***************************************************************************/
#ifndef CAN_H
#define CAN_H
/** \file
* \brief Generic CAN communication
* Common commands used to communicate via the CAN protocol.
* These methods are implemented by all CAN communication backends.
*/
#include <tulibs/config.h>
/** Predefined CAN constants
*/
#define CAN_CONFIG_ARG_PREFIX "can"
/** Predefined CAN error codes
*/
#define CAN_ERROR_NONE 0
#define CAN_ERROR_OPEN 1
#define CAN_ERROR_SETUP 2
#define CAN_ERROR_CLOSE 3
#define CAN_ERROR_SEND 4
#define CAN_ERROR_RECEIVE 5
/** \brief Predefined CAN error descriptions
*/
extern const char* can_errors[];
/** \brief Structure defining a CAN message
*/
typedef struct can_message_t {
int id; //!< The CAN message identifier.
unsigned char content[8]; //!< The actual CAN message content.
ssize_t length; //!< The length of the CAN message.
} can_message_t, *can_message_p;
/** \brief Structure defining a CAN device
*/
typedef struct can_device_t {
void* comm_dev; //!< The CAN communication device.
config_t config; //!< The CAN configuration parameters.
ssize_t num_references; //!< Number of references to this device.
ssize_t num_sent; //!< The number of CAN messages sent.
ssize_t num_received; //!< The number of CAN messages read.
} can_device_t, *can_device_p;
/** \brief Predefined CAN default configuration
*/
extern config_t can_default_config;
/** \brief Initialize CAN device
* \param[in] dev The CAN device to be initialized.
* \param[in] config The optional CAN device configuration parameters.
* Can be null.
*/
void can_init(
can_device_p dev,
config_p config);
/** \brief Initialize CAN device from command line arguments
* \param[in] dev The CAN device to be initialized.
* \param[in] argc The number of supplied command line arguments.
* \param[in] argv The list of supplied command line arguments.
* \param[in] prefix An optional argument prefix.
*/
void can_init_arg(
can_device_p dev,
int argc,
char **argv,
const char* prefix);
/** \brief Destroy an existing CAN device
* \param[in] dev The CAN device to be destroyed.
*/
void can_destroy(
can_device_p dev);
/** \brief Open CAN communication
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The initialized CAN device to be opened.
* \return The resulting error code.
*/
int can_open(
can_device_p dev);
/** \brief Close CAN communication
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The opened CAN device to be closed.
* \return The resulting error code.
*/
int can_close(
can_device_p dev);
/** \brief Send a CAN message
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The CAN device to be used for sending the message.
* \param[in] message The CAN message to be sent.
* \return The resulting error code.
*/
int can_send_message(
can_device_p dev,
can_message_p message);
/** \brief Synchronously receive a CAN message
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The CAN device to be used for receiving the message.
* \param[in,out] message The sent CAN message that will be transformed
* into the CAN message received.
* \return The resulting error code.
*/
int can_receive_message(
can_device_p dev,
can_message_p message);
#endif
|
NIFTi-Fraunhofer/nifti_arm
|
libcan/src/can/can.h
|
C
|
bsd-3-clause
| 5,084 |
/* Copyright (c) 2009, University of Oslo, Norway
* 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 University of Oslo 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 vtk.text.tl.expr;
import java.math.BigDecimal;
import vtk.text.tl.Symbol;
public class Multiply extends NumericOperator {
public Multiply(Symbol symbol) {
super(symbol);
}
@Override
protected Object evalNumeric(BigDecimal n1, BigDecimal n2) {
return n1.multiply(n2);
}
}
|
vtkio/vtk
|
src/main/java/vtk/text/tl/expr/Multiply.java
|
Java
|
bsd-3-clause
| 1,929 |
// 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.
//
// Definition of ModelTypePayloadMap and various utility functions.
#ifndef SYNC_INTERNAL_PUBLIC_API_BASE_MODEL_TYPE_PAYLOAD_MAP_H_
#define SYNC_INTERNAL_PUBLIC_API_BASE_MODEL_TYPE_PAYLOAD_MAP_H_
#include <map>
#include <string>
#include "sync/base/sync_export.h"
#include "sync/internal_api/public/base/model_type.h"
// TODO(akalin): Move the non-exported functions in this file to a
// private header.
namespace base {
class DictionaryValue;
}
namespace syncer {
// A container that contains a set of datatypes with possible string
// payloads.
typedef std::map<ModelType, std::string> ModelTypePayloadMap;
// Helper functions for building ModelTypePayloadMaps.
// Make a TypePayloadMap from all the types in a ModelTypeSet using a
// default payload.
SYNC_EXPORT ModelTypePayloadMap ModelTypePayloadMapFromEnumSet(
ModelTypeSet model_types, const std::string& payload);
ModelTypeSet ModelTypePayloadMapToEnumSet(
const ModelTypePayloadMap& payload_map);
std::string ModelTypePayloadMapToString(
const ModelTypePayloadMap& model_type_payloads);
// Caller takes ownership of the returned dictionary.
base::DictionaryValue* ModelTypePayloadMapToValue(
const ModelTypePayloadMap& model_type_payloads);
// Coalesce |update| into |original|, overwriting only when |update| has
// a non-empty payload.
void CoalescePayloads(ModelTypePayloadMap* original,
const ModelTypePayloadMap& update);
} // namespace syncer
#endif // SYNC_INTERNAL_PUBLIC_API_BASE_MODEL_TYPE_PAYLOAD_MAP_H_
|
keishi/chromium
|
sync/internal_api/public/base/model_type_payload_map.h
|
C
|
bsd-3-clause
| 1,702 |
# 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.
"""Provides fakes for several of Telemetry's internal objects.
These allow code like story_runner and Benchmark to be run and tested
without compiling or starting a browser. Class names prepended with an
underscore are intended to be implementation details, and should not
be subclassed; however, some, like _FakeBrowser, have public APIs that
may need to be called in tests.
"""
from telemetry.internal.backends.chrome_inspector import websocket
from telemetry.internal.browser import browser_options
from telemetry.internal.platform import system_info
from telemetry.page import shared_page_state
from telemetry.util import image_util
from telemetry.testing.internal import fake_gpu_info
from types import ModuleType
# Classes and functions which are intended to be part of the public
# fakes API.
class FakePlatform(object):
def __init__(self):
self._network_controller = None
self._tracing_controller = None
self._has_battor = False
self._os_name = 'FakeOS'
self._device_type_name = 'abc'
self._is_svelte = False
self._is_aosp = True
@property
def is_host_platform(self):
raise NotImplementedError
@property
def network_controller(self):
if self._network_controller is None:
self._network_controller = _FakeNetworkController()
return self._network_controller
@property
def tracing_controller(self):
if self._tracing_controller is None:
self._tracing_controller = _FakeTracingController()
return self._tracing_controller
def Initialize(self):
pass
def CanMonitorThermalThrottling(self):
return False
def IsThermallyThrottled(self):
return False
def HasBeenThermallyThrottled(self):
return False
def GetArchName(self):
raise NotImplementedError
def SetOSName(self, name):
self._os_name = name
def GetOSName(self):
return self._os_name
def GetOSVersionName(self):
raise NotImplementedError
def GetOSVersionDetailString(self):
raise NotImplementedError
def StopAllLocalServers(self):
pass
def WaitForBatteryTemperature(self, _):
pass
def HasBattOrConnected(self):
return self._has_battor
def SetBattOrDetected(self, b):
assert isinstance(b, bool)
self._has_battor = b
# TODO(rnephew): Investigate moving from setters to @property.
def SetDeviceTypeName(self, name):
self._device_type_name = name
def GetDeviceTypeName(self):
return self._device_type_name
def SetIsSvelte(self, b):
assert isinstance(b, bool)
self._is_svelte = b
def IsSvelte(self):
if self._os_name != 'android':
raise NotImplementedError
return self._is_svelte
def SetIsAosp(self, b):
assert isinstance(b, bool)
self._is_aosp = b
def IsAosp(self):
return self._is_aosp and self._os_name == 'android'
class FakeLinuxPlatform(FakePlatform):
def __init__(self):
super(FakeLinuxPlatform, self).__init__()
self.screenshot_png_data = None
self.http_server_directories = []
self.http_server = FakeHTTPServer()
@property
def is_host_platform(self):
return True
def GetDeviceTypeName(self):
return 'Desktop'
def GetArchName(self):
return 'x86_64'
def GetOSName(self):
return 'linux'
def GetOSVersionName(self):
return 'trusty'
def GetOSVersionDetailString(self):
return ''
def CanTakeScreenshot(self):
return bool(self.screenshot_png_data)
def TakeScreenshot(self, file_path):
if not self.CanTakeScreenshot():
raise NotImplementedError
img = image_util.FromBase64Png(self.screenshot_png_data)
image_util.WritePngFile(img, file_path)
return True
def SetHTTPServerDirectories(self, paths):
self.http_server_directories.append(paths)
class FakeHTTPServer(object):
def UrlOf(self, url):
del url # unused
return 'file:///foo'
class FakePossibleBrowser(object):
def __init__(self, execute_on_startup=None,
execute_after_browser_creation=None):
self._returned_browser = _FakeBrowser(FakeLinuxPlatform())
self.browser_type = 'linux'
self.supports_tab_control = False
self.is_remote = False
self.execute_on_startup = execute_on_startup
self.execute_after_browser_creation = execute_after_browser_creation
@property
def returned_browser(self):
"""The browser object that will be returned through later API calls."""
return self._returned_browser
def Create(self, finder_options):
if self.execute_on_startup is not None:
self.execute_on_startup()
del finder_options # unused
if self.execute_after_browser_creation is not None:
self.execute_after_browser_creation(self._returned_browser)
return self.returned_browser
@property
def platform(self):
"""The platform object from the returned browser.
To change this or set it up, change the returned browser's
platform.
"""
return self.returned_browser.platform
def IsRemote(self):
return self.is_remote
def SetCredentialsPath(self, _):
pass
class FakeSharedPageState(shared_page_state.SharedPageState):
def __init__(self, test, finder_options, story_set):
super(FakeSharedPageState, self).__init__(test, finder_options, story_set)
def _GetPossibleBrowser(self, test, finder_options):
p = FakePossibleBrowser()
self.ConfigurePossibleBrowser(p)
return p
def ConfigurePossibleBrowser(self, possible_browser):
"""Override this to configure the PossibleBrowser.
Can make changes to the browser's configuration here via e.g.:
possible_browser.returned_browser.returned_system_info = ...
"""
pass
def DidRunStory(self, results):
# TODO(kbr): add a test which throws an exception from DidRunStory
# to verify the fix from https://crrev.com/86984d5fc56ce00e7b37ebe .
super(FakeSharedPageState, self).DidRunStory(results)
class FakeSystemInfo(system_info.SystemInfo):
def __init__(self, model_name='', gpu_dict=None, command_line=''):
if gpu_dict == None:
gpu_dict = fake_gpu_info.FAKE_GPU_INFO
super(FakeSystemInfo, self).__init__(model_name, gpu_dict, command_line)
class _FakeBrowserFinderOptions(browser_options.BrowserFinderOptions):
def __init__(self, execute_on_startup=None,
execute_after_browser_creation=None, *args, **kwargs):
browser_options.BrowserFinderOptions.__init__(self, *args, **kwargs)
self.fake_possible_browser = \
FakePossibleBrowser(
execute_on_startup=execute_on_startup,
execute_after_browser_creation=execute_after_browser_creation)
def CreateBrowserFinderOptions(browser_type=None, execute_on_startup=None,
execute_after_browser_creation=None):
"""Creates fake browser finder options for discovering a browser."""
return _FakeBrowserFinderOptions(
browser_type=browser_type,
execute_on_startup=execute_on_startup,
execute_after_browser_creation=execute_after_browser_creation)
# Internal classes. Note that end users may still need to both call
# and mock out methods of these classes, but they should not be
# subclassed.
class _FakeBrowser(object):
def __init__(self, platform):
self._tabs = _FakeTabList(self)
# Fake the creation of the first tab.
self._tabs.New()
self._returned_system_info = FakeSystemInfo()
self._platform = platform
self._browser_type = 'release'
self._is_crashed = False
@property
def platform(self):
return self._platform
@platform.setter
def platform(self, incoming):
"""Allows overriding of the fake browser's platform object."""
assert isinstance(incoming, FakePlatform)
self._platform = incoming
@property
def returned_system_info(self):
"""The object which will be returned from calls to GetSystemInfo."""
return self._returned_system_info
@returned_system_info.setter
def returned_system_info(self, incoming):
"""Allows overriding of the returned SystemInfo object.
Incoming argument must be an instance of FakeSystemInfo."""
assert isinstance(incoming, FakeSystemInfo)
self._returned_system_info = incoming
@property
def browser_type(self):
"""The browser_type this browser claims to be ('debug', 'release', etc.)"""
return self._browser_type
@browser_type.setter
def browser_type(self, incoming):
"""Allows setting of the browser_type."""
self._browser_type = incoming
@property
def credentials(self):
return _FakeCredentials()
def Close(self):
self._is_crashed = False
@property
def supports_system_info(self):
return True
def GetSystemInfo(self):
return self.returned_system_info
@property
def supports_tab_control(self):
return True
@property
def tabs(self):
return self._tabs
def DumpStateUponFailure(self):
pass
class _FakeCredentials(object):
def WarnIfMissingCredentials(self, _):
pass
class _FakeTracingController(object):
def __init__(self):
self._is_tracing = False
def StartTracing(self, tracing_config, timeout=10):
self._is_tracing = True
del tracing_config
del timeout
def StopTracing(self):
self._is_tracing = False
@property
def is_tracing_running(self):
return self._is_tracing
def ClearStateIfNeeded(self):
pass
def IsChromeTracingSupported(self):
return True
class _FakeNetworkController(object):
def __init__(self):
self.wpr_mode = None
self.extra_wpr_args = None
self.is_initialized = False
self.is_open = False
self.use_live_traffic = None
def InitializeIfNeeded(self, use_live_traffic=False):
self.use_live_traffic = use_live_traffic
def UpdateTrafficSettings(self, round_trip_latency_ms=None,
download_bandwidth_kbps=None, upload_bandwidth_kbps=None):
pass
def Open(self, wpr_mode, extra_wpr_args, use_wpr_go=False):
del use_wpr_go # Unused.
self.wpr_mode = wpr_mode
self.extra_wpr_args = extra_wpr_args
self.is_open = True
def Close(self):
self.wpr_mode = None
self.extra_wpr_args = None
self.is_initialized = False
self.is_open = False
def StartReplay(self, archive_path, make_javascript_deterministic=False):
del make_javascript_deterministic # Unused.
assert self.is_open
self.is_initialized = archive_path is not None
def StopReplay(self):
self.is_initialized = False
class _FakeTab(object):
def __init__(self, browser, tab_id):
self._browser = browser
self._tab_id = str(tab_id)
self._collect_garbage_count = 0
self.test_png = None
@property
def collect_garbage_count(self):
return self._collect_garbage_count
@property
def id(self):
return self._tab_id
@property
def browser(self):
return self._browser
def WaitForDocumentReadyStateToBeComplete(self, timeout=0):
pass
def Navigate(self, url, script_to_evaluate_on_commit=None,
timeout=0):
del script_to_evaluate_on_commit, timeout # unused
if url == 'chrome://crash':
self.browser._is_crashed = True
raise Exception
def WaitForDocumentReadyStateToBeInteractiveOrBetter(self, timeout=0):
pass
def WaitForFrameToBeDisplayed(self, timeout=0):
pass
def IsAlive(self):
return True
def CloseConnections(self):
pass
def CollectGarbage(self):
self._collect_garbage_count += 1
def Close(self):
pass
@property
def screenshot_supported(self):
return self.test_png is not None
def Screenshot(self):
assert self.screenshot_supported, 'Screenshot is not supported'
return image_util.FromBase64Png(self.test_png)
class _FakeTabList(object):
_current_tab_id = 0
def __init__(self, browser):
self._tabs = []
self._browser = browser
def New(self, timeout=300):
del timeout # unused
type(self)._current_tab_id += 1
t = _FakeTab(self._browser, type(self)._current_tab_id)
self._tabs.append(t)
return t
def __iter__(self):
return self._tabs.__iter__()
def __len__(self):
return len(self._tabs)
def __getitem__(self, index):
if self._tabs[index].browser._is_crashed:
raise Exception
else:
return self._tabs[index]
def GetTabById(self, identifier):
"""The identifier of a tab can be accessed with tab.id."""
for tab in self._tabs:
if tab.id == identifier:
return tab
return None
class FakeInspectorWebsocket(object):
_NOTIFICATION_EVENT = 1
_NOTIFICATION_CALLBACK = 2
"""A fake InspectorWebsocket.
A fake that allows tests to send pregenerated data. Normal
InspectorWebsockets allow for any number of domain handlers. This fake only
allows up to 1 domain handler, and assumes that the domain of the response
always matches that of the handler.
"""
def __init__(self, mock_timer):
self._mock_timer = mock_timer
self._notifications = []
self._response_handlers = {}
self._pending_callbacks = {}
self._handler = None
def RegisterDomain(self, _, handler):
self._handler = handler
def AddEvent(self, method, params, time):
if self._notifications:
assert self._notifications[-1][1] < time, (
'Current response is scheduled earlier than previous response.')
response = {'method': method, 'params': params}
self._notifications.append((response, time, self._NOTIFICATION_EVENT))
def AddAsyncResponse(self, method, result, time):
if self._notifications:
assert self._notifications[-1][1] < time, (
'Current response is scheduled earlier than previous response.')
response = {'method': method, 'result': result}
self._notifications.append((response, time, self._NOTIFICATION_CALLBACK))
def AddResponseHandler(self, method, handler):
self._response_handlers[method] = handler
def SyncRequest(self, request, *args, **kwargs):
del args, kwargs # unused
handler = self._response_handlers[request['method']]
return handler(request) if handler else None
def AsyncRequest(self, request, callback):
self._pending_callbacks.setdefault(request['method'], []).append(callback)
def SendAndIgnoreResponse(self, request):
pass
def Connect(self, _):
pass
def DispatchNotifications(self, timeout):
current_time = self._mock_timer.time()
if not self._notifications:
self._mock_timer.SetTime(current_time + timeout + 1)
raise websocket.WebSocketTimeoutException()
response, time, kind = self._notifications[0]
if time - current_time > timeout:
self._mock_timer.SetTime(current_time + timeout + 1)
raise websocket.WebSocketTimeoutException()
self._notifications.pop(0)
self._mock_timer.SetTime(time + 1)
if kind == self._NOTIFICATION_EVENT:
self._handler(response)
elif kind == self._NOTIFICATION_CALLBACK:
callback = self._pending_callbacks.get(response['method']).pop(0)
callback(response)
else:
raise Exception('Unexpected response type')
class FakeTimer(object):
""" A fake timer to fake out the timing for a module.
Args:
module: module to fake out the time
"""
def __init__(self, module=None):
self._elapsed_time = 0
self._module = module
self._actual_time = None
if module:
assert isinstance(module, ModuleType)
self._actual_time = module.time
self._module.time = self
def sleep(self, time):
self._elapsed_time += time
def time(self):
return self._elapsed_time
def SetTime(self, time):
self._elapsed_time = time
def __del__(self):
self.Restore()
def Restore(self):
if self._module:
self._module.time = self._actual_time
self._module = None
self._actual_time = None
|
benschmaus/catapult
|
telemetry/telemetry/testing/fakes/__init__.py
|
Python
|
bsd-3-clause
| 15,827 |
/* Copyright (c) 2015-2020 The Khronos Group Inc.
* Copyright (c) 2015-2020 Valve Corporation
* Copyright (c) 2015-2020 LunarG, Inc.
* Copyright (C) 2015-2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Courtney Goeltzenleuchter <[email protected]>
* Author: Tobin Ehlis <[email protected]>
* Author: Chris Forbes <[email protected]>
* Author: Mark Lobodzinski <[email protected]>
* Author: Dave Houlton <[email protected]>
* Author: John Zulauf <[email protected]>
*/
#ifndef CORE_VALIDATION_TYPES_H_
#define CORE_VALIDATION_TYPES_H_
#include "cast_utils.h"
#include "hash_vk_types.h"
#include "sparse_containers.h"
#include "vk_safe_struct.h"
#include "vulkan/vulkan.h"
#include "vk_layer_logging.h"
#include "vk_object_types.h"
#include "vk_extension_helper.h"
#include "vk_typemap_helper.h"
#include "convert_to_renderpass2.h"
#include "layer_chassis_dispatch.h"
#include "image_layout_map.h"
#include <array>
#include <atomic>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <list>
#ifdef VK_USE_PLATFORM_ANDROID_KHR
#include "android_ndk_types.h"
#endif // VK_USE_PLATFORM_ANDROID_KHR
// Fwd declarations -- including descriptor_set.h creates an ugly include loop
namespace cvdescriptorset {
class DescriptorSetLayoutDef;
class DescriptorSetLayout;
class DescriptorSet;
} // namespace cvdescriptorset
// Only CoreChecks uses this, but the state tracker stores it.
constexpr static auto kInvalidLayout = image_layout_map::kInvalidLayout;
using ImageSubresourceLayoutMap = image_layout_map::ImageSubresourceLayoutMap;
struct CMD_BUFFER_STATE;
class CoreChecks;
class ValidationStateTracker;
enum CALL_STATE {
UNCALLED, // Function has not been called
QUERY_COUNT, // Function called once to query a count
QUERY_DETAILS, // Function called w/ a count to query details
};
class BASE_NODE {
public:
// Track when object is being used by an in-flight command buffer
std::atomic_int in_use;
// Track command buffers that this object is bound to
// binding initialized when cmd referencing object is bound to command buffer
// binding removed when command buffer is reset or destroyed
// When an object is destroyed, any bound cbs are set to INVALID.
// "int" value is an index into object_bindings where the corresponding
// backpointer to this node is stored.
small_unordered_map<CMD_BUFFER_STATE *, int, 8> cb_bindings;
// Set to true when the API-level object is destroyed, but this object may
// hang around until its shared_ptr refcount goes to zero.
bool destroyed;
BASE_NODE() {
in_use.store(0);
destroyed = false;
};
};
// Track command pools and their command buffers
struct COMMAND_POOL_STATE : public BASE_NODE {
VkCommandPoolCreateFlags createFlags;
uint32_t queueFamilyIndex;
// Cmd buffers allocated from this pool
std::unordered_set<VkCommandBuffer> commandBuffers;
};
// Utilities for barriers and the commmand pool
template <typename Barrier>
static bool IsTransferOp(const Barrier *barrier) {
return barrier->srcQueueFamilyIndex != barrier->dstQueueFamilyIndex;
}
template <typename Barrier, bool assume_transfer = false>
static bool TempIsReleaseOp(const COMMAND_POOL_STATE *pool, const Barrier *barrier) {
return (assume_transfer || IsTransferOp(barrier)) && (pool->queueFamilyIndex == barrier->srcQueueFamilyIndex);
}
template <typename Barrier, bool assume_transfer = false>
static bool IsAcquireOp(const COMMAND_POOL_STATE *pool, const Barrier *barrier) {
return (assume_transfer || IsTransferOp(barrier)) && (pool->queueFamilyIndex == barrier->dstQueueFamilyIndex);
}
static inline bool QueueFamilyIsSpecial(const uint32_t queue_family_index) {
return (queue_family_index == VK_QUEUE_FAMILY_EXTERNAL_KHR) || (queue_family_index == VK_QUEUE_FAMILY_FOREIGN_EXT);
}
static inline bool QueueFamilyIsIgnored(uint32_t queue_family_index) { return queue_family_index == VK_QUEUE_FAMILY_IGNORED; }
// Intentionally ignore VulkanTypedHandle::node, it is optional
inline bool operator==(const VulkanTypedHandle &a, const VulkanTypedHandle &b) NOEXCEPT {
return a.handle == b.handle && a.type == b.type;
}
namespace std {
template <>
struct hash<VulkanTypedHandle> {
size_t operator()(VulkanTypedHandle obj) const NOEXCEPT { return hash<uint64_t>()(obj.handle) ^ hash<uint32_t>()(obj.type); }
};
} // namespace std
// Flags describing requirements imposed by the pipeline on a descriptor. These
// can't be checked at pipeline creation time as they depend on the Image or
// ImageView bound.
enum descriptor_req {
DESCRIPTOR_REQ_VIEW_TYPE_1D = 1 << VK_IMAGE_VIEW_TYPE_1D,
DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY = 1 << VK_IMAGE_VIEW_TYPE_1D_ARRAY,
DESCRIPTOR_REQ_VIEW_TYPE_2D = 1 << VK_IMAGE_VIEW_TYPE_2D,
DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY = 1 << VK_IMAGE_VIEW_TYPE_2D_ARRAY,
DESCRIPTOR_REQ_VIEW_TYPE_3D = 1 << VK_IMAGE_VIEW_TYPE_3D,
DESCRIPTOR_REQ_VIEW_TYPE_CUBE = 1 << VK_IMAGE_VIEW_TYPE_CUBE,
DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY = 1 << VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
DESCRIPTOR_REQ_ALL_VIEW_TYPE_BITS = (1 << (VK_IMAGE_VIEW_TYPE_CUBE_ARRAY + 1)) - 1,
DESCRIPTOR_REQ_SINGLE_SAMPLE = 2 << VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
DESCRIPTOR_REQ_MULTI_SAMPLE = DESCRIPTOR_REQ_SINGLE_SAMPLE << 1,
DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT = DESCRIPTOR_REQ_MULTI_SAMPLE << 1,
DESCRIPTOR_REQ_COMPONENT_TYPE_SINT = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT << 1,
DESCRIPTOR_REQ_COMPONENT_TYPE_UINT = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT << 1,
};
extern unsigned DescriptorRequirementsBitsFromFormat(VkFormat fmt);
typedef std::map<uint32_t, descriptor_req> BindingReqMap;
struct DESCRIPTOR_POOL_STATE : BASE_NODE {
VkDescriptorPool pool;
uint32_t maxSets; // Max descriptor sets allowed in this pool
uint32_t availableSets; // Available descriptor sets in this pool
safe_VkDescriptorPoolCreateInfo createInfo;
std::unordered_set<cvdescriptorset::DescriptorSet *> sets; // Collection of all sets in this pool
std::map<uint32_t, uint32_t> maxDescriptorTypeCount; // Max # of descriptors of each type in this pool
std::map<uint32_t, uint32_t> availableDescriptorTypeCount; // Available # of descriptors of each type in this pool
DESCRIPTOR_POOL_STATE(const VkDescriptorPool pool, const VkDescriptorPoolCreateInfo *pCreateInfo)
: pool(pool),
maxSets(pCreateInfo->maxSets),
availableSets(pCreateInfo->maxSets),
createInfo(pCreateInfo),
maxDescriptorTypeCount(),
availableDescriptorTypeCount() {
// Collect maximums per descriptor type.
for (uint32_t i = 0; i < createInfo.poolSizeCount; ++i) {
uint32_t typeIndex = static_cast<uint32_t>(createInfo.pPoolSizes[i].type);
// Same descriptor types can appear several times
maxDescriptorTypeCount[typeIndex] += createInfo.pPoolSizes[i].descriptorCount;
availableDescriptorTypeCount[typeIndex] = maxDescriptorTypeCount[typeIndex];
}
}
};
struct MemRange {
VkDeviceSize offset = 0;
VkDeviceSize size = 0;
};
// Data struct for tracking memory object
struct DEVICE_MEMORY_STATE : public BASE_NODE {
void *object; // Dispatchable object used to create this memory (device of swapchain)
VkDeviceMemory mem;
safe_VkMemoryAllocateInfo alloc_info;
bool is_dedicated;
VkBuffer dedicated_buffer;
VkImage dedicated_image;
bool is_export;
VkExternalMemoryHandleTypeFlags export_handle_type_flags;
std::unordered_set<VulkanTypedHandle> obj_bindings; // objects bound to this memory
// Convenience vectors of handles to speed up iterating over objects independently
std::unordered_set<VkImage> bound_images;
std::unordered_set<VkBuffer> bound_buffers;
std::unordered_set<VkAccelerationStructureNV> bound_acceleration_structures;
MemRange mapped_range;
void *shadow_copy_base; // Base of layer's allocation for guard band, data, and alignment space
void *shadow_copy; // Pointer to start of guard-band data before mapped region
uint64_t shadow_pad_size; // Size of the guard-band data before and after actual data. It MUST be a
// multiple of limits.minMemoryMapAlignment
void *p_driver_data; // Pointer to application's actual memory
DEVICE_MEMORY_STATE(void *disp_object, const VkDeviceMemory in_mem, const VkMemoryAllocateInfo *p_alloc_info)
: object(disp_object),
mem(in_mem),
alloc_info(p_alloc_info),
is_dedicated(false),
dedicated_buffer(VK_NULL_HANDLE),
dedicated_image(VK_NULL_HANDLE),
is_export(false),
export_handle_type_flags(0),
mapped_range{},
shadow_copy_base(0),
shadow_copy(0),
shadow_pad_size(0),
p_driver_data(0){};
};
// Generic memory binding struct to track objects bound to objects
struct MEM_BINDING {
std::shared_ptr<DEVICE_MEMORY_STATE> mem_state;
VkDeviceSize offset;
VkDeviceSize size;
};
struct BufferBinding {
VkBuffer buffer;
VkDeviceSize size;
VkDeviceSize offset;
};
struct IndexBufferBinding : BufferBinding {
VkIndexType index_type;
};
inline bool operator==(MEM_BINDING a, MEM_BINDING b) NOEXCEPT {
return a.mem_state == b.mem_state && a.offset == b.offset && a.size == b.size;
}
namespace std {
template <>
struct hash<MEM_BINDING> {
size_t operator()(MEM_BINDING mb) const NOEXCEPT {
auto intermediate = hash<uint64_t>()(reinterpret_cast<uint64_t &>(mb.mem_state)) ^ hash<uint64_t>()(mb.offset);
return intermediate ^ hash<uint64_t>()(mb.size);
}
};
} // namespace std
// Superclass for bindable object state (currently images and buffers)
class BINDABLE : public BASE_NODE {
public:
bool sparse; // Is this object being bound with sparse memory or not?
// Non-sparse binding data
MEM_BINDING binding;
// Memory requirements for this BINDABLE
VkMemoryRequirements requirements;
// bool to track if memory requirements were checked
bool memory_requirements_checked;
// Tracks external memory types creating resource
VkExternalMemoryHandleTypeFlags external_memory_handle;
// Sparse binding data, initially just tracking MEM_BINDING per mem object
// There's more data for sparse bindings so need better long-term solution
// TODO : Need to update solution to track all sparse binding data
std::unordered_set<MEM_BINDING> sparse_bindings;
small_unordered_set<DEVICE_MEMORY_STATE *, 1> bound_memory_set_;
BINDABLE()
: sparse(false),
binding{},
requirements{},
memory_requirements_checked(false),
external_memory_handle(0),
sparse_bindings{},
bound_memory_set_{} {};
// Update the cached set of memory bindings.
// Code that changes binding.mem or sparse_bindings must call UpdateBoundMemorySet()
void UpdateBoundMemorySet() {
bound_memory_set_.clear();
if (!sparse) {
if (binding.mem_state) bound_memory_set_.insert(binding.mem_state.get());
} else {
for (auto sb : sparse_bindings) {
bound_memory_set_.insert(sb.mem_state.get());
}
}
}
// Return unordered set of memory objects that are bound
// Instead of creating a set from scratch each query, return the cached one
const small_unordered_set<DEVICE_MEMORY_STATE *, 1> &GetBoundMemory() const { return bound_memory_set_; }
};
class BUFFER_STATE : public BINDABLE {
public:
VkBuffer buffer;
VkBufferCreateInfo createInfo;
VkDeviceAddress deviceAddress;
BUFFER_STATE(VkBuffer buff, const VkBufferCreateInfo *pCreateInfo) : buffer(buff), createInfo(*pCreateInfo) {
if ((createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) && (createInfo.queueFamilyIndexCount > 0)) {
uint32_t *pQueueFamilyIndices = new uint32_t[createInfo.queueFamilyIndexCount];
for (uint32_t i = 0; i < createInfo.queueFamilyIndexCount; i++) {
pQueueFamilyIndices[i] = pCreateInfo->pQueueFamilyIndices[i];
}
createInfo.pQueueFamilyIndices = pQueueFamilyIndices;
}
if (createInfo.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
sparse = true;
}
auto *externalMemoryInfo = lvl_find_in_chain<VkExternalMemoryBufferCreateInfo>(pCreateInfo->pNext);
if (externalMemoryInfo) {
external_memory_handle = externalMemoryInfo->handleTypes;
}
};
BUFFER_STATE(BUFFER_STATE const &rh_obj) = delete;
~BUFFER_STATE() {
if ((createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) && (createInfo.queueFamilyIndexCount > 0)) {
delete[] createInfo.pQueueFamilyIndices;
createInfo.pQueueFamilyIndices = nullptr;
}
};
};
class BUFFER_VIEW_STATE : public BASE_NODE {
public:
VkBufferView buffer_view;
VkBufferViewCreateInfo create_info;
std::shared_ptr<BUFFER_STATE> buffer_state;
BUFFER_VIEW_STATE(const std::shared_ptr<BUFFER_STATE> &bf, VkBufferView bv, const VkBufferViewCreateInfo *ci)
: buffer_view(bv), create_info(*ci), buffer_state(bf){};
BUFFER_VIEW_STATE(const BUFFER_VIEW_STATE &rh_obj) = delete;
};
struct SAMPLER_STATE : public BASE_NODE {
VkSampler sampler;
VkSamplerCreateInfo createInfo;
VkSamplerYcbcrConversion samplerConversion = VK_NULL_HANDLE;
VkSamplerCustomBorderColorCreateInfoEXT customCreateInfo = {};
SAMPLER_STATE(const VkSampler *ps, const VkSamplerCreateInfo *pci) : sampler(*ps), createInfo(*pci) {
auto *conversionInfo = lvl_find_in_chain<VkSamplerYcbcrConversionInfo>(pci->pNext);
if (conversionInfo) samplerConversion = conversionInfo->conversion;
auto cbci = lvl_find_in_chain<VkSamplerCustomBorderColorCreateInfoEXT>(pci->pNext);
if (cbci) customCreateInfo = *cbci;
}
};
class IMAGE_STATE : public BINDABLE {
public:
VkImage image;
safe_VkImageCreateInfo safe_create_info;
VkImageCreateInfo &createInfo;
bool valid; // If this is a swapchain image backing memory track valid here as it doesn't have DEVICE_MEMORY_STATE
bool acquired; // If this is a swapchain image, has it been acquired by the app.
bool shared_presentable; // True for a front-buffered swapchain image
bool layout_locked; // A front-buffered image that has been presented can never have layout transitioned
bool get_sparse_reqs_called; // Track if GetImageSparseMemoryRequirements() has been called for this image
bool sparse_metadata_required; // Track if sparse metadata aspect is required for this image
bool sparse_metadata_bound; // Track if sparse metadata aspect is bound to this image
bool external_ahb; // True if image will be imported/exported from/to an Android Hardware Buffer
bool has_ahb_format; // True if image was created with an external Android format
bool is_swapchain_image; // True if image is a swapchain image
uint64_t ahb_format; // External Android format, if provided
VkImageSubresourceRange full_range; // The normalized ISR for all levels, layers (slices), and aspects
VkSwapchainKHR create_from_swapchain;
VkSwapchainKHR bind_swapchain;
uint32_t bind_swapchain_imageIndex;
image_layout_map::Encoder range_encoder;
VkFormatFeatureFlags format_features = 0;
// Need to memory requirments for each plane if image is disjoint
bool disjoint; // True if image was created with VK_IMAGE_CREATE_DISJOINT_BIT
VkMemoryRequirements plane0_requirements;
bool plane0_memory_requirements_checked;
VkMemoryRequirements plane1_requirements;
bool plane1_memory_requirements_checked;
VkMemoryRequirements plane2_requirements;
bool plane2_memory_requirements_checked;
std::vector<VkSparseImageMemoryRequirements> sparse_requirements;
IMAGE_STATE(VkImage img, const VkImageCreateInfo *pCreateInfo);
IMAGE_STATE(IMAGE_STATE const &rh_obj) = delete;
std::unordered_set<VkImage> aliasing_images;
bool IsCompatibleAliasing(IMAGE_STATE *other_image_state);
bool IsCreateInfoEqual(const VkImageCreateInfo &other_createInfo) const;
bool IsCreateInfoDedicatedAllocationImageAliasingCompatible(const VkImageCreateInfo &other_createInfo) const;
inline bool IsImageTypeEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.imageType == other_createInfo.imageType;
}
inline bool IsFormatEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.format == other_createInfo.format;
}
inline bool IsMipLevelsEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.mipLevels == other_createInfo.mipLevels;
}
inline bool IsUsageEqual(const VkImageCreateInfo &other_createInfo) const { return createInfo.usage == other_createInfo.usage; }
inline bool IsSamplesEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.samples == other_createInfo.samples;
}
inline bool IsTilingEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.tiling == other_createInfo.tiling;
}
inline bool IsArrayLayersEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.arrayLayers == other_createInfo.arrayLayers;
}
inline bool IsInitialLayoutEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.initialLayout == other_createInfo.initialLayout;
}
inline bool IsSharingModeEqual(const VkImageCreateInfo &other_createInfo) const {
return createInfo.sharingMode == other_createInfo.sharingMode;
}
inline bool IsExtentEqual(const VkImageCreateInfo &other_createInfo) const {
return (createInfo.extent.width == other_createInfo.extent.width) &&
(createInfo.extent.height == other_createInfo.extent.height) &&
(createInfo.extent.depth == other_createInfo.extent.depth);
}
inline bool IsQueueFamilyIndicesEqual(const VkImageCreateInfo &other_createInfo) const {
return (createInfo.queueFamilyIndexCount == other_createInfo.queueFamilyIndexCount) &&
(createInfo.queueFamilyIndexCount == 0 ||
memcmp(createInfo.pQueueFamilyIndices, other_createInfo.pQueueFamilyIndices,
createInfo.queueFamilyIndexCount * sizeof(createInfo.pQueueFamilyIndices[0])) == 0);
}
~IMAGE_STATE() {
if ((createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) && (createInfo.queueFamilyIndexCount > 0)) {
delete[] createInfo.pQueueFamilyIndices;
createInfo.pQueueFamilyIndices = nullptr;
}
};
};
class IMAGE_VIEW_STATE : public BASE_NODE {
public:
VkImageView image_view;
VkImageViewCreateInfo create_info;
const VkImageSubresourceRange normalized_subresource_range;
const image_layout_map::RangeGenerator range_generator;
VkSampleCountFlagBits samples;
unsigned descriptor_format_bits;
VkSamplerYcbcrConversion samplerConversion; // Handle of the ycbcr sampler conversion the image was created with, if any
VkFormatFeatureFlags format_features;
std::shared_ptr<IMAGE_STATE> image_state;
IMAGE_VIEW_STATE(const std::shared_ptr<IMAGE_STATE> &image_state, VkImageView iv, const VkImageViewCreateInfo *ci);
IMAGE_VIEW_STATE(const IMAGE_VIEW_STATE &rh_obj) = delete;
};
class ACCELERATION_STRUCTURE_STATE : public BINDABLE {
public:
VkAccelerationStructureNV acceleration_structure;
safe_VkAccelerationStructureCreateInfoNV create_infoNV;
safe_VkAccelerationStructureCreateInfoKHR create_infoKHR;
bool memory_requirements_checked = false;
VkMemoryRequirements2KHR memory_requirements;
bool build_scratch_memory_requirements_checked = false;
VkMemoryRequirements2KHR build_scratch_memory_requirements;
bool update_scratch_memory_requirements_checked = false;
VkMemoryRequirements2KHR update_scratch_memory_requirements;
bool built = false;
safe_VkAccelerationStructureInfoNV build_info;
uint64_t opaque_handle = 0;
ACCELERATION_STRUCTURE_STATE(VkAccelerationStructureNV as, const VkAccelerationStructureCreateInfoNV *ci)
: acceleration_structure(as),
create_infoNV(ci),
memory_requirements{},
build_scratch_memory_requirements_checked{},
update_scratch_memory_requirements_checked{} {}
ACCELERATION_STRUCTURE_STATE(VkAccelerationStructureKHR as, const VkAccelerationStructureCreateInfoKHR *ci)
: acceleration_structure(as),
create_infoKHR(ci),
memory_requirements{},
build_scratch_memory_requirements_checked{},
update_scratch_memory_requirements_checked{} {}
ACCELERATION_STRUCTURE_STATE(const ACCELERATION_STRUCTURE_STATE &rh_obj) = delete;
};
struct SWAPCHAIN_IMAGE {
VkImage image;
std::unordered_set<VkImage> bound_images;
};
class SWAPCHAIN_NODE : public BASE_NODE {
public:
safe_VkSwapchainCreateInfoKHR createInfo;
VkSwapchainKHR swapchain;
std::vector<SWAPCHAIN_IMAGE> images;
bool retired = false;
bool shared_presentable = false;
CALL_STATE vkGetSwapchainImagesKHRState = UNCALLED;
uint32_t get_swapchain_image_count = 0;
SWAPCHAIN_NODE(const VkSwapchainCreateInfoKHR *pCreateInfo, VkSwapchainKHR swapchain)
: createInfo(pCreateInfo), swapchain(swapchain) {}
};
extern bool ImageLayoutMatches(const VkImageAspectFlags aspect_mask, VkImageLayout a, VkImageLayout b);
// Store the DAG.
struct DAGNode {
uint32_t pass;
std::vector<uint32_t> prev;
std::vector<uint32_t> next;
};
struct RENDER_PASS_STATE : public BASE_NODE {
VkRenderPass renderPass;
safe_VkRenderPassCreateInfo2 createInfo;
std::vector<std::vector<uint32_t>> self_dependencies;
std::vector<DAGNode> subpassToNode;
std::unordered_map<uint32_t, bool> attachment_first_read;
RENDER_PASS_STATE(VkRenderPassCreateInfo2KHR const *pCreateInfo) : createInfo(pCreateInfo) {}
RENDER_PASS_STATE(VkRenderPassCreateInfo const *pCreateInfo) {
ConvertVkRenderPassCreateInfoToV2KHR(*pCreateInfo, &createInfo);
}
};
// Autogenerated as part of the vk_validation_error_message.h codegen
enum CMD_TYPE { VUID_CMD_ENUM_LIST(CMD_) };
enum CB_STATE {
CB_NEW, // Newly created CB w/o any cmds
CB_RECORDING, // BeginCB has been called on this CB
CB_RECORDED, // EndCB has been called on this CB
CB_INVALID_COMPLETE, // had a complete recording, but was since invalidated
CB_INVALID_INCOMPLETE, // fouled before recording was completed
};
// CB Status -- used to track status of various bindings on cmd buffer objects
typedef VkFlags CBStatusFlags;
enum CBStatusFlagBits {
// clang-format off
CBSTATUS_NONE = 0x00000000, // No status is set
CBSTATUS_LINE_WIDTH_SET = 0x00000001, // Line width has been set
CBSTATUS_DEPTH_BIAS_SET = 0x00000002, // Depth bias has been set
CBSTATUS_BLEND_CONSTANTS_SET = 0x00000004, // Blend constants state has been set
CBSTATUS_DEPTH_BOUNDS_SET = 0x00000008, // Depth bounds state object has been set
CBSTATUS_STENCIL_READ_MASK_SET = 0x00000010, // Stencil read mask has been set
CBSTATUS_STENCIL_WRITE_MASK_SET = 0x00000020, // Stencil write mask has been set
CBSTATUS_STENCIL_REFERENCE_SET = 0x00000040, // Stencil reference has been set
CBSTATUS_VIEWPORT_SET = 0x00000080,
CBSTATUS_SCISSOR_SET = 0x00000100,
CBSTATUS_INDEX_BUFFER_BOUND = 0x00000200, // Index buffer has been set
CBSTATUS_EXCLUSIVE_SCISSOR_SET = 0x00000400,
CBSTATUS_SHADING_RATE_PALETTE_SET = 0x00000800,
CBSTATUS_LINE_STIPPLE_SET = 0x00001000,
CBSTATUS_VIEWPORT_W_SCALING_SET = 0x00002000,
CBSTATUS_ALL_STATE_SET = 0x00003DFF, // All state set (intentionally exclude index buffer)
// clang-format on
};
struct QueryObject {
VkQueryPool pool;
uint32_t query;
// These next two fields are *not* used in hash or comparison, they are effectively a data payload
uint32_t index; // must be zero if !indexed
uint32_t perf_pass;
bool indexed;
// Command index in the command buffer where the end of the query was
// recorded (equal to the number of commands in the command buffer before
// the end of the query).
uint64_t endCommandIndex;
QueryObject(VkQueryPool pool_, uint32_t query_)
: pool(pool_), query(query_), index(0), perf_pass(0), indexed(false), endCommandIndex(0) {}
QueryObject(VkQueryPool pool_, uint32_t query_, uint32_t index_)
: pool(pool_), query(query_), index(index_), perf_pass(0), indexed(true), endCommandIndex(0) {}
QueryObject(const QueryObject &obj)
: pool(obj.pool),
query(obj.query),
index(obj.index),
perf_pass(obj.perf_pass),
indexed(obj.indexed),
endCommandIndex(obj.endCommandIndex) {}
QueryObject(const QueryObject &obj, uint32_t perf_pass_)
: pool(obj.pool),
query(obj.query),
index(obj.index),
perf_pass(perf_pass_),
indexed(obj.indexed),
endCommandIndex(obj.endCommandIndex) {}
bool operator<(const QueryObject &rhs) const {
return (pool == rhs.pool) ? ((query == rhs.query) ? (perf_pass < rhs.perf_pass) : (query < rhs.query)) : pool < rhs.pool;
}
};
inline bool operator==(const QueryObject &query1, const QueryObject &query2) {
return ((query1.pool == query2.pool) && (query1.query == query2.query) && (query1.perf_pass == query2.perf_pass));
}
enum QueryState {
QUERYSTATE_UNKNOWN, // Initial state.
QUERYSTATE_RESET, // After resetting.
QUERYSTATE_RUNNING, // Query running.
QUERYSTATE_ENDED, // Query ended but results may not be available.
QUERYSTATE_AVAILABLE, // Results available.
};
enum QueryResultType {
QUERYRESULT_UNKNOWN,
QUERYRESULT_NO_DATA,
QUERYRESULT_SOME_DATA,
QUERYRESULT_WAIT_ON_RESET,
QUERYRESULT_WAIT_ON_RUNNING,
};
inline const char *string_QueryResultType(QueryResultType result_type) {
switch (result_type) {
case QUERYRESULT_UNKNOWN:
return "query may be in an unknown state";
case QUERYRESULT_NO_DATA:
return "query may return no data";
case QUERYRESULT_SOME_DATA:
return "query will return some data or availability bit";
case QUERYRESULT_WAIT_ON_RESET:
return "waiting on a query that has been reset and not issued yet";
case QUERYRESULT_WAIT_ON_RUNNING:
return "waiting on a query that has not ended yet";
}
assert(false);
return "UNKNOWN QUERY STATE"; // Unreachable.
}
namespace std {
template <>
struct hash<QueryObject> {
size_t operator()(QueryObject query) const throw() {
return hash<uint64_t>()((uint64_t)(query.pool)) ^
hash<uint64_t>()(static_cast<uint64_t>(query.query) | (static_cast<uint64_t>(query.perf_pass) << 32));
}
};
} // namespace std
struct CBVertexBufferBindingInfo {
std::vector<BufferBinding> vertex_buffer_bindings;
};
static inline bool operator==(const VkImageSubresource &lhs, const VkImageSubresource &rhs) {
bool is_equal = (lhs.aspectMask == rhs.aspectMask) && (lhs.mipLevel == rhs.mipLevel) && (lhs.arrayLayer == rhs.arrayLayer);
return is_equal;
}
// Canonical dictionary for PushConstantRanges
using PushConstantRangesDict = hash_util::Dictionary<PushConstantRanges>;
using PushConstantRangesId = PushConstantRangesDict::Id;
// Canonical dictionary for the pipeline layout's layout of descriptorsetlayouts
using DescriptorSetLayoutDef = cvdescriptorset::DescriptorSetLayoutDef;
using DescriptorSetLayoutId = std::shared_ptr<const DescriptorSetLayoutDef>;
using PipelineLayoutSetLayoutsDef = std::vector<DescriptorSetLayoutId>;
using PipelineLayoutSetLayoutsDict =
hash_util::Dictionary<PipelineLayoutSetLayoutsDef, hash_util::IsOrderedContainer<PipelineLayoutSetLayoutsDef>>;
using PipelineLayoutSetLayoutsId = PipelineLayoutSetLayoutsDict::Id;
// Defines/stores a compatibility defintion for set N
// The "layout layout" must store at least set+1 entries, but only the first set+1 are considered for hash and equality testing
// Note: the "cannonical" data are referenced by Id, not including handle or device specific state
// Note: hash and equality only consider layout_id entries [0, set] for determining uniqueness
struct PipelineLayoutCompatDef {
uint32_t set;
PushConstantRangesId push_constant_ranges;
PipelineLayoutSetLayoutsId set_layouts_id;
PipelineLayoutCompatDef(const uint32_t set_index, const PushConstantRangesId pcr_id, const PipelineLayoutSetLayoutsId sl_id)
: set(set_index), push_constant_ranges(pcr_id), set_layouts_id(sl_id) {}
size_t hash() const;
bool operator==(const PipelineLayoutCompatDef &other) const;
};
// Canonical dictionary for PipelineLayoutCompat records
using PipelineLayoutCompatDict = hash_util::Dictionary<PipelineLayoutCompatDef, hash_util::HasHashMember<PipelineLayoutCompatDef>>;
using PipelineLayoutCompatId = PipelineLayoutCompatDict::Id;
// Store layouts and pushconstants for PipelineLayout
struct PIPELINE_LAYOUT_STATE : public BASE_NODE {
VkPipelineLayout layout;
std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> set_layouts;
PushConstantRangesId push_constant_ranges;
std::vector<PipelineLayoutCompatId> compat_for_set;
PIPELINE_LAYOUT_STATE() : layout(VK_NULL_HANDLE), set_layouts{}, push_constant_ranges{}, compat_for_set{} {}
void reset() {
layout = VK_NULL_HANDLE;
set_layouts.clear();
push_constant_ranges.reset();
compat_for_set.clear();
}
};
// Shader typedefs needed to store StageStage below
struct interface_var {
uint32_t id;
uint32_t type_id;
uint32_t offset;
bool is_patch;
bool is_block_member;
bool is_relaxed_precision;
// TODO: collect the name, too? Isn't required to be present.
};
typedef std::pair<unsigned, unsigned> descriptor_slot_t;
// Safe struct that spans NV and KHR VkRayTracingPipelineCreateInfo structures.
// It is a safe_VkRayTracingPipelineCreateInfoKHR and supports construction from
// a VkRayTracingPipelineCreateInfoNV.
class safe_VkRayTracingPipelineCreateInfoCommon : public safe_VkRayTracingPipelineCreateInfoKHR {
public:
safe_VkRayTracingPipelineCreateInfoCommon() : safe_VkRayTracingPipelineCreateInfoKHR() {}
safe_VkRayTracingPipelineCreateInfoCommon(const VkRayTracingPipelineCreateInfoNV *pCreateInfo)
: safe_VkRayTracingPipelineCreateInfoKHR() {
initialize(pCreateInfo);
}
void initialize(const VkRayTracingPipelineCreateInfoNV *pCreateInfo) {
safe_VkRayTracingPipelineCreateInfoNV nvStruct;
nvStruct.initialize(pCreateInfo);
sType = nvStruct.sType;
// Take ownership of the pointer and null it out in nvStruct
pNext = nvStruct.pNext;
nvStruct.pNext = nullptr;
flags = nvStruct.flags;
stageCount = nvStruct.stageCount;
pStages = nvStruct.pStages;
nvStruct.pStages = nullptr;
groupCount = nvStruct.groupCount;
maxRecursionDepth = nvStruct.maxRecursionDepth;
layout = nvStruct.layout;
basePipelineHandle = nvStruct.basePipelineHandle;
basePipelineIndex = nvStruct.basePipelineIndex;
assert(pGroups == nullptr);
if (nvStruct.groupCount && nvStruct.pGroups) {
pGroups = new safe_VkRayTracingShaderGroupCreateInfoKHR[groupCount];
for (uint32_t i = 0; i < groupCount; ++i) {
pGroups[i].sType = nvStruct.pGroups[i].sType;
pGroups[i].pNext = nvStruct.pGroups[i].pNext;
pGroups[i].type = nvStruct.pGroups[i].type;
pGroups[i].generalShader = nvStruct.pGroups[i].generalShader;
pGroups[i].closestHitShader = nvStruct.pGroups[i].closestHitShader;
pGroups[i].anyHitShader = nvStruct.pGroups[i].anyHitShader;
pGroups[i].intersectionShader = nvStruct.pGroups[i].intersectionShader;
pGroups[i].intersectionShader = nvStruct.pGroups[i].intersectionShader;
pGroups[i].pShaderGroupCaptureReplayHandle = nullptr;
}
}
}
void initialize(const VkRayTracingPipelineCreateInfoKHR *pCreateInfo) {
safe_VkRayTracingPipelineCreateInfoKHR::initialize(pCreateInfo);
}
};
class PIPELINE_STATE : public BASE_NODE {
public:
struct StageState {
std::unordered_set<uint32_t> accessible_ids;
std::vector<std::pair<descriptor_slot_t, interface_var>> descriptor_uses;
bool has_writable_descriptor;
};
VkPipeline pipeline;
safe_VkGraphicsPipelineCreateInfo graphicsPipelineCI;
safe_VkComputePipelineCreateInfo computePipelineCI;
safe_VkRayTracingPipelineCreateInfoCommon raytracingPipelineCI;
// Hold shared ptr to RP in case RP itself is destroyed
std::shared_ptr<const RENDER_PASS_STATE> rp_state;
// Flag of which shader stages are active for this pipeline
uint32_t active_shaders;
uint32_t duplicate_shaders;
// Capture which slots (set#->bindings) are actually used by the shaders of this pipeline
std::unordered_map<uint32_t, BindingReqMap> active_slots;
uint32_t max_active_slot; // the highest set number in active_slots for pipeline layout compatibility checks
// Additional metadata needed by pipeline_state initialization and validation
std::vector<StageState> stage_state;
// Vtx input info (if any)
std::vector<VkVertexInputBindingDescription> vertex_binding_descriptions_;
std::vector<VkVertexInputAttributeDescription> vertex_attribute_descriptions_;
std::vector<VkDeviceSize> vertex_attribute_alignments_;
std::unordered_map<uint32_t, uint32_t> vertex_binding_to_index_map_;
std::vector<VkPipelineColorBlendAttachmentState> attachments;
bool blendConstantsEnabled; // Blend constants enabled for any attachments
std::shared_ptr<const PIPELINE_LAYOUT_STATE> pipeline_layout;
VkPrimitiveTopology topology_at_rasterizer;
VkBool32 sample_location_enabled;
// Default constructor
PIPELINE_STATE()
: pipeline{},
graphicsPipelineCI{},
computePipelineCI{},
raytracingPipelineCI{},
rp_state(nullptr),
active_shaders(0),
duplicate_shaders(0),
active_slots(),
max_active_slot(0),
vertex_binding_descriptions_(),
vertex_attribute_descriptions_(),
vertex_binding_to_index_map_(),
attachments(),
blendConstantsEnabled(false),
pipeline_layout(),
topology_at_rasterizer{},
sample_location_enabled(VK_FALSE) {}
void reset() {
VkGraphicsPipelineCreateInfo emptyGraphicsCI = {};
graphicsPipelineCI.initialize(&emptyGraphicsCI, false, false);
VkComputePipelineCreateInfo emptyComputeCI = {};
computePipelineCI.initialize(&emptyComputeCI);
VkRayTracingPipelineCreateInfoKHR emptyRayTracingCI = {};
raytracingPipelineCI.initialize(&emptyRayTracingCI);
stage_state.clear();
}
void initGraphicsPipeline(const ValidationStateTracker *state_data, const VkGraphicsPipelineCreateInfo *pCreateInfo,
std::shared_ptr<const RENDER_PASS_STATE> &&rpstate);
void initComputePipeline(const ValidationStateTracker *state_data, const VkComputePipelineCreateInfo *pCreateInfo);
template <typename CreateInfo>
void initRayTracingPipeline(const ValidationStateTracker *state_data, const CreateInfo *pCreateInfo);
inline VkPipelineBindPoint getPipelineType() const {
if (graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO)
return VK_PIPELINE_BIND_POINT_GRAPHICS;
else if (computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO)
return VK_PIPELINE_BIND_POINT_COMPUTE;
else if (raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV)
return VK_PIPELINE_BIND_POINT_RAY_TRACING_NV;
else if (raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR)
return VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR;
else
return VK_PIPELINE_BIND_POINT_MAX_ENUM;
}
inline VkPipelineCreateFlags getPipelineCreateFlags() const {
if (graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO)
return graphicsPipelineCI.flags;
else if (computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO)
return computePipelineCI.flags;
else if (raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV)
return raytracingPipelineCI.flags;
else
return 0;
}
};
// Track last states that are bound per pipeline bind point (Gfx & Compute)
struct LAST_BOUND_STATE {
LAST_BOUND_STATE() { reset(); } // must define default constructor for portability reasons
PIPELINE_STATE *pipeline_state;
VkPipelineLayout pipeline_layout;
std::unique_ptr<cvdescriptorset::DescriptorSet> push_descriptor_set;
// Ordered bound set tracking where index is set# that given set is bound to
struct PER_SET {
PER_SET()
: bound_descriptor_set(nullptr),
compat_id_for_set(0),
validated_set(nullptr),
validated_set_change_count(~0ULL),
validated_set_image_layout_change_count(~0ULL),
validated_set_binding_req_map() {}
cvdescriptorset::DescriptorSet *bound_descriptor_set;
// one dynamic offset per dynamic descriptor bound to this CB
std::vector<uint32_t> dynamicOffsets;
PipelineLayoutCompatId compat_id_for_set;
// Cache most recently validated descriptor state for ValidateCmdBufDrawState/UpdateDrawState
const cvdescriptorset::DescriptorSet *validated_set;
uint64_t validated_set_change_count;
uint64_t validated_set_image_layout_change_count;
BindingReqMap validated_set_binding_req_map;
};
std::vector<PER_SET> per_set;
void reset() {
pipeline_state = nullptr;
pipeline_layout = VK_NULL_HANDLE;
push_descriptor_set = nullptr;
per_set.clear();
}
void UnbindAndResetPushDescriptorSet(cvdescriptorset::DescriptorSet *ds) {
if (push_descriptor_set) {
for (std::size_t i = 0; i < per_set.size(); i++) {
if (per_set[i].bound_descriptor_set == push_descriptor_set.get()) {
per_set[i].bound_descriptor_set = nullptr;
}
}
}
push_descriptor_set.reset(ds);
}
};
static inline bool CompatForSet(uint32_t set, const LAST_BOUND_STATE &a, const std::vector<PipelineLayoutCompatId> &b) {
bool result = (set < a.per_set.size()) && (set < b.size()) && (a.per_set[set].compat_id_for_set == b[set]);
return result;
}
static inline bool CompatForSet(uint32_t set, const PIPELINE_LAYOUT_STATE *a, const PIPELINE_LAYOUT_STATE *b) {
// Intentionally have a result variable to simplify debugging
bool result = a && b && (set < a->compat_for_set.size()) && (set < b->compat_for_set.size()) &&
(a->compat_for_set[set] == b->compat_for_set[set]);
return result;
}
// Types to store queue family ownership (QFO) Transfers
// Common to image and buffer memory barriers
template <typename Handle, typename Barrier>
struct QFOTransferBarrierBase {
using HandleType = Handle;
using BarrierType = Barrier;
struct Tag {};
HandleType handle = VK_NULL_HANDLE;
uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
QFOTransferBarrierBase() = default;
QFOTransferBarrierBase(const BarrierType &barrier, const HandleType &resource_handle)
: handle(resource_handle),
srcQueueFamilyIndex(barrier.srcQueueFamilyIndex),
dstQueueFamilyIndex(barrier.dstQueueFamilyIndex) {}
hash_util::HashCombiner base_hash_combiner() const {
hash_util::HashCombiner hc;
hc << srcQueueFamilyIndex << dstQueueFamilyIndex << handle;
return hc;
}
bool operator==(const QFOTransferBarrierBase &rhs) const {
return (srcQueueFamilyIndex == rhs.srcQueueFamilyIndex) && (dstQueueFamilyIndex == rhs.dstQueueFamilyIndex) &&
(handle == rhs.handle);
}
};
template <typename Barrier>
struct QFOTransferBarrier {};
// Image barrier specific implementation
template <>
struct QFOTransferBarrier<VkImageMemoryBarrier> : public QFOTransferBarrierBase<VkImage, VkImageMemoryBarrier> {
using BaseType = QFOTransferBarrierBase<VkImage, VkImageMemoryBarrier>;
VkImageLayout oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImageLayout newLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImageSubresourceRange subresourceRange;
QFOTransferBarrier() = default;
QFOTransferBarrier(const BarrierType &barrier)
: BaseType(barrier, barrier.image),
oldLayout(barrier.oldLayout),
newLayout(barrier.newLayout),
subresourceRange(barrier.subresourceRange) {}
size_t hash() const {
// Ignoring the layout information for the purpose of the hash, as we're interested in QFO release/acquisition w.r.t.
// the subresource affected, an layout transitions are current validated on another path
auto hc = base_hash_combiner() << subresourceRange;
return hc.Value();
}
bool operator==(const QFOTransferBarrier<BarrierType> &rhs) const {
// Ignoring layout w.r.t. equality. See comment in hash above.
return (static_cast<BaseType>(*this) == static_cast<BaseType>(rhs)) && (subresourceRange == rhs.subresourceRange);
}
// TODO: codegen a comprehensive complie time type -> string (and or other traits) template family
static const char *BarrierName() { return "VkImageMemoryBarrier"; }
static const char *HandleName() { return "VkImage"; }
// UNASSIGNED-VkImageMemoryBarrier-image-00001 QFO transfer image barrier must not duplicate QFO recorded in command buffer
static const char *ErrMsgDuplicateQFOInCB() { return "UNASSIGNED-VkImageMemoryBarrier-image-00001"; }
// UNASSIGNED-VkImageMemoryBarrier-image-00002 QFO transfer image barrier must not duplicate QFO submitted in batch
static const char *ErrMsgDuplicateQFOInSubmit() { return "UNASSIGNED-VkImageMemoryBarrier-image-00002"; }
// UNASSIGNED-VkImageMemoryBarrier-image-00003 QFO transfer image barrier must not duplicate QFO submitted previously
static const char *ErrMsgDuplicateQFOSubmitted() { return "UNASSIGNED-VkImageMemoryBarrier-image-00003"; }
// UNASSIGNED-VkImageMemoryBarrier-image-00004 QFO acquire image barrier must have matching QFO release submitted previously
static const char *ErrMsgMissingQFOReleaseInSubmit() { return "UNASSIGNED-VkImageMemoryBarrier-image-00004"; }
};
// Buffer barrier specific implementation
template <>
struct QFOTransferBarrier<VkBufferMemoryBarrier> : public QFOTransferBarrierBase<VkBuffer, VkBufferMemoryBarrier> {
using BaseType = QFOTransferBarrierBase<VkBuffer, VkBufferMemoryBarrier>;
VkDeviceSize offset = 0;
VkDeviceSize size = 0;
QFOTransferBarrier(const VkBufferMemoryBarrier &barrier)
: BaseType(barrier, barrier.buffer), offset(barrier.offset), size(barrier.size) {}
size_t hash() const {
auto hc = base_hash_combiner() << offset << size;
return hc.Value();
}
bool operator==(const QFOTransferBarrier<BarrierType> &rhs) const {
return (static_cast<BaseType>(*this) == static_cast<BaseType>(rhs)) && (offset == rhs.offset) && (size == rhs.size);
}
static const char *BarrierName() { return "VkBufferMemoryBarrier"; }
static const char *HandleName() { return "VkBuffer"; }
// UNASSIGNED-VkImageMemoryBarrier-buffer-00001 QFO transfer buffer barrier must not duplicate QFO recorded in command buffer
static const char *ErrMsgDuplicateQFOInCB() { return "UNASSIGNED-VkBufferMemoryBarrier-buffer-00001"; }
// UNASSIGNED-VkBufferMemoryBarrier-buffer-00002 QFO transfer buffer barrier must not duplicate QFO submitted in batch
static const char *ErrMsgDuplicateQFOInSubmit() { return "UNASSIGNED-VkBufferMemoryBarrier-buffer-00002"; }
// UNASSIGNED-VkBufferMemoryBarrier-buffer-00003 QFO transfer buffer barrier must not duplicate QFO submitted previously
static const char *ErrMsgDuplicateQFOSubmitted() { return "UNASSIGNED-VkBufferMemoryBarrier-buffer-00003"; }
// UNASSIGNED-VkBufferMemoryBarrier-buffer-00004 QFO acquire buffer barrier must have matching QFO release submitted previously
static const char *ErrMsgMissingQFOReleaseInSubmit() { return "UNASSIGNED-VkBufferMemoryBarrier-buffer-00004"; }
};
template <typename Barrier>
using QFOTransferBarrierHash = hash_util::HasHashMember<QFOTransferBarrier<Barrier>>;
// Command buffers store the set of barriers recorded
template <typename Barrier>
using QFOTransferBarrierSet = std::unordered_set<QFOTransferBarrier<Barrier>, QFOTransferBarrierHash<Barrier>>;
template <typename Barrier>
struct QFOTransferBarrierSets {
QFOTransferBarrierSet<Barrier> release;
QFOTransferBarrierSet<Barrier> acquire;
void Reset() {
acquire.clear();
release.clear();
}
};
// The layer_data stores the map of pending release barriers
template <typename Barrier>
using GlobalQFOTransferBarrierMap =
std::unordered_map<typename QFOTransferBarrier<Barrier>::HandleType, QFOTransferBarrierSet<Barrier>>;
// Submit queue uses the Scoreboard to track all release/acquire operations in a batch.
template <typename Barrier>
using QFOTransferCBScoreboard =
std::unordered_map<QFOTransferBarrier<Barrier>, const CMD_BUFFER_STATE *, QFOTransferBarrierHash<Barrier>>;
template <typename Barrier>
struct QFOTransferCBScoreboards {
QFOTransferCBScoreboard<Barrier> acquire;
QFOTransferCBScoreboard<Barrier> release;
};
typedef std::map<QueryObject, QueryState> QueryMap;
typedef std::unordered_map<VkEvent, VkPipelineStageFlags> EventToStageMap;
typedef ImageSubresourceLayoutMap::LayoutMap GlobalImageLayoutRangeMap;
typedef std::unordered_map<VkImage, std::unique_ptr<GlobalImageLayoutRangeMap>> GlobalImageLayoutMap;
typedef std::unordered_map<VkImage, std::unique_ptr<ImageSubresourceLayoutMap>> CommandBufferImageLayoutMap;
// Cmd Buffer Wrapper Struct - TODO : This desperately needs its own class
struct CMD_BUFFER_STATE : public BASE_NODE {
VkCommandBuffer commandBuffer;
VkCommandBufferAllocateInfo createInfo = {};
VkCommandBufferBeginInfo beginInfo;
VkCommandBufferInheritanceInfo inheritanceInfo;
VkDevice device; // device this CB belongs to
std::shared_ptr<const COMMAND_POOL_STATE> command_pool;
bool hasDrawCmd;
bool hasTraceRaysCmd;
bool hasBuildAccelerationStructureCmd;
bool hasDispatchCmd;
CB_STATE state; // Track cmd buffer update state
uint64_t commandCount; // Number of commands recorded
uint64_t submitCount; // Number of times CB has been submitted
typedef uint64_t ImageLayoutUpdateCount;
ImageLayoutUpdateCount image_layout_change_count; // The sequence number for changes to image layout (for cached validation)
CBStatusFlags status; // Track status of various bindings on cmd buffer
CBStatusFlags static_status; // All state bits provided by current graphics pipeline
// rather than dynamic state
// Currently storing "lastBound" objects on per-CB basis
// long-term may want to create caches of "lastBound" states and could have
// each individual CMD_NODE referencing its own "lastBound" state
// Store last bound state for Gfx & Compute pipeline bind points
std::map<uint32_t, LAST_BOUND_STATE> lastBound;
using Bindings = std::map<uint32_t, descriptor_req>;
using Pipelines_Bindings = std::map<VkPipeline, Bindings>;
std::unordered_map<VkDescriptorSet, Pipelines_Bindings> validate_descriptorsets_in_queuesubmit;
uint32_t viewportMask;
uint32_t scissorMask;
uint32_t initial_device_mask;
safe_VkRenderPassBeginInfo activeRenderPassBeginInfo;
RENDER_PASS_STATE *activeRenderPass;
VkSubpassContents activeSubpassContents;
uint32_t active_render_pass_device_mask;
uint32_t activeSubpass;
VkFramebuffer activeFramebuffer;
std::unordered_set<VkFramebuffer> framebuffers;
// Unified data structs to track objects bound to this command buffer as well as object
// dependencies that have been broken : either destroyed objects, or updated descriptor sets
std::vector<VulkanTypedHandle> object_bindings;
std::vector<VulkanTypedHandle> broken_bindings;
QFOTransferBarrierSets<VkBufferMemoryBarrier> qfo_transfer_buffer_barriers;
QFOTransferBarrierSets<VkImageMemoryBarrier> qfo_transfer_image_barriers;
std::unordered_set<VkEvent> waitedEvents;
std::vector<VkEvent> writeEventsBeforeWait;
std::vector<VkEvent> events;
std::unordered_set<QueryObject> activeQueries;
std::unordered_set<QueryObject> startedQueries;
std::unordered_set<QueryObject> resetQueries;
CommandBufferImageLayoutMap image_layout_map;
CBVertexBufferBindingInfo current_vertex_buffer_binding_info;
bool vertex_buffer_used; // Track for perf warning to make sure any bound vtx buffer used
VkCommandBuffer primaryCommandBuffer;
// If primary, the secondary command buffers we will call.
// If secondary, the primary command buffers we will be called by.
std::unordered_set<CMD_BUFFER_STATE *> linkedCommandBuffers;
// Validation functions run at primary CB queue submit time
std::vector<std::function<bool(const ValidationStateTracker *device_data, const class QUEUE_STATE *queue_state)>>
queue_submit_functions;
// Validation functions run when secondary CB is executed in primary
std::vector<std::function<bool(const CMD_BUFFER_STATE *, VkFramebuffer)>> cmd_execute_commands_functions;
std::vector<
std::function<bool(const ValidationStateTracker *device_data, bool do_validate, EventToStageMap *localEventToStageMap)>>
eventUpdates;
std::vector<std::function<bool(const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool,
uint32_t perfQueryPass, QueryMap *localQueryToStateMap)>>
queryUpdates;
std::unordered_set<cvdescriptorset::DescriptorSet *> validated_descriptor_sets;
// Contents valid only after an index buffer is bound (CBSTATUS_INDEX_BUFFER_BOUND set)
IndexBufferBinding index_buffer_binding;
bool performance_lock_acquired = false;
bool performance_lock_released = false;
// Cache of current insert label...
LoggingLabel debug_label;
std::vector<uint8_t> push_constant_data;
PushConstantRangesId push_constant_data_ranges;
// Used for Best Practices tracking
uint32_t small_indexed_draw_call_count;
std::vector<IMAGE_VIEW_STATE *> imagelessFramebufferAttachments;
};
static inline const QFOTransferBarrierSets<VkImageMemoryBarrier> &GetQFOBarrierSets(
const CMD_BUFFER_STATE *cb, const QFOTransferBarrier<VkImageMemoryBarrier>::Tag &type_tag) {
return cb->qfo_transfer_image_barriers;
}
static inline const QFOTransferBarrierSets<VkBufferMemoryBarrier> &GetQFOBarrierSets(
const CMD_BUFFER_STATE *cb, const QFOTransferBarrier<VkBufferMemoryBarrier>::Tag &type_tag) {
return cb->qfo_transfer_buffer_barriers;
}
static inline QFOTransferBarrierSets<VkImageMemoryBarrier> &GetQFOBarrierSets(
CMD_BUFFER_STATE *cb, const QFOTransferBarrier<VkImageMemoryBarrier>::Tag &type_tag) {
return cb->qfo_transfer_image_barriers;
}
static inline QFOTransferBarrierSets<VkBufferMemoryBarrier> &GetQFOBarrierSets(
CMD_BUFFER_STATE *cb, const QFOTransferBarrier<VkBufferMemoryBarrier>::Tag &type_tag) {
return cb->qfo_transfer_buffer_barriers;
}
struct SEMAPHORE_WAIT {
VkSemaphore semaphore;
VkQueue queue;
uint64_t payload;
uint64_t seq;
};
struct SEMAPHORE_SIGNAL {
VkSemaphore semaphore;
uint64_t payload;
uint64_t seq;
};
struct CB_SUBMISSION {
CB_SUBMISSION(std::vector<VkCommandBuffer> const &cbs, std::vector<SEMAPHORE_WAIT> const &waitSemaphores,
std::vector<SEMAPHORE_SIGNAL> const &signalSemaphores, std::vector<VkSemaphore> const &externalSemaphores,
VkFence fence, uint32_t perf_submit_pass)
: cbs(cbs),
waitSemaphores(waitSemaphores),
signalSemaphores(signalSemaphores),
externalSemaphores(externalSemaphores),
fence(fence),
perf_submit_pass(perf_submit_pass) {}
std::vector<VkCommandBuffer> cbs;
std::vector<SEMAPHORE_WAIT> waitSemaphores;
std::vector<SEMAPHORE_SIGNAL> signalSemaphores;
std::vector<VkSemaphore> externalSemaphores;
VkFence fence;
uint32_t perf_submit_pass;
};
struct MT_FB_ATTACHMENT_INFO {
IMAGE_VIEW_STATE *view_state;
VkImage image;
};
class FRAMEBUFFER_STATE : public BASE_NODE {
public:
VkFramebuffer framebuffer;
safe_VkFramebufferCreateInfo createInfo;
std::shared_ptr<const RENDER_PASS_STATE> rp_state;
FRAMEBUFFER_STATE(VkFramebuffer fb, const VkFramebufferCreateInfo *pCreateInfo, std::shared_ptr<RENDER_PASS_STATE> &&rpstate)
: framebuffer(fb), createInfo(pCreateInfo), rp_state(rpstate){};
};
struct SHADER_MODULE_STATE;
struct DeviceExtensions;
struct DeviceFeatures {
VkPhysicalDeviceFeatures core;
VkPhysicalDeviceVulkan11Features core11;
VkPhysicalDeviceVulkan12Features core12;
VkPhysicalDeviceExclusiveScissorFeaturesNV exclusive_scissor;
VkPhysicalDeviceShadingRateImageFeaturesNV shading_rate_image;
VkPhysicalDeviceMeshShaderFeaturesNV mesh_shader;
VkPhysicalDeviceInlineUniformBlockFeaturesEXT inline_uniform_block;
VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features;
VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT vtx_attrib_divisor_features;
VkPhysicalDeviceBufferDeviceAddressFeaturesEXT buffer_device_address_ext;
VkPhysicalDeviceCooperativeMatrixFeaturesNV cooperative_matrix_features;
VkPhysicalDeviceComputeShaderDerivativesFeaturesNV compute_shader_derivatives_features;
VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV fragment_shader_barycentric_features;
VkPhysicalDeviceShaderImageFootprintFeaturesNV shader_image_footprint_features;
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT fragment_shader_interlock_features;
VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT demote_to_helper_invocation_features;
VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT texel_buffer_alignment_features;
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pipeline_exe_props_features;
VkPhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV dedicated_allocation_image_aliasing_features;
VkPhysicalDevicePerformanceQueryFeaturesKHR performance_query_features;
VkPhysicalDeviceCoherentMemoryFeaturesAMD device_coherent_memory_features;
VkPhysicalDeviceYcbcrImageArraysFeaturesEXT ycbcr_image_array_features;
VkPhysicalDeviceRayTracingFeaturesKHR ray_tracing_features;
VkPhysicalDeviceRobustness2FeaturesEXT robustness2_features;
VkPhysicalDeviceFragmentDensityMapFeaturesEXT fragment_density_map_features;
VkPhysicalDeviceCustomBorderColorFeaturesEXT custom_border_color_features;
};
enum RenderPassCreateVersion { RENDER_PASS_VERSION_1 = 0, RENDER_PASS_VERSION_2 = 1 };
enum CommandVersion { CMD_VERSION_1 = 0, CMD_VERSION_2 = 1 };
enum BarrierOperationsType {
kAllAcquire, // All Barrier operations are "ownership acquire" operations
kAllRelease, // All Barrier operations are "ownership release" operations
kGeneral, // Either no ownership operations or a mix of ownership operation types and/or non-ownership operations
};
ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(CMD_BUFFER_STATE *cb_state, const IMAGE_STATE &image_state);
const ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(const CMD_BUFFER_STATE *cb_state, VkImage image);
void AddInitialLayoutintoImageLayoutMap(const IMAGE_STATE &image_state, GlobalImageLayoutMap &image_layout_map);
#endif // CORE_VALIDATION_TYPES_H_
|
endlessm/chromium-browser
|
third_party/angle/third_party/vulkan-validation-layers/src/layers/core_validation_types.h
|
C
|
bsd-3-clause
| 57,785 |
FILE(REMOVE_RECURSE
"CMakeFiles/dynamic_object_test.dir/unittests/dynamic_object_test.cpp.o"
"dynamic_object_test.pdb"
"dynamic_object_test"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/dynamic_object_test.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
|
skaag/chaiscript
|
obj-x86_64-linux-gnu/CMakeFiles/dynamic_object_test.dir/cmake_clean.cmake
|
CMake
|
bsd-3-clause
| 319 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends SimpleRobot {
private Joystick joystick = new Joystick(1);
private Drivetrain drivetrain;
private BowlerArm arm;
Compressor compressor;
Pan pan;
//int port_1 = 7; //these ports were placeholders, no longer applicable
//int port_2 = 7;
public RobotTemplate() {
drivetrain = new Drivetrain();
arm = new BowlerArm();
pan = new Pan();
compressor = new Compressor(7, 7);//7 for the switch, 7 for the relay
}
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
drivetrain.set(1, 1);
sleep(5000);
drivetrain.set(0,0);
// arm.auto();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
compressor.start();
arm.setSolenoid(-1);
while (isOperatorControl()) {
//drivetrain updates
double lstick = -joystick.getRawAxis(2);
double rstick = -joystick.getRawAxis(4);
drivetrain.set(Math.abs(lstick) * lstick, Math.abs(rstick) * rstick); //If I'm not mistaken, this is the most convenient way to square in Java?
//pan updates version 2 (Amita); this is basic and can be used for backup
if(joystick.getRawButton(10)){
pan.endGame();
}
else{
pan.resetServo();
}
//bowler arm updates
if (joystick.getRawButton(7)) {
arm.rampDown();
} else if (joystick.getRawButton(5)) {
arm.rampUp();
} else {
arm.setRamp(0);
}
arm.setSolenoid((int) joystick.getRawAxis(6));
}
}
/*
*changes the servo state based on the button being pressed.
*once it is pressed, it is set to the opposite of what is was at the start, ditto for release.
*/
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
public void updateDrivetrain(){
}
public void updateArm(){
}
public void updatePan(){
}
public static void sleep(long ms){
long t=System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<t){
//do nothing!
}
}
}
|
2374/chris
|
src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
|
Java
|
bsd-3-clause
| 3,586 |
/*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PtyPartEffectTranslate.moc.h"
#include <QtToolbox/CollapsibleWidget.moc.h>
#include <QtToolbox/SingleSlidingValue.moc.h>
#include <QtToolbox/SingleSlidingHDR.moc.h>
#include <QGridLayout>
#include <QPushButton>
namespace EPI
{
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtyPartEffectTranslate::PtyPartEffectTranslate( const Ptr<Universe::NodeEmitter>& pNodeE,
const Ptr<Universe::PartEffectTranslate>& pEffect,
const Core::String& title)
: PtyPartEffect(pNodeE, pEffect, title)
{
updateProperty();
}
//-----------------------------------------------------------------------------
PtyPartEffectTranslate::PtyPartEffectTranslate(const Ptr<Universe::NodeEmitter>& pNodeE, const Core::String& title)
: PtyPartEffect(
pNodeE,
Ptr<Universe::PartEffectTranslate>(new Universe::PartEffectTranslate()),
title)
{
updateProperty();
}
//-----------------------------------------------------------------------------
PtyPartEffectTranslate::~PtyPartEffectTranslate()
{}
//-----------------------------------------------------------------------------
Ptr<PropertyWidget> PtyPartEffectTranslate::internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDataProxy, QWidget * parent)
{
Ptr<PtyWidgetPartEffectTranslate> pPW (new PtyWidgetPartEffectTranslate(pDataProxy, parent));
return pPW;
}
//-----------------------------------------------------------------------------
void PtyPartEffectTranslate::updateData()
{
Ptr<Universe::PartEffectTranslate> pEffet = LM_DEBUG_PTR_CAST<Universe::PartEffectTranslate> (getEffect());
pEffet->setConstSpeed(_constSpeed);
pEffet->setRandSpeed(_randSpeed);
}
//-----------------------------------------------------------------------------
void PtyPartEffectTranslate::updateProperty()
{
Ptr<Universe::PartEffectTranslate> pEffet = LM_DEBUG_PTR_CAST<Universe::PartEffectTranslate> (getEffect());
_constSpeed = pEffet->getConstSpeed();
_randSpeed = pEffet->getRandSpeed();
}
//-----------------------------------------------------------------------------
void PtyPartEffectTranslate::internalResurrect(const Ptr<Universe::World>& pWorld, const Ptr<Universe::World>& pWorldInfoContent, const Ptr<Property>& pty)
{
LM_ASSERT(getEffect()==null);
Ptr<Universe::IPartEffect> pEffet = Ptr<Universe::PartEffectTranslate>(new Universe::PartEffectTranslate());
setEffect(pEffet);
getUniverseNodeEmitter()->addEffect(getEffect());
updateData();
}
//-----------------------------------------------------------------------------
Ptr<Property> PtyPartEffectTranslate::clone() const
{
return Ptr<Property>(new PtyPartEffectTranslate( *this ));
}
//-----------------------------------------------------------------------------
void PtyPartEffectTranslate::internalCopy(const Ptr<Property>& pSrc)
{
PtyPartEffect::internalCopy(pSrc);
Ptr<PtyPartEffectTranslate> pPty = LM_DEBUG_PTR_CAST<PtyPartEffectTranslate>(pSrc);
_constSpeed = pPty->_constSpeed;
_randSpeed = pPty->_randSpeed;
updateData();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtyWidgetPartEffectTranslate::PtyWidgetPartEffectTranslate(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent)
: PropertyWidget(data, parent)
{
setupUi();
}
//-----------------------------------------------------------------------------
PtyWidgetPartEffectTranslate::~PtyWidgetPartEffectTranslate()
{}
//-----------------------------------------------------------------------------
void PtyWidgetPartEffectTranslate::readProperty()
{
Ptr<PtyPartEffectTranslate> pP = LM_DEBUG_PTR_CAST<PtyPartEffectTranslate>(getDataProxy()->getProperty());
_constSpeedX->setSingleValue(pP->_constSpeed.x);
_constSpeedY->setSingleValue(pP->_constSpeed.y);
_constSpeedZ->setSingleValue(pP->_constSpeed.z);
_randSpeedX->setSingleValue(pP->_randSpeed.x);
_randSpeedY->setSingleValue(pP->_randSpeed.y);
_randSpeedZ->setSingleValue(pP->_randSpeed.z);
}
//-----------------------------------------------------------------------------
void PtyWidgetPartEffectTranslate::writeProperty(QWidget* pWidget)
{
Ptr<PtyPartEffectTranslate> pP = LM_DEBUG_PTR_CAST<PtyPartEffectTranslate>(getDataProxy()->getProperty());
double x = 0.0;
double y = 0.0;
double z = 0.0;
_constSpeedX->getSingleValue(x);
_constSpeedY->getSingleValue(y);
_constSpeedZ->getSingleValue(z);
pP->_constSpeed = Core::Vector3f(float(x), float(y), float(z));
_randSpeedX->getSingleValue(x);
_randSpeedY->getSingleValue(y);
_randSpeedZ->getSingleValue(z);
pP->_randSpeed = Core::Vector3f(float(x), float(y), float(z));
}
//-----------------------------------------------------------------------------
void PtyWidgetPartEffectTranslate::setupUi()
{
_layout = new QGridLayout(this);
_layout->setContentsMargins(0, 0, 0, 0);
_layout->setSpacing(0);
_groupBox = new QtToolbox::CollapsibleWidget(this, "Translate effect");
_del = new QPushButton(QIcon(":/icons/smallClearBW.png"), "", this);
_constSpeedX = new QtToolbox::SingleSlidingHDR(this, "Const X", true);
_constSpeedY = new QtToolbox::SingleSlidingHDR(this, "Const Y", true);
_constSpeedZ = new QtToolbox::SingleSlidingHDR(this, "Const Z", true);
_randSpeedX = new QtToolbox::SingleSlidingHDR(this, "Rand X", true);
_randSpeedY = new QtToolbox::SingleSlidingHDR(this, "Rand Y", true);
_randSpeedZ = new QtToolbox::SingleSlidingHDR(this, "Rand Z", true);
_groupBox->addWidgetToTitle(_del);
_groupBox->getLayout()->addWidget(_constSpeedX);
_groupBox->getLayout()->addWidget(_constSpeedY);
_groupBox->getLayout()->addWidget(_constSpeedZ);
_groupBox->getLayout()->addWidget(_randSpeedX);
_groupBox->getLayout()->addWidget(_randSpeedY);
_groupBox->getLayout()->addWidget(_randSpeedZ);
_layout->addWidget(_groupBox);
setLayout(_layout);
getWidgetsForUndoRedo().push_back(_constSpeedX);
getWidgetsForUndoRedo().push_back(_constSpeedY);
getWidgetsForUndoRedo().push_back(_constSpeedZ);
getWidgetsForUndoRedo().push_back(_randSpeedX);
getWidgetsForUndoRedo().push_back(_randSpeedY);
getWidgetsForUndoRedo().push_back(_randSpeedZ);
PropertyWidget::setupUi();
connect(_del, SIGNAL(clicked()), this, SLOT(deleteWidget()));
}
//-----------------------------------------------------------------------------
void PtyWidgetPartEffectTranslate::deleteWidget()
{
emit deletePtyWidgetEffect(this);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
}//namespace EPI
|
benkaraban/anima-games-engine
|
Sources/Tools/EPI/Document/Properties/PtyNodeEmitter/PtyPartEffectTranslate.moc.cpp
|
C++
|
bsd-3-clause
| 8,876 |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy import fuzzy_uncertainty
module_logger = logging.getLogger(__name__)
def fuzzylogic(features, cfg, require="all"):
"""
FIXME: Think about, should I return 0, or have an assert, and at qc.py
all qc tests are applied with a try, and in case it fails it flag
0s.
"""
require = cfg.get("require", require)
if (require == "all") and not np.all([f in features for f in cfg["features"]]):
module_logger.warning(
"Not all features (%s) required by fuzzy logic are available".format(
cfg["features"].keys()
)
)
raise KeyError
uncertainty = fuzzy_uncertainty(
data=features, features=cfg["features"], output=cfg["output"], require=require
)
return uncertainty
class FuzzyLogic(QCCheckVar):
def set_features(self):
self.features = {}
for v in [f for f in self.cfg["features"] if f not in self.features]:
if v == "woa_bias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] = woa_comparison["woa_bias"]
elif v == "woa_normbias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] = woa_comparison["woa_normbias"]
elif v == "spike":
self.features[v] = spike(self.data[self.varname])
elif v == "gradient":
self.features[v] = gradient(self.data[self.varname])
self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg)
def test(self):
self.flags = {}
cfg = self.cfg
flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1")
uncertainty = self.features["fuzzylogic"]
# FIXME: As it is now, it will have no zero flag value. Think about cases
# where some values in a profile would not be estimated, hence flag=0
# I needed to use np.nonzeros because now uncertainty is a masked array,
# to accept when a feature is masked.
flag[np.nonzero(uncertainty <= 0.29)] = 1
flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2
flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3
flag[np.nonzero(uncertainty > 0.72)] = 4
self.flags["fuzzylogic"] = flag
|
castelao/CoTeDe
|
cotede/qctests/fuzzylogic.py
|
Python
|
bsd-3-clause
| 2,680 |
# Spree PayPal Express
This is a "re-do" of the official [spree_paypal_express][4] extension. The old extension is extremely hard to maintain and complex.
Behind-the-scenes, this extension uses [PayPal's Merchant Ruby SDK](https://github.com/paypal/merchant-sdk-ruby).
## Installation
1. Add this extension to your Gemfile with this line:
gem 'spree_paypal_express', :github => "spree-contrib/better_spree_paypal_express", :branch => "2-2-stable"
2. Install the gem using Bundler:
bundle install
3. Copy & run migrations
bundle exec rails g spree_paypal_express:install
4. Restart your server
If your server was running, restart it so that it can find the assets properly.
### Sandbox Setup
#### PayPal
Go to [PayPal's Developer Website](https://developer.paypal.com/), sign in with your PayPal account, click "Applications" then "Sandbox Accounts" and create a new "Business" account. Once the account is created, click on the triangle next to its email address, then "Profile". The "API Credentials" tab will provide your API credentials (probably). If this tab is blank, try refreshing the page.
You will also need a "Personal" account to test the transactions on your site. Create this in the same way, finding the account information under "Profile" as well. You may need to set a password in order to be able to log in to PayPal's sandbox for this user.
#### Spree Setup
In Spree, go to the admin backend, click "Configuration" and then "Payment Methods" and create a new payment method. Select "Spree::Gateway::PayPalExpress" as the provider, and click "Create". Enter the email address, password and signature from the "API Credentials" tab for the **Business** account on PayPal.
### Production setup
#### PayPal
Sign in to PayPal, then click "Profile" and then (under "Account Information" on the left), click "API Access". On this page, select "Option 2" and click "View API Signature". The username, password and signature will be displayed on this screen.
If you are unable to find it, then follow [PayPal's own documentation](https://developer.paypal.com/webapps/developer/docs/classic/api/apiCredentials/).
#### Spree Setup
Same as sandbox setup, but change "Server" from "sandbox" to "live".
## Configuration
The PayPal Express Checkout has [no less than 4.5 billion configuration options](https://github.com/paypal/merchant-sdk-ruby/blob/1d65e598d2f9f200f85c6b3338d4293dbed576d8/lib/paypal-sdk/merchant/data_types.rb#L830-L959).
This Spree extension supports *some* of those. If your favourite is not here, then please submit an issue about it, or better still a patch to add it in.
### Solution Type
Determines whether or not a user needs a PayPal account to check out.
```ruby
payment_method.preferred_solution_type = "Mark"
# or
payment_method.preferred_solution_type = "Sole"
```
"Mark" if you do want users to have a paypal account, "Sole" otherwise.
### Landing Page
Determines which page to show users once they're redirected to PayPal.
```ruby
payment_method.preferred_solution_type = "Login"
# or
payment_method.preferred_solution_type = "Billing"
```
"Login" will show the users the login form for PayPal, and "Billing" will show them a form where they can enter their credit card data and possibly sign up for a PayPal account (depending on the Solution Type setting above).
### Logo
Determines what logo, if any, to display at the top left of the PayPal express checkout:
```ruby
payment_method.preferred_logourl = 'http://yoursite.com/images/checkout.jpg'
```
**Must** be an absolute path to the image.
## Caveats
*Caveat venditor*
Paypal will refuse any order with a zero cost item.
Any such item will be skipped and not displayed.
PayPal will also refuse any order where item total (before taxes and shipping costs) is zero.
In this case the PayPal checkout page will simply display "Current order".
## Contributing
In the spirit of [free software][1], **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using prerelease versions
* by reporting [bugs][2]
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (*no patch is too small*: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by resolving [issues][2]
* by reviewing patches
Starting point:
* Fork the repo
* Clone your repo
* Run `bundle install`
* Run `bundle exec rake test_app` to create the test application in `spec/dummy`
* Make your changes
* Ensure specs pass by running `bundle exec rspec spec`
* Submit your pull request
Copyright (c) 2014 Spree Commerce and contributors, released under the [New BSD License][3]
[1]: http://www.fsf.org/licensing/essays/free-sw.html
[2]: https://github.com/spree/better_spree_paypal_express/issues
[3]: https://github.com/spree/better_spree_paypal_express/tree/master/LICENSE.md
[4]: https://github.com/spree/spree_paypal_express
|
Hates/better_spree_paypal_express
|
README.md
|
Markdown
|
bsd-3-clause
| 4,986 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.BuildConfig;
import java.lang.ref.WeakReference;
/**
* An {@link OptimizedFrameLayout} that increases the speed of frequent view lookup by ID by caching
* the result of the lookup. Adding or removing a view with the same ID as a cached version will
* cause the cache to be invalidated for that view and cause a re-lookup the next time it is
* queried. The goal of this view type is to be used in cases where child views are frequently
* accessed or reused, for example as part of a {@link androidx.recyclerview.widget.RecyclerView}.
* The logic in the {@link #fastFindViewById(int)} method would be in {@link #findViewById(int)} if
* it weren't final on the {@link View} class.
*
* {@link android.view.ViewGroup.OnHierarchyChangeListener}s cannot be used on ViewGroups that are
* children of this group since they would overwrite the listeners that are critical to this class'
* functionality.
*
* Usage:
* Use the same way that you would use a normal {@link android.widget.FrameLayout}, but instead
* of using {@link #findViewById(int)} to access views, use {@link #fastFindViewById(int)}.
*/
public class ViewLookupCachingFrameLayout extends OptimizedFrameLayout {
/** A map containing views that have had lookup performed on them for quicker access. */
private final SparseArray<WeakReference<View>> mCachedViews = new SparseArray<>();
/** The hierarchy listener responsible for notifying the cache that the tree has changed. */
@VisibleForTesting
final OnHierarchyChangeListener mListener = new OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, this);
}
@Override
public void onChildViewRemoved(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, null);
}
};
/** Default constructor for use in XML. */
public ViewLookupCachingFrameLayout(Context context, AttributeSet atts) {
super(context, atts);
setOnHierarchyChangeListener(mListener);
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
assert listener == mListener : "Hierarchy change listeners cannot be set for this group!";
super.setOnHierarchyChangeListener(listener);
}
/**
* Set the hierarchy listener that invalidates relevant parts of the cache when subtrees change.
* @param view The root of the tree to attach listeners to.
* @param listener The listener to attach (null to unset).
*/
private void setHierarchyListenerOnTree(View view, OnHierarchyChangeListener listener) {
if (!(view instanceof ViewGroup)) return;
ViewGroup group = (ViewGroup) view;
group.setOnHierarchyChangeListener(listener);
for (int i = 0; i < group.getChildCount(); i++) {
setHierarchyListenerOnTree(group.getChildAt(i), listener);
}
}
/**
* Does the same thing as {@link #findViewById(int)} but caches the result if not null.
* Subsequent lookups are cheaper as a result. Adding or removing a child view invalidates
* the cache for the ID of the view removed and causes a re-lookup.
* @param id The ID of the view to lookup.
* @return The view if it exists.
*/
@Nullable
public View fastFindViewById(@IdRes int id) {
WeakReference<View> ref = mCachedViews.get(id);
View view = null;
if (ref != null) view = ref.get();
if (view == null) view = findViewById(id);
if (BuildConfig.DCHECK_IS_ON) {
assert view == findViewById(id) : "View caching logic is broken!";
assert ref == null
|| ref.get() != null : "Cache held reference to garbage collected view!";
}
if (view != null) mCachedViews.put(id, new WeakReference<>(view));
return view;
}
@VisibleForTesting
SparseArray<WeakReference<View>> getCache() {
return mCachedViews;
}
}
|
endlessm/chromium-browser
|
ui/android/java/src/org/chromium/ui/widget/ViewLookupCachingFrameLayout.java
|
Java
|
bsd-3-clause
| 4,641 |
<!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:44:17 AEDT 2015 -->
<title>org.bouncycastle.math.raw (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="org.bouncycastle.math.raw (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 class="navBarCell1Rev">Package</li>
<li>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/math/field/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/bouncycastle/math/raw/test/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/math/raw/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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">
<h1 title="Package" class="title">Package org.bouncycastle.math.raw</h1>
<div class="docSummary">
<div class="block">Math support for raw multi-precision calculations.</div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Interleave.html" title="class in org.bouncycastle.math.raw">Interleave</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Mod.html" title="class in org.bouncycastle.math.raw">Mod</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Mont256.html" title="class in org.bouncycastle.math.raw">Mont256</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat.html" title="class in org.bouncycastle.math.raw">Nat</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat128.html" title="class in org.bouncycastle.math.raw">Nat128</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat160.html" title="class in org.bouncycastle.math.raw">Nat160</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat192.html" title="class in org.bouncycastle.math.raw">Nat192</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat224.html" title="class in org.bouncycastle.math.raw">Nat224</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat256.html" title="class in org.bouncycastle.math.raw">Nat256</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat320.html" title="class in org.bouncycastle.math.raw">Nat320</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat384.html" title="class in org.bouncycastle.math.raw">Nat384</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat448.html" title="class in org.bouncycastle.math.raw">Nat448</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat512.html" title="class in org.bouncycastle.math.raw">Nat512</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat576.html" title="class in org.bouncycastle.math.raw">Nat576</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package org.bouncycastle.math.raw Description">Package org.bouncycastle.math.raw Description</h2>
<div class="block">Math support for raw multi-precision calculations.</div>
</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 class="navBarCell1Rev">Package</li>
<li>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/math/field/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/bouncycastle/math/raw/test/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/math/raw/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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>
|
GaloisInc/hacrypto
|
src/Java/BouncyCastle/BouncyCastle-1.54/lcrypto-jdk15on-154/javadoc/org/bouncycastle/math/raw/package-summary.html
|
HTML
|
bsd-3-clause
| 7,812 |
from setuptools import setup, find_packages
setup(name='gelato.models',
version='0.1.2',
description='Gelato models',
namespace_packages=['gelato'],
long_description='',
author='',
author_email='',
license='',
url='',
include_package_data=True,
packages=find_packages(exclude=['tests']),
install_requires=['django', 'tower'])
|
washort/gelato.models
|
setup.py
|
Python
|
bsd-3-clause
| 394 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeFamilies #-}
module Rubik.Turn where
import Data.Array
import Rubik.Negate as N
import Rubik.Key
data Turn = NoTurn | Clock | OneEighty | CounterClock
deriving (Eq,Ord,Show,Enum,Ix)
instance Negate Turn where
negate NoTurn = NoTurn
negate Clock = CounterClock
negate OneEighty = OneEighty
negate CounterClock = Clock
instance Key Turn where
universe = [ NoTurn, Clock, OneEighty, CounterClock ]
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- never used
--instance (Negate a, Rotate a b) => Rotate a (b -> c) where
-- rotate t f a = f (rotate (N.negate t) a)
{-
-- Split into its own module
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- can complete either
turn :: a -> a
turn = rotateBy Clock
rotateBy :: Turn -> a -> a
rotateBy Clock = turn
rotateBy OneEighty = turn . turn
rotateBy CounterClock = turn . turn . turn
-- We invert the rotate because it is the co-varient position
instance Rotate a => Rotate (a -> b) where
type SideOf (a -> b) = SideOf a
rotateBy t f a = f (rotateBy (N.negate t) a)
instance (Rotate a,Rotate b) => Rotate (a,b) where
rotateBy t (a,b) = (rotateBy t a, rotateBy t b)
data Apply a b = Apply (a -> b) a
apply :: Apply a b -> b
apply (Apply f a) = f a
instance Rotate a => Rotate (Apply a b) where
turn (Apply f a) = Apply f (turn a)
-}
|
andygill/rubik-solver
|
src/Rubik/Turn.hs
|
Haskell
|
bsd-3-clause
| 1,481 |
/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "irods_auth_object.hpp"
namespace irods {
auth_object::auth_object(
rError_t* _r_error ) : r_error_( _r_error ) {
// TODO - stub
}
auth_object::~auth_object() {
// TODO - stub
}
auth_object::auth_object(
const auth_object& _rhs ) {
r_error_ = _rhs.r_error();
request_result_ = _rhs.request_result();
context_ = _rhs.context();
}
auth_object& auth_object::operator=(
const auth_object& _rhs ) {
r_error_ = _rhs.r_error();
request_result_ = _rhs.request_result();
context_ = _rhs.context();
return *this;
}
bool auth_object::operator==(
const auth_object& _rhs ) const {
// For the base class just always return true
return ( r_error_ == _rhs.r_error() &&
request_result_ == _rhs.request_result() &&
context_ == _rhs.context() );
}
}; // namespace irods
|
leesab/irods
|
iRODS/lib/core/src/irods_auth_object.cpp
|
C++
|
bsd-3-clause
| 1,097 |
package operation
import (
"fmt"
"os"
"github.com/runabove/sail/internal"
"github.com/spf13/cobra"
)
var cmdOperationAttach = &cobra.Command{
Use: "attach",
Short: "Attach to an ongoing operation output: sail operation attach [applicationName] <operationId>",
Long: `Attach to an ongoing operation output: sail operation attach [applicationName] <operationId>
Example: sail operation attach devel/redis fa853ede-6c05-4823-8b20-46a5389fe0de
If the applicationName is not passed, the default application name will be used (the user's username).
`,
Run: func(cmd *cobra.Command, args []string) {
switch len(args) {
case 1:
// applicationName was not passed. Using default one.
applicationName := internal.GetUserName()
operationAttach(applicationName, args[0])
case 2:
operationAttach(args[0], args[1])
default:
fmt.Fprintln(os.Stderr, "Invalid usage. sail operation attach [applicationName] <operationId>. Please see sail operation attach --help")
}
},
}
func operationAttach(app, operationID string) {
// Split namespace and service
internal.StreamPrint("GET", fmt.Sprintf("/applications/%s/operation/%s/attach", app, operationID), nil)
internal.ExitAfterCtrlC()
}
|
runabove/sail
|
operation/attach.go
|
GO
|
bsd-3-clause
| 1,209 |
/*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2016 Google Inc.
* Copyright (c) 2016 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/ /*!
* \file
* \brief CTS runner main().
*/ /*-------------------------------------------------------------------*/
#include "deString.h"
#include "deUniquePtr.hpp"
#include "glcTestRunner.hpp"
#include "tcuPlatform.hpp"
#include "tcuResource.hpp"
#include <cstdio>
// See tcuMain.cpp
tcu::Platform* createPlatform(void);
struct CommandLine
{
CommandLine(void) : runType(glu::ApiType::es(2, 0)), flags(0)
{
}
glu::ApiType runType;
std::string dstLogDir;
deUint32 flags;
};
static bool parseCommandLine(CommandLine& cmdLine, int argc, const char* const* argv)
{
for (int argNdx = 1; argNdx < argc; argNdx++)
{
const char* arg = argv[argNdx];
if (deStringBeginsWith(arg, "--type="))
{
static const struct
{
const char* name;
glu::ApiType runType;
} runTypes[] = { { "es2", glu::ApiType::es(2, 0) }, { "es3", glu::ApiType::es(3, 0) },
{ "es31", glu::ApiType::es(3, 1) }, { "es32", glu::ApiType::es(3, 2) },
{ "gl30", glu::ApiType::core(3, 0) }, { "gl31", glu::ApiType::core(3, 1) },
{ "gl32", glu::ApiType::core(3, 2) }, { "gl33", glu::ApiType::core(3, 3) },
{ "gl40", glu::ApiType::core(4, 0) }, { "gl41", glu::ApiType::core(4, 1) },
{ "gl42", glu::ApiType::core(4, 2) }, { "gl43", glu::ApiType::core(4, 3) },
{ "gl44", glu::ApiType::core(4, 4) }, { "gl45", glu::ApiType::core(4, 5) },
{ "gl46", glu::ApiType::core(4, 6) } };
const char* value = arg + 7;
int ndx = 0;
for (; ndx < DE_LENGTH_OF_ARRAY(runTypes); ndx++)
{
if (deStringEqual(runTypes[ndx].name, value))
{
cmdLine.runType = runTypes[ndx].runType;
break;
}
}
if (ndx >= DE_LENGTH_OF_ARRAY(runTypes))
return false;
}
else if (deStringBeginsWith(arg, "--logdir="))
{
const char* value = arg + 9;
cmdLine.dstLogDir = value;
}
else if (deStringBeginsWith(arg, "--summary"))
{
cmdLine.flags = glcts::TestRunner::PRINT_SUMMARY;
}
else if (deStringEqual(arg, "--verbose"))
cmdLine.flags = glcts::TestRunner::VERBOSE_ALL;
else
return false;
}
return true;
}
static void printHelp(const char* binName)
{
printf("%s:\n", binName);
printf(" --type=[esN[M]|glNM] Conformance test run type. Choose from\n");
printf(" ES: es2, es3, es31, es32\n");
printf(" GL: gl30, gl31, gl32, gl33, gl40, gl41, gl42, gl43, gl44, gl45, gl46\n");
printf(" --logdir=[path] Destination directory for log files\n");
printf(" --summary Print summary without running the tests\n");
printf(" --verbose Print out and log more information\n");
}
int main(int argc, char** argv)
{
CommandLine cmdLine;
int exitStatus = EXIT_SUCCESS;
if (!parseCommandLine(cmdLine, argc, argv))
{
printHelp(argv[0]);
return -1;
}
try
{
de::UniquePtr<tcu::Platform> platform(createPlatform());
tcu::DirArchive archive(".");
glcts::TestRunner runner(static_cast<tcu::Platform&>(*platform.get()), archive, cmdLine.dstLogDir.c_str(),
cmdLine.runType, cmdLine.flags);
for (;;)
{
if (!runner.iterate())
{
if (!runner.isConformant())
{
exitStatus = EXIT_FAILURE;
}
break;
}
}
}
catch (const std::exception& e)
{
printf("ERROR: %s\n", e.what());
return -1;
}
return exitStatus;
}
|
endlessm/chromium-browser
|
third_party/angle/third_party/VK-GL-CTS/src/external/openglcts/modules/runner/glcTestRunnerMain.cpp
|
C++
|
bsd-3-clause
| 4,116 |
/*
* Copyright (c) 2016, Groupon, 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 GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.groupon.lex.metrics;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
*
* @author ariane
*/
public class SimpleMetricTest {
@Test
public void constructor_number() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), (short)7);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 7, m.getValue());
}
@Test
public void constructor_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), "chocoladevla");
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateString("chocoladevla", m.getValue());
}
@Test
public void constructor_bool() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), true);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateBoolean(true, m.getValue());
}
@Test
public void constructor_metric() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromNumberValue(9000));
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 9000, m.getValue());
}
@Test
public void constructor_empty() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.EMPTY);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateEmpty(m.getValue());
}
@Test
public void to_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertThat(m.toString(), Matchers.allOf(containsString("foobar"), containsString("19")));
}
@Test
public void equality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertEquals(m0, m1);
assertEquals(m0.hashCode(), m1.hashCode());
}
@Test
public void inequality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(17));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m2 = new SimpleMetric(MetricName.valueOf("fizzbuzz"), MetricValue.fromIntValue(19));
assertNotEquals(m0, m1);
assertNotEquals(m0, m2);
assertNotEquals(m1, m0);
assertNotEquals(m1, m2);
assertNotEquals(m2, m0);
assertNotEquals(m2, m1);
}
@Test
public void equal_across_types() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertFalse(m.equals(null));
assertFalse(m.equals(new Object()));
}
}
|
groupon/monsoon
|
intf/src/test/java/com/groupon/lex/metrics/SimpleMetricTest.java
|
Java
|
bsd-3-clause
| 4,854 |
import sys
import warnings
try:
import itertools.izip as zip
except ImportError:
pass
from itertools import product
import numpy as np
from .. import util
from ..dimension import dimension_name
from ..element import Element
from ..ndmapping import NdMapping, item_check, sorted_context
from .interface import DataError, Interface
from .pandas import PandasInterface
from .util import finite_range
class cuDFInterface(PandasInterface):
"""
The cuDFInterface allows a Dataset objects to wrap a cuDF
DataFrame object. Using cuDF allows working with columnar
data on a GPU. Most operations leave the data in GPU memory,
however to plot the data it has to be loaded into memory.
The cuDFInterface covers almost the complete API exposed
by the PandasInterface with two notable exceptions:
1) Aggregation and groupby do not have a consistent sort order
(see https://github.com/rapidsai/cudf/issues/4237)
3) Not all functions can be easily applied to a cuDF so
some functions applied with aggregate and reduce will not work.
"""
datatype = 'cuDF'
types = ()
@classmethod
def loaded(cls):
return 'cudf' in sys.modules
@classmethod
def applies(cls, obj):
if not cls.loaded():
return False
import cudf
return isinstance(obj, (cudf.DataFrame, cudf.Series))
@classmethod
def init(cls, eltype, data, kdims, vdims):
import cudf
import pandas as pd
element_params = eltype.param.objects()
kdim_param = element_params['kdims']
vdim_param = element_params['vdims']
if isinstance(data, (cudf.Series, pd.Series)):
data = data.to_frame()
if not isinstance(data, cudf.DataFrame):
data, _, _ = PandasInterface.init(eltype, data, kdims, vdims)
data = cudf.from_pandas(data)
columns = list(data.columns)
ncols = len(columns)
index_names = [data.index.name]
if index_names == [None]:
index_names = ['index']
if eltype._auto_indexable_1d and ncols == 1 and kdims is None:
kdims = list(index_names)
if isinstance(kdim_param.bounds[1], int):
ndim = min([kdim_param.bounds[1], len(kdim_param.default)])
else:
ndim = None
nvdim = vdim_param.bounds[1] if isinstance(vdim_param.bounds[1], int) else None
if kdims and vdims is None:
vdims = [c for c in columns if c not in kdims]
elif vdims and kdims is None:
kdims = [c for c in columns if c not in vdims][:ndim]
elif kdims is None:
kdims = list(columns[:ndim])
if vdims is None:
vdims = [d for d in columns[ndim:((ndim+nvdim) if nvdim else None)]
if d not in kdims]
elif kdims == [] and vdims is None:
vdims = list(columns[:nvdim if nvdim else None])
# Handle reset of index if kdims reference index by name
for kd in kdims:
kd = dimension_name(kd)
if kd in columns:
continue
if any(kd == ('index' if name is None else name)
for name in index_names):
data = data.reset_index()
break
if any(isinstance(d, (np.int64, int)) for d in kdims+vdims):
raise DataError("cudf DataFrame column names used as dimensions "
"must be strings not integers.", cls)
if kdims:
kdim = dimension_name(kdims[0])
if eltype._auto_indexable_1d and ncols == 1 and kdim not in columns:
data = data.copy()
data.insert(0, kdim, np.arange(len(data)))
for d in kdims+vdims:
d = dimension_name(d)
if len([c for c in columns if c == d]) > 1:
raise DataError('Dimensions may not reference duplicated DataFrame '
'columns (found duplicate %r columns). If you want to plot '
'a column against itself simply declare two dimensions '
'with the same name. '% d, cls)
return data, {'kdims':kdims, 'vdims':vdims}, {}
@classmethod
def range(cls, dataset, dimension):
dimension = dataset.get_dimension(dimension, strict=True)
column = dataset.data[dimension.name]
if dimension.nodata is not None:
column = cls.replace_value(column, dimension.nodata)
if column.dtype.kind == 'O':
return np.NaN, np.NaN
else:
return finite_range(column, column.min(), column.max())
@classmethod
def values(cls, dataset, dim, expanded=True, flat=True, compute=True,
keep_index=False):
dim = dataset.get_dimension(dim, strict=True)
data = dataset.data[dim.name]
if not expanded:
data = data.unique()
return data.values_host if compute else data.values
elif keep_index:
return data
elif compute:
return data.values_host
try:
return data.values
except Exception:
return data.values_host
@classmethod
def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs):
# Get dimensions information
dimensions = [dataset.get_dimension(d).name for d in dimensions]
kdims = [kdim for kdim in dataset.kdims if kdim not in dimensions]
# Update the kwargs appropriately for Element group types
group_kwargs = {}
group_type = dict if group_type == 'raw' else group_type
if issubclass(group_type, Element):
group_kwargs.update(util.get_param_values(dataset))
group_kwargs['kdims'] = kdims
group_kwargs.update(kwargs)
# Propagate dataset
group_kwargs['dataset'] = dataset.dataset
# Find all the keys along supplied dimensions
keys = product(*(dataset.data[dimensions[0]].unique().values_host for d in dimensions))
# Iterate over the unique entries applying selection masks
grouped_data = []
for unique_key in util.unique_iterator(keys):
group_data = dataset.select(**dict(zip(dimensions, unique_key)))
if not len(group_data):
continue
group_data = group_type(group_data, **group_kwargs)
grouped_data.append((unique_key, group_data))
if issubclass(container_type, NdMapping):
with item_check(False), sorted_context(False):
kdims = [dataset.get_dimension(d) for d in dimensions]
return container_type(grouped_data, kdims=kdims)
else:
return container_type(grouped_data)
@classmethod
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e. tuple ranges, slices, sets, lists, or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
mask = None
for dim, sel in selection.items():
if isinstance(sel, tuple):
sel = slice(*sel)
arr = cls.values(dataset, dim, keep_index=True)
if util.isdatetime(arr) and util.pd:
try:
sel = util.parse_datetime_selection(sel)
except:
pass
new_masks = []
if isinstance(sel, slice):
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered')
if sel.start is not None:
new_masks.append(sel.start <= arr)
if sel.stop is not None:
new_masks.append(arr < sel.stop)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask &= imask
elif isinstance(sel, (set, list)):
for v in sel:
new_masks.append(arr==v)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask |= imask
elif callable(sel):
new_mask = sel(arr)
else:
new_mask = arr == sel
if mask is None:
mask = new_mask
else:
mask &= new_mask
return mask
@classmethod
def select(cls, dataset, selection_mask=None, **selection):
df = dataset.data
if selection_mask is None:
selection_mask = cls.select_mask(dataset, selection)
indexed = cls.indexed(dataset, selection)
if selection_mask is not None:
df = df.loc[selection_mask]
if indexed and len(df) == 1 and len(dataset.vdims) == 1:
return df[dataset.vdims[0].name].iloc[0]
return df
@classmethod
def concat_fn(cls, dataframes, **kwargs):
import cudf
return cudf.concat(dataframes, **kwargs)
@classmethod
def add_dimension(cls, dataset, dimension, dim_pos, values, vdim):
data = dataset.data.copy()
if dimension.name not in data:
data[dimension.name] = values
return data
@classmethod
def aggregate(cls, dataset, dimensions, function, **kwargs):
data = dataset.data
cols = [d.name for d in dataset.kdims if d in dimensions]
vdims = dataset.dimensions('value', label='name')
reindexed = data[cols+vdims]
agg = function.__name__
if len(dimensions):
agg_map = {'amin': 'min', 'amax': 'max'}
agg = agg_map.get(agg, agg)
grouped = reindexed.groupby(cols, sort=False)
if not hasattr(grouped, agg):
raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg)
df = getattr(grouped, agg)().reset_index()
else:
agg_map = {'amin': 'min', 'amax': 'max', 'size': 'count'}
agg = agg_map.get(agg, agg)
if not hasattr(reindexed, agg):
raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg)
agg = getattr(reindexed, agg)()
data = dict(((col, [v]) for col, v in zip(agg.index.values_host, agg.to_array())))
df = util.pd.DataFrame(data, columns=list(agg.index.values_host))
dropped = []
for vd in vdims:
if vd not in df.columns:
dropped.append(vd)
return df, dropped
@classmethod
def iloc(cls, dataset, index):
import cudf
rows, cols = index
scalar = False
columns = list(dataset.data.columns)
if isinstance(cols, slice):
cols = [d.name for d in dataset.dimensions()][cols]
elif np.isscalar(cols):
scalar = np.isscalar(rows)
cols = [dataset.get_dimension(cols).name]
else:
cols = [dataset.get_dimension(d).name for d in index[1]]
col_index = [columns.index(c) for c in cols]
if np.isscalar(rows):
rows = [rows]
if scalar:
return dataset.data[cols[0]].iloc[rows[0]]
result = dataset.data.iloc[rows, col_index]
# cuDF does not handle single rows and cols indexing correctly
# as of cudf=0.10.0 so we have to convert Series back to DataFrame
if isinstance(result, cudf.Series):
if len(cols) == 1:
result = result.to_frame(cols[0])
else:
result = result.to_frame().T
return result
@classmethod
def sort(cls, dataset, by=[], reverse=False):
cols = [dataset.get_dimension(d, strict=True).name for d in by]
return dataset.data.sort_values(by=cols, ascending=not reverse)
@classmethod
def dframe(cls, dataset, dimensions):
if dimensions:
return dataset.data[dimensions].to_pandas()
else:
return dataset.data.to_pandas()
Interface.register(cuDFInterface)
|
ioam/holoviews
|
holoviews/core/data/cudf.py
|
Python
|
bsd-3-clause
| 12,346 |
/*
* Copyright (c) Contributors, http://openviewer.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenViewer Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using OpenViewer.Model;
namespace OpenViewer.UI
{
public abstract class UIBase : IUI
{
protected MetaverseSession m_model;
public abstract string GetName();
public abstract void Initialize(MetaverseSession model, string renderingEngine, string loginURI, string username, string password);
public abstract void Run();
}
}
|
jimmygkr/openviewer
|
OpenViewer/UI/UIBase.cs
|
C#
|
bsd-3-clause
| 2,040 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
return array(
'router' => array(
'routes' => array(
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /api/:controller/:action
'api' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'api.vuongquocbalo.com',
),
),
),
),
);
|
thailvn/dev
|
module/Api/config/api.vuongquocbalo.com.php
|
PHP
|
bsd-3-clause
| 893 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.