code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `load_with` fn in crate `gleam`.">
<meta name="keywords" content="rust, rustlang, rust-lang, load_with">
<title>gleam::ffi::WindowPos3f::load_with - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>WindowPos3f</a></p><script>window.sidebarCurrent = {name: 'load_with', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>WindowPos3f</a>::<wbr><a class='fn' href=''>load_with</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-55342' class='srclink' href='../../../src/gleam///home/servo/buildbot/slave/doc/build/target/debug/build/gleam-9662459d59abad25/out/gl_bindings.rs.html#20129-20133' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn load_with<F>(loadfn: F) <span class='where'>where F: <a class='trait' href='../../../core/ops/trait.FnMut.html' title='core::ops::FnMut'>FnMut</a>(&<a href='../../../std/primitive.str.html'>str</a>) -> <a href='../../../std/primitive.pointer.html'>*const <a class='enum' href='../../../libc/types/common/c95/enum.c_void.html' title='libc::types::common::c95::c_void'>c_void</a></a></span></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../../";
window.currentCrate = "gleam";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script async src="../../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
gleam/ffi/WindowPos3f/fn.load_with.html
|
HTML
|
mpl-2.0
| 4,409
|
# encoding: utf-8
#
#
# self Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with self file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from collections import Mapping
import mo_dots as dot
from mo_math import SUM
from pyLibrary.queries.containers import Container
from pyLibrary.queries.domains import Domain, ALGEBRAIC, KNOWN
from mo_dots import Null, coalesce, join_field, split_field, Data
from mo_dots.lists import FlatList
from mo_times.timer import Timer
from mo_logs import Log
from mo_dots import wrap, listwrap
DEFAULT_QUERY_LIMIT = 20
class Dimension(Container):
__slots__ = ["name", "full_name", "where", "type", "limit", "index", "parent", "edges", "partitions", "fields"]
def __init__(self, dim, parent, jx):
dim = wrap(dim)
self.name = dim.name
self.parent = coalesce(parent)
self.full_name = join_field(split_field(self.parent.full_name)+[self.name])
self.edges = None # FOR NOW
dot.set_default(self, dim)
self.where = dim.where
self.type = coalesce(dim.type, "set")
self.limit = coalesce(dim.limit, DEFAULT_QUERY_LIMIT)
self.index = coalesce(dim.index, coalesce(parent, Null).index, jx.settings.index)
if not self.index:
Log.error("Expecting an index name")
# ALLOW ACCESS TO SUB-PART BY NAME (IF ONLY THERE IS NO NAME COLLISION)
self.edges = Data()
for e in listwrap(dim.edges):
new_e = Dimension(e, self, jx)
self.edges[new_e.full_name] = new_e
self.partitions = wrap(coalesce(dim.partitions, []))
parse_partition(self)
fields = coalesce(dim.field, dim.fields)
if not fields:
return # NO FIELDS TO SEARCH
elif isinstance(fields, Mapping):
self.fields = wrap(fields)
edges = wrap([{"name": k, "value": v, "allowNulls": False} for k, v in self.fields.items()])
else:
self.fields = listwrap(fields)
edges = wrap([{"name": f, "value": f, "index": i, "allowNulls": False} for i, f in enumerate(self.fields)])
if dim.partitions:
return # ALREADY HAVE PARTS
if self.type not in KNOWN - ALGEBRAIC:
return # PARTS OR TOO FUZZY (OR TOO NUMEROUS) TO FETCH
jx.get_columns()
with Timer("Get parts of {{name}}", {"name": self.name}):
parts = jx.query({
"from": self.index,
"select": {"name": "count", "aggregate": "count"},
"edges": edges,
"where": self.where,
"limit": self.limit
})
Log.note("{{name}} has {{num}} parts", name= self.name, num= len(parts))
d = parts.edges[0].domain
if dim.path:
if len(edges) > 1:
Log.error("Not supported yet")
# EACH TERM RETURNED IS A PATH INTO A PARTITION TREE
temp = Data(partitions=[])
for i, count in enumerate(parts):
a = dim.path(d.getEnd(d.partitions[i]))
if not isinstance(a, list):
Log.error("The path function on " + dim.name + " must return an ARRAY of parts")
addParts(
temp,
dim.path(d.getEnd(d.partitions[i])),
count,
0
)
self.value = coalesce(dim.value, "name")
self.partitions = temp.partitions
elif isinstance(fields, Mapping):
self.value = "name" # USE THE "name" ATTRIBUTE OF PARTS
partitions = FlatList()
for g, p in parts.groupby(edges):
if p:
partitions.append({
"value": g,
"where": {"and": [
{"term": {e.value: g[e.name]}}
for e in edges
]},
"count": int(p)
})
self.partitions = partitions
elif len(edges) == 1:
self.value = "name" # USE THE "name" ATTRIBUTE OF PARTS
# SIMPLE LIST OF PARTS RETURNED, BE SURE TO INTERRELATE THEM
self.partitions = wrap([
{
"name": str(d.partitions[i].name), # CONVERT TO STRING
"value": d.getEnd(d.partitions[i]),
"where": {"term": {edges[0].value: d.partitions[i].value}},
"count": count
}
for i, count in enumerate(parts)
])
self.order = {p.value: i for i, p in enumerate(self.partitions)}
elif len(edges) == 2:
self.value = "name" # USE THE "name" ATTRIBUTE OF PARTS
d2 = parts.edges[1].domain
# SIMPLE LIST OF PARTS RETURNED, BE SURE TO INTERRELATE THEM
array = parts.data.values()[0].cube # DIG DEEP INTO RESULT (ASSUME SINGLE VALUE CUBE, WITH NULL AT END)
def edges2value(*values):
if isinstance(fields, Mapping):
output = Data()
for e, v in zip(edges, values):
output[e.name] = v
return output
else:
return tuple(values)
self.partitions = wrap([
{
"name": str(d.partitions[i].name), # CONVERT TO STRING
"value": d.getEnd(d.partitions[i]),
"where": {"term": {edges[0].value: d.partitions[i].value}},
"count": SUM(subcube),
"partitions": [
{
"name": str(d2.partitions[j].name), # CONVERT TO STRING
"value": edges2value(d.getEnd(d.partitions[i]), d2.getEnd(d2.partitions[j])),
"where": {"and": [
{"term": {edges[0].value: d.partitions[i].value}},
{"term": {edges[1].value: d2.partitions[j].value}}
]},
"count": count2
}
for j, count2 in enumerate(subcube)
if count2 > 0 # ONLY INCLUDE PROPERTIES THAT EXIST
]
}
for i, subcube in enumerate(array)
])
else:
Log.error("Not supported")
parse_partition(self) # RELATE THE PARTS TO THE PARENTS
def __getitem__(self, item):
return self.__getattr__(item)
def __getattr__(self, key):
"""
RETURN CHILD EDGE OR PARTITION BY NAME
"""
#TODO: IGNORE THE STANDARD DIMENSION PROPERTIES TO AVOID ACCIDENTAL SELECTION OF EDGE OR PART
if key in Dimension.__slots__:
return None
e = self.edges[key]
if e:
return e
for p in self.partitions:
if p.name == key:
return p
return Null
def getDomain(self, **kwargs):
# kwargs.depth IS MEANT TO REACH INTO SUB-PARTITIONS
kwargs = wrap(kwargs)
kwargs.depth = coalesce(kwargs.depth, len(self.fields)-1 if isinstance(self.fields, list) else None)
if not self.partitions and self.edges:
# USE EACH EDGE AS A PARTITION, BUT isFacet==True SO IT ALLOWS THE OVERLAP
partitions = [
{
"name": v.name,
"value": v.name,
"where": v.where,
"style": v.style,
"weight": v.weight # YO! WHAT DO WE *NOT* COPY?
}
for i, v in enumerate(self.edges)
if i < coalesce(self.limit, DEFAULT_QUERY_LIMIT) and v.where
]
self.isFacet = True
elif kwargs.depth == None: # ASSUME self.fields IS A dict
partitions = FlatList()
for i, part in enumerate(self.partitions):
if i >= coalesce(self.limit, DEFAULT_QUERY_LIMIT):
break
partitions.append({
"name":part.name,
"value":part.value,
"where":part.where,
"style":coalesce(part.style, part.parent.style),
"weight":part.weight # YO! WHAT DO WE *NOT* COPY?
})
elif kwargs.depth == 0:
partitions = [
{
"name":v.name,
"value":v.value,
"where":v.where,
"style":v.style,
"weight":v.weight # YO! WHAT DO WE *NOT* COPY?
}
for i, v in enumerate(self.partitions)
if i < coalesce(self.limit, DEFAULT_QUERY_LIMIT)]
elif kwargs.depth == 1:
partitions = FlatList()
rownum = 0
for i, part in enumerate(self.partitions):
if i >= coalesce(self.limit, DEFAULT_QUERY_LIMIT):
continue
rownum += 1
try:
for j, subpart in enumerate(part.partitions):
partitions.append({
"name":join_field(split_field(subpart.parent.name) + [subpart.name]),
"value":subpart.value,
"where":subpart.where,
"style":coalesce(subpart.style, subpart.parent.style),
"weight":subpart.weight # YO! WHAT DO WE *NOT* COPY?
})
except Exception as e:
Log.error("", e)
else:
Log.error("deeper than 2 is not supported yet")
return Domain(
type=self.type,
name=self.name,
partitions=wrap(partitions),
min=self.min,
max=self.max,
interval=self.interval,
# THE COMPLICATION IS THAT SOMETIMES WE WANT SIMPLE PARTITIONS, LIKE
# STRINGS, DATES, OR NUMBERS. OTHER TIMES WE WANT PARTITION OBJECTS
# WITH NAME, VALUE, AND OTHER MARKUP.
# USUALLY A "set" IS MEANT TO BE SIMPLE, BUT THE end() FUNCTION IS
# OVERRIDES EVERYTHING AND IS EXPLICIT. - NOT A GOOD SOLUTION BECAUSE
# end() IS USED BOTH TO INDICATE THE QUERY PARTITIONS *AND* DISPLAY
# COORDINATES ON CHARTS
# PLEASE SPLIT end() INTO value() (replacing the string value) AND
# label() (for presentation)
value="name" if not self.value and self.partitions else self.value,
key="value",
label=coalesce(self.label, (self.type == "set" and self.name)),
end=coalesce(self.end, (self.type == "set" and self.name)),
isFacet=self.isFacet,
dimension=self
)
def getSelect(self, **kwargs):
if self.fields:
if len(self.fields) == 1:
return Data(
name=self.full_name,
value=self.fields[0],
aggregate="none"
)
else:
return Data(
name=self.full_name,
value=self.fields,
aggregate="none"
)
domain = self.getDomain(**kwargs)
if not domain.getKey:
Log.error("Should not happen")
if not domain.NULL:
Log.error("Should not happen")
return Data(
name=self.full_name,
domain=domain,
aggregate="none"
)
def addParts(parentPart, childPath, count, index):
"""
BUILD A hierarchy BY REPEATEDLY CALLING self METHOD WITH VARIOUS childPaths
count IS THE NUMBER FOUND FOR self PATH
"""
if index == None:
index = 0
if index == len(childPath):
return
c = childPath[index]
parentPart.count = coalesce(parentPart.count, 0) + count
if parentPart.partitions == None:
parentPart.partitions = FlatList()
for i, part in enumerate(parentPart.partitions):
if part.name == c.name:
addParts(part, childPath, count, index + 1)
return
parentPart.partitions.append(c)
addParts(c, childPath, count, index + 1)
def parse_partition(part):
for p in part.partitions:
if part.index:
p.index = part.index # COPY INDEX DOWN
parse_partition(p)
p.value = coalesce(p.value, p.name)
p.parent = part
if not part.where:
if len(part.partitions) > 100:
Log.error("Must define an where on {{name}} there are too many partitions ({{num_parts}})",
name= part.name,
num_parts= len(part.partitions))
# DEFAULT where IS THE UNION OF ALL CHILD FILTERS
if part.partitions:
part.where = {"or": part.partitions.where}
|
klahnakoski/esReplicate
|
pyLibrary/queries/dimensions.py
|
Python
|
mpl-2.0
| 13,303
|
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=384147
-->
<head>
<title>Test for Bug 384147</title>
<script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=384147">Mozilla Bug 384147</a>
<p id="display"></p>
<div id="content" style="display: block">
<div contentEditable id="editor"></div>
</div>
<pre id="test">
<script class="testbody" type="text/javascript;version=1.7">
/** Test for Bug 384147 **/
SimpleTest.waitForExplicitFinish();
// netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var editor = document.getElementById("editor");
editor.innerHTML = "<ol><li>Item 1</li><li>Item 2</li><ol><li>Item 3</li></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>";
editor.focus();
// If executed directly, a race condition exists that will cause execCommand
// to fail occasionally (but often). Defer test execution to page load.
addLoadEvent(function() {
var sel = window.getSelection();
// Test the affect that the tab key has on list items. Each test is
// documented with the initial state of the list on the left, and the
// expected state of the list on the right. {\t} indicates the list item
// that will be indented. {\st} indicates that a shift-tab will be simulated
// on that list item, outdenting it.
//
// Note: any test failing will likely result in all following tests failing
// as well, since each test depends on the document being in a given state.
// Unfortunately, due to the problems getting document focus and key events
// to fire consistently, it's difficult to reset state between tests.
// If there are test failures here, only debug the first test failure.
// *** test 1 ***
// 1. Item 1 1. Item 1
// 2. {\t}Item 2 1. Item 2
// 1. Item 3 2. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[1]);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 1");
// *** test 2 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. {\t}Item 3 1. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[2]);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><ol><li>Item 3</li></ol></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 2");
// *** test 3 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 1. {\st}Item 3 2. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
document.execCommand("outdent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 3");
// *** test 4 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. {\st}Item 3 2. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
document.execCommand("outdent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li></ol><li>Item 3</li></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 4");
// *** test 5 ***
// 1. Item 1 1. Item 1
// 1. {\st}Item 2 2. Item 2
// 2. Item 3 3. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[1]);
document.execCommand("outdent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><li>Item 2</li><li>Item 3</li></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 5");
// *** test 6 ***
// 1. Item 1 1. Item 1
// 2. {\t}Item 2 1. Item 2
// 3. Item 3 2. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li></ol><li>Item 3</li></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 6");
// *** test 7 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. {\t}Item 3 2. Item 3
// * Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[2]);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>",
"html output doesn't match expected value in test 7");
// That covers the basics of merging lists on indent and outdent.
// We also want to check that ul / ol lists won't be merged together,
// since they're different types of lists.
// *** test 8 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. Item 3 2. Item 3
// * {\t}Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[3]);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><ul><li>Item 4</li></ul><li>Item 5</li></ul>",
"html output doesn't match expected value in test 8");
// Better test merging with <ul> rather than <ol> too.
// *** test 9 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. Item 3 2. Item 3
// * Item 4 * Item 4
// * {\t}Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[4]);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><ul><li>Item 4</li><li>Item 5</li></ul></ul>",
"html output doesn't match expected value in test 9");
// Same test as test 8, but with outdent rather than indent.
// *** test 10 ***
// 1. Item 1 1. Item 1
// 1. Item 2 1. Item 2
// 2. Item 3 2. Item 3
// * {\st}Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
sel.selectAllChildren(editor.getElementsByTagName("li")[3]);
document.execCommand("outdent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><li>Item 4</li><ul><li>Item 5</li></ul></ul>",
"html output doesn't match expected value in test 10");
// Test indenting multiple items at once. Hold down "shift" and select
// upwards to get all the <ol> items and the first <ul> item.
// *** test 11 ***
// 1. Item 1 1. Item 1
// 1. {\t}Item 2 1. Item 2
// 2. {\t}Item 3 2. Item 3
// * {\t}Item 4 * Item 4
// * Item 5 * Item 5
sel.removeAllRanges();
var range = document.createRange();
range.setStart(editor.getElementsByTagName("li")[1], 0);
range.setEnd(editor.getElementsByTagName("li")[3], editor.getElementsByTagName("li")[3].childNodes.length);
sel.addRange(range);
document.execCommand("indent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><ol><li>Item 2</li><li>Item 3</li></ol></ol></ol><ul><ul><li>Item 4</li><li>Item 5</li></ul></ul>",
"html output doesn't match expected value in test 11");
// Test outdenting multiple items at once. Selection is already ready...
// *** test 12 ***
// 1. Item 1 1. Item 1
// 1. {\st}Item 2 1. Item 2
// 2. {\st}Item 3 2. Item 3
// * {\st}Item 4 * Item 4
// * Item 5 * Item 5
document.execCommand("outdent", false, null);
ok(editor.innerHTML == "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li></ol></ol><ul><li>Item 4</li><ul><li>Item 5</li></ul></ul>",
"html output doesn't match expected value in test 12");
SimpleTest.finish();
});
</script>
</pre>
</body>
</html>
|
tmhorne/celtx
|
editor/composer/test/test_bug384147.html
|
HTML
|
mpl-2.0
| 9,557
|
namespace Sparkle.Services.Networks.Models
{
using System;
public enum AdminWorkTask
{
None,
AcceptOrRefuse,
Other,
}
}
|
SparkleNetworks/SparkleNetworks
|
src/Sparkle.Services/Networks/Models/AdminWorkTask.cs
|
C#
|
mpl-2.0
| 177
|
namespace AIOSystemUtility3
{
partial class GPUSummary
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TempTxt = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.gpu = new System.Windows.Forms.Label();
this.UtilizationTxt = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// TempTxt
//
this.TempTxt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.TempTxt.AutoSize = true;
this.TempTxt.Font = new System.Drawing.Font("Segoe UI Light", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TempTxt.Location = new System.Drawing.Point(62, 103);
this.TempTxt.Name = "TempTxt";
this.TempTxt.Size = new System.Drawing.Size(28, 37);
this.TempTxt.TabIndex = 23;
this.TempTxt.Text = "-";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Segoe UI Light", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(4, 109);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 30);
this.label3.TabIndex = 22;
this.label3.Text = "Temp:";
//
// gpu
//
this.gpu.BackColor = System.Drawing.Color.Transparent;
this.gpu.Font = new System.Drawing.Font("Segoe UI Light", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gpu.Location = new System.Drawing.Point(-2, 7);
this.gpu.Name = "gpu";
this.gpu.Size = new System.Drawing.Size(118, 65);
this.gpu.TabIndex = 21;
this.gpu.Text = "GPU";
//
// UtilizationTxt
//
this.UtilizationTxt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.UtilizationTxt.AutoSize = true;
this.UtilizationTxt.Font = new System.Drawing.Font("Segoe UI Light", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.UtilizationTxt.Location = new System.Drawing.Point(106, 66);
this.UtilizationTxt.Name = "UtilizationTxt";
this.UtilizationTxt.Size = new System.Drawing.Size(28, 37);
this.UtilizationTxt.TabIndex = 20;
this.UtilizationTxt.Text = "-";
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Segoe UI Light", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(4, 72);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(111, 30);
this.label2.TabIndex = 19;
this.label2.Text = "Utilization:";
//
// GPUSummary
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.TempTxt);
this.Controls.Add(this.label3);
this.Controls.Add(this.gpu);
this.Controls.Add(this.UtilizationTxt);
this.Controls.Add(this.label2);
this.Name = "GPUSummary";
this.Size = new System.Drawing.Size(210, 146);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label TempTxt;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label gpu;
private System.Windows.Forms.Label UtilizationTxt;
private System.Windows.Forms.Label label2;
}
}
|
Kriogen777/Otil
|
AIOSystemUtility3/Controls/SummaryControls/GPUSummary.Designer.cs
|
C#
|
mpl-2.0
| 5,439
|
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package database
import (
"github.com/oracle/oci-go-sdk/v46/common"
"net/http"
)
// GetAutonomousPatchRequest wrapper for the GetAutonomousPatch operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/database/GetAutonomousPatch.go.html to see an example of how to use GetAutonomousPatchRequest.
type GetAutonomousPatchRequest struct {
// The autonomous patch OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm).
AutonomousPatchId *string `mandatory:"true" contributesTo:"path" name:"autonomousPatchId"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request GetAutonomousPatchRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// GetAutonomousPatchResponse wrapper for the GetAutonomousPatch operation
type GetAutonomousPatchResponse struct {
// The underlying http response
RawResponse *http.Response
// The AutonomousPatch instance
AutonomousPatch `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you contact Oracle about
// a particular request, then you must provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response GetAutonomousPatchResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
|
oracle/terraform-provider-baremetal
|
vendor/github.com/oracle/oci-go-sdk/v46/database/get_autonomous_patch_request_response.go
|
GO
|
mpl-2.0
| 3,078
|
// META: script=/resources/testdriver.js
// META: script=/resources/testdriver-vendor.js
// META: script=/bluetooth/resources/bluetooth-helpers.js
'use strict';
const test_desc = 'multiple calls to getDevices() resolves with the same' +
'BluetoothDevice objects for each granted Bluetooth device.';
bluetooth_test(async () => {
await getConnectedHealthThermometerDevice();
let firstDevices = await navigator.bluetooth.getDevices();
assert_equals(
firstDevices.length, 1, 'getDevices() should return the granted device.');
let secondDevices = await navigator.bluetooth.getDevices();
assert_equals(
secondDevices.length, 1,
'getDevices() should return the granted device.');
assert_equals(
firstDevices[0], secondDevices[0],
'getDevices() should produce the same BluetoothDevice objects for a ' +
'given Bluetooth device.');
}, test_desc);
|
UK992/servo
|
tests/wpt/web-platform-tests/bluetooth/getDevices/returns-same-bluetooth-device-object.https.window.js
|
JavaScript
|
mpl-2.0
| 895
|
importScript([
'../modevlib/main.js',
'../modevlib/Dimension-Bugzilla.js',
"../modevlib/Dimension-Tracked.js",
"../js/grid.js",
"../modevlib/gui/accordion.js",
"../modevlib/gui/dynamic.js",
"../modevlib/gui/aColor.js",
"blockerCharts.js",
"nominationCharts.js",
"regressionCharts.js",
"blockers.css"
]);
|
ashughes1/pi-tracked-bugs
|
js/chart_lib.js
|
JavaScript
|
mpl-2.0
| 316
|
using Alex.Networking.Java.Util;
namespace Alex.Networking.Java.Packets.Play
{
public class UpdateViewPositionPacket : Packet<UpdateViewPositionPacket>
{
public int ChunkX { get; set; }
public int ChunkZ { get; set; }
/// <inheritdoc />
public override void Decode(MinecraftStream stream)
{
ChunkX = stream.ReadVarInt();
ChunkZ = stream.ReadVarInt();
}
/// <inheritdoc />
public override void Encode(MinecraftStream stream)
{
throw new System.NotImplementedException();
}
}
}
|
kennyvv/Alex
|
src/Alex.Networking.Java/Packets/Play/UpdateViewPositionPacket.cs
|
C#
|
mpl-2.0
| 510
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.models.nitrogen;
import java.io.FileWriter;
import java.io.IOException;
import etomica.api.IBox;
import etomica.api.IMoleculeList;
import etomica.api.ISpecies;
import etomica.api.IVector;
import etomica.box.Box;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.lattice.crystal.Basis;
import etomica.lattice.crystal.BasisHcp;
import etomica.lattice.crystal.Primitive;
import etomica.lattice.crystal.PrimitiveHexagonal;
import etomica.normalmode.ArrayReader1D;
import etomica.normalmode.BasisBigCell;
import etomica.potential.PotentialMaster;
import etomica.simulation.Simulation;
import etomica.space.Boundary;
import etomica.space.BoundaryDeformablePeriodic;
import etomica.space.ISpace;
import etomica.space.Space;
import etomica.units.Degree;
/**
*
* This class is written to minimize the lattice energy of the beta-phase
* Nitrogen, which has HCP packing with 2 basis atoms using line minimization
*
* The varying parameters are all the translational d.o.f of the molecules
* NO rotational d.o.f.
*
*
* @author Tai Boon Tan
*
*/
public class MinimizeBetaNitrogenTranslationDOF extends Simulation {
public MinimizeBetaNitrogenTranslationDOF(ISpace space, int[] nC, double density, String fname, double tol){
super(space);
this.space = space;
this.density = density;
this.nC = nC;
this.fname = fname;
this.tolerance = tol;
energy = new double[3];
allValue = new double[3];
double ratio = 1.631;//Math.sqrt(8.0/3.0);
aDim = Math.pow(4.0/(Math.sqrt(3.0)*ratio*density), 1.0/3.0);
cDim = aDim*ratio;
numMolecule = nC[0]*nC[1]*nC[2]*2;
potentialMaster = new PotentialMaster();
Basis basisHCP = new BasisHcp();
BasisBigCell basis = new BasisBigCell(space, basisHCP, nC);
species = new SpeciesN2(space);
addSpecies(species);
box = new Box(space);
addBox(box);
box.setNMolecules(species, numMolecule);
boxDim = new IVector[3];
boxDim[0] = space.makeVector(new double[]{nC[0]*aDim, 0, 0});
boxDim[1] = space.makeVector(new double[]{-nC[1]*aDim*Math.cos(Degree.UNIT.toSim(60)), nC[1]*aDim*Math.sin(Degree.UNIT.toSim(60)), 0});
boxDim[2] = space.makeVector(new double[]{0, 0, nC[2]*cDim});
boundary = new BoundaryDeformablePeriodic(space, boxDim);
primitive = new PrimitiveHexagonal(space, nC[0]*aDim, nC[2]*cDim);
coordinateDefinition = new CoordinateDefinitionNitrogen(this, box, primitive, basis, space);
coordinateDefinition.setIsGamma();
coordinateDefinition.setOrientationVectorGamma(space);
coordinateDefinition.initializeCoordinates(new int[]{1,1,1});
box.setBoundary(boundary);
double rC = box.getBoundary().getBoxSize().getX(0)*0.475;
//System.out.println("rC: " + rC);
P2Nitrogen potential = new P2Nitrogen(space, rC);
potential.setBox(box);
potentialMaster.addPotential(potential, new ISpecies[]{species, species});
meterPotential = new MeterPotentialEnergy(potentialMaster);
meterPotential.setBox(box);
}
public double getEnergy (double[] u){
int numCells = coordinateDefinition.getBasisCells().length;
for (int cell=0; cell<numCells; cell++){
IMoleculeList molecules = coordinateDefinition.getBasisCells()[cell].molecules;
coordinateDefinition.setToU(molecules, u);
}
return meterPotential.getDataAsScalar();
}
public void doFindMinimum(double[] parameter){
this.parameters = parameter;
int numIter = 1;
double initEnergy = 0.0;
double afterEnergy = 0.0;
double initParam = 0.0;
double[] minVal = new double[parameter.length];
double[] maxVal = new double[parameter.length];
for (int i=0; i<parameter.length; i++){
minVal[i] = parameter[i] *(1 - 0.0011);
maxVal[i] = parameter[i] *(1 + 0.0012);
}
while(numIter < 100){
for (int iVar=0; iVar<parameter.length; iVar++){
// for(int iVar=parameter.length-1; iVar>0; iVar--){
if(iVar>0 && (iVar%5==3 || iVar%5==4)){
continue;
}
initEnergy = getEnergy(parameters);
initParam = parameters[iVar];
parameters[iVar] = findOptParameter(minVal[iVar], maxVal[iVar], parameters, iVar);
afterEnergy = getEnergy(parameters);
//System.out.println("diff: "+ (afterEnergy-initEnergy));
if(afterEnergy < initEnergy){
if(Math.abs(parameters[iVar]) < 1e-8){
minVal[iVar] = parameter[iVar] - 0.01;
maxVal[iVar] = parameter[iVar] + 0.01;
} else{
minVal[iVar] = parameter[iVar] *(1-0.003/Math.sqrt(numIter));
maxVal[iVar] = parameter[iVar] *(1+0.003/Math.sqrt(numIter));
}
//System.out.println("Write FILE DONE");
} else {
parameters[iVar] = initParam;
if(Math.abs(afterEnergy - initEnergy)< tolerance){
System.out.println("Minimum found! with tolerance of " + tolerance);
System.out.println("after: "+ afterEnergy/numMolecule + " before:" + initEnergy/numMolecule);
return;
}
}
}
System.out.println("after " +numIter + " loop; energy: "+ afterEnergy/numMolecule);
++numIter;
try {
FileWriter fileWriter = new FileWriter(fname+".out", false);
for (int i=0; i<parameters.length; i++){
fileWriter.write(parameters[i] + " ");
if(i>1 && i%10==9){
fileWriter.write("\n");
}
}
fileWriter.close();
} catch(IOException e){
throw new RuntimeException("Failed to write coord data normalize coord U" + e);
}
}
}
public double findOptParameter(double min, double max, double[] param, int iVar){
/*
* Every time you comes in, you only vary a parameter, called "value"
*
* Need to vary min and max
*/
int bootstrap = 0;
double value = min;
param[iVar] = value;
while (true) {
latticeEnergy = getEnergy(param);
// System.out.println("<findOpt> ivar: "+iVar +" ; " +value+" ;lattice energy: " + latticeEnergy/numMolecule);
// System.out.println(allValue[0]+" "+allValue[1]+" "+allValue[2]);
// System.out.println(energy[0]+" "+energy[1]+" "+energy[2]);
if (bootstrap < 3) {
allValue[bootstrap] = value;
energy[bootstrap] = latticeEnergy;
bootstrap++;
value += 0.5*(max-min);
param[iVar] = value;
}
else {
if (value > allValue[2]) {
allValue[0] = allValue[1];
allValue[1] = allValue[2];
allValue[2] = value;
energy[0] = energy[1];
energy[1] = energy[2];
energy[2] = latticeEnergy;
}
else if (value < allValue[0]) {
allValue[2] = allValue[1];
allValue[1] = allValue[0];
allValue[0] = value;
energy[2] = energy[1];
energy[1] = energy[0];
energy[0] = latticeEnergy;
}
else if (energy[2] > energy[0]) {
max = allValue[2];
if (value > allValue[1]) {
energy[2] = latticeEnergy;
allValue[2] = value;
}
else {
energy[2] = energy[1];
allValue[2] = allValue[1];
energy[1] = latticeEnergy;
allValue[1] = value;
}
}
else {
min = allValue[0];
if (value < allValue[1]) {
energy[0] = latticeEnergy;
allValue[0] = value;
}
else {
energy[0] = energy[1];
allValue[0] = allValue[1];
energy[1] = latticeEnergy;
allValue[1] = value;
}
}
if ((energy[1] > energy[0] && energy[1] > energy[2]) || (energy[1] < energy[0] && energy[1] < energy[2])){
// we found a maximum, due to numerical precision failure
// just bail and pretend that the middle point is the global minimum
return allValue[1];
}
}
if (bootstrap == 3) {
// now estimate minimum in U from the three points.
double dc01 = allValue[1]-allValue[0];
double dc12 = allValue[2]-allValue[1];
double du01 = energy[1]-energy[0];
double du12 = energy[2]-energy[1];
double dudc01 = du01/dc01;
double dudc12 = du12/dc12;
double m = (dudc12-dudc01)/(0.5*(dc01+dc12));
value = 0.9*(0.5*(allValue[1]+allValue[2]) - dudc12/m) + 0.1*(0.5*(allValue[0]+allValue[2]));
param[iVar] = value;
if (value == allValue[1] || value == allValue[2]) {
value = 0.5*(allValue[1] + allValue[2]);
param[iVar] = value;
}
if (value == allValue[0] || value == allValue[1]) {
value = 0.5*(allValue[1] + allValue[0]);
param[iVar] = value;
}
if (value < min) {
value = 0.5*(min + allValue[0]);
param[iVar] = value;
}
if (value > max) {
value = 0.5*(max + allValue[2]);
param[iVar] = value;
}
if (value == allValue[0] || value == allValue[1] || value == allValue[2] ) {
// we converged value to numerical precision.
//System.out.println("value "+ value);
//System.out.println("***"+value + " ;a: " + a+ " ;c: " + c);
return value;
}
if (Math.abs(energy[0]-energy[1])<1e-10 || Math.abs(energy[1]-energy[2])<1e-10 ||Math.abs(energy[0]-energy[2])<1e-10) {
if(energy[0]< energy[1]){
value = allValue[0];
} else {
value = allValue[1];
}
if(energy[1]< energy[2]){
value = allValue[1];
} else {
value = allValue[2];
}
if(energy[0]< energy[2]){
value = allValue[0];
} else {
value = allValue[2];
}
return value;
}
}
}
}
public double getLatticeEnergy(){
return latticeEnergy;
}
public static void main(String[] args){
double density = 0.025;
int nCell = 6;
double tol = 1e-10;
if(args.length > 0){
nCell = Integer.parseInt(args[0]);
}
if(args.length > 1){
tol = Double.parseDouble(args[1]);
}
int[] nC = new int[]{nCell, nCell, nCell};
String fname = "parameterN2beta_nCell"+nC[0];
double[][] vals = ArrayReader1D.getFromFile(fname+".in");
double[] parameters = new double[vals.length*vals[0].length];
for(int i=0; i<vals.length; i++){
for (int j=0; j<vals[0].length; j++){
parameters[i*vals[0].length + j] = vals[i][j];
}
}
System.out.println("Running lattice energy minimization algorithm for beta-N2");
System.out.println("with nCell: " + nCell + " in each dimension at density of " + density);
System.out.println("with tolerance of " + tol);
System.out.println("output file to: " + fname + ".out\n");
MinimizeBetaNitrogenTranslationDOF func = new MinimizeBetaNitrogenTranslationDOF(Space.getInstance(3), nC, density, fname, tol);
System.out.println("Initial Minimum lattice energy (per molecule): " + func.getEnergy(parameters)/func.numMolecule);
func.doFindMinimum(parameters);
System.out.println("Minimum lattice energy (per molecule): " + func.getEnergy(func.parameters)/func.numMolecule);
try {
FileWriter fileWriter = new FileWriter(fname+".out", false);
for (int i=0; i<parameters.length; i++){
fileWriter.write(parameters[i] + " ");
if(i>1 && i%10==9){
fileWriter.write("\n");
}
}
fileWriter.close();
} catch(IOException e){
throw new RuntimeException("Failed to write coord data normalize coord U" + e);
}
}
protected CoordinateDefinitionNitrogen coordinateDefinition;
protected MeterPotentialEnergy meterPotential;
protected PotentialMaster potentialMaster;
protected IBox box;
protected SpeciesN2 species;
protected double density;
protected ISpace space;
protected Primitive primitive;
protected Boundary boundary;
protected IVector[] boxDim;
protected double aDim, cDim;
protected double [] parameters;
protected int[] nC;
protected String fname;
protected double[] energy;
protected double[] allValue;
protected double tolerance;
protected double latticeEnergy;
protected int numMolecule;
private static final long serialVersionUID = 1L;
}
|
ajschult/etomica
|
etomica-apps/src/main/java/etomica/models/nitrogen/MinimizeBetaNitrogenTranslationDOF.java
|
Java
|
mpl-2.0
| 13,557
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
Authors:
Michael Berg <michael.berg@zalf.de>
//taken from https://gcc.gnu.org/wiki/Visibility
Maintainers:
Currently maintained by the authors.
This file is part of the util library used by models created at the Institute of
Landscape Systems Analysis at the ZALF.
Copyright (C) Leibniz Centre for Agricultural Landscape Research (ZALF)
*/
#ifndef DLL_EXPORTS_H
#define DLL_EXPORTS_H
// Generic helper definitions for shared library support
#if defined _WIN32 || defined __CYGWIN__
#define HELPER_DLL_IMPORT __declspec(dllimport)
#define HELPER_DLL_EXPORT __declspec(dllexport)
#define HELPER_DLL_LOCAL
#else
#if __GNUC__ >= 4
#define HELPER_DLL_IMPORT __attribute__ ((visibility ("default")))
#define HELPER_DLL_EXPORT __attribute__ ((visibility ("default")))
#define HELPER_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define HELPER_DLL_IMPORT
#define HELPER_DLL_EXPORT
#define HELPER_DLL_LOCAL
#endif
#endif
// Now we use the generic helper definitions above to define DLL_API and DLL_LOCAL.
// DLL_API is used for the public API symbols. It either DLL imports or DLL exports (or does nothing for static build)
// DLL_LOCAL is used for non-api symbols.
#ifdef USE_DLL // defined if code is compiled as a DLL
#ifdef DLL_EXPORTS // defined if we are building the DLL (instead of using it)
#define DLL_API HELPER_DLL_EXPORT
#else
#define DLL_API HELPER_DLL_IMPORT
#endif // DLL_EXPORTS
#define DLL_LOCAL HELPER_DLL_LOCAL
#else // MONICA_DLL is not defined: this means code is a static lib.
#define DLL_API
#define DLL_LOCAL
#endif // USE_DLL
#endif // DLL_EXPORTS_H
|
zalf-lsa/util
|
common/dll-exports.h
|
C
|
mpl-2.0
| 1,795
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gfile_test
import (
"os"
"testing"
"time"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_MTime(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
file1 = "/testfile_t1.txt"
err error
fileobj os.FileInfo
)
createTestFile(file1, "")
defer delTestFiles(file1)
fileobj, err = os.Stat(testpath() + file1)
t.Assert(err, nil)
t.Assert(gfile.MTime(testpath()+file1), fileobj.ModTime())
t.Assert(gfile.MTime(""), "")
})
}
func Test_MTimeMillisecond(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
file1 = "/testfile_t1.txt"
err error
fileobj os.FileInfo
)
createTestFile(file1, "")
defer delTestFiles(file1)
fileobj, err = os.Stat(testpath() + file1)
t.Assert(err, nil)
time.Sleep(time.Millisecond * 100)
t.AssertGE(
gfile.MTimestampMilli(testpath()+file1),
fileobj.ModTime().UnixNano()/1000000,
)
t.Assert(gfile.MTimestampMilli(""), -1)
})
}
|
EngineQ/gf
|
os/gfile/gfile_z_time_test.go
|
GO
|
mpl-2.0
| 1,227
|
/*
Copyright (c) 2015, Digi International Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**************************************************************************
digbankin.c
This sample program is for LP3500 series controllers.
Description
===========
This program demonstrates the use of the digital inputs.
Using the provided DEMO board in your kit to toggle a bank of
input channels from HIGH to LOW when pressing a push button on
the DEMO board.
Connections
===========
Connect +K to external power source.
When the controller is plugged into to the demo board the
following connections are readily available.
Controller Demo Board
---------- ----------
IN00 <-> S1
IN01 <-> S2
IN02 <-> S3
IN03 <-> S4
Instructions
============
1. Compile and run this program.
2. Press any one of the DEMO board switches S1 or S2 and you should
see the inputs go LOW on the bank of channels the switch is connected to.
**************************************************************************/
#class auto
// set the STDIO cursor location and display a string
void DispStr(int x, int y, char *s)
{
x += 0x20;
y += 0x20;
printf ("\x1B=%c%c%s", x, y, s);
}
// update digital inputs for the given channel range
void update_input(int bank, int col, int row)
{
auto char s[40];
auto char display[80];
auto int reading, i;
// display the input status for the given channel range
display[0] = '\0'; //initialize for strcat function
reading = digBankIn(bank); //read channels
for (i=0; i<=7; i++)
{
sprintf(s, "%d\t", reading&1); //format reading in memory
strcat(display,s); //append reading to display string
reading = reading >> 1;
}
DispStr(col, row, display); //update input status
}
///////////////////////////////////////////////////////////////////////////
void main()
{
auto int key, reading, channel;
brdInit();
//Display user instructions and channel headings
DispStr(8, 1, " <<< Digital inputs 0 - 15: >>>");
DispStr(8, 3, "IN0\tIN1\tIN2\tIN3\tIN4\tIN5\tIN6\tIN7");
DispStr(8, 4, "----\t----\t----\t----\t----\t----\t----\t----");
DispStr(8, 7, "IN8\tIN9\tIN10\tIN11\tIN12\tIN13\tIN14\tIN15");
DispStr(8, 8, "----\t----\t----\t----\t----\t----\t----\t----");
DispStr(8, 16, "Connect the Demo Bd. switches to the inputs that you what to toggle.");
DispStr(8, 17, "(See instructions in sample program for complete details)");
DispStr(8, 19, "<-PRESS 'Q' TO QUIT->");
//loop until user presses the "Q" key
for(;;)
{
// update input channels 0 - 7 (display at col = 8 row = 5)
update_input(0, 8, 5);
// update input channels 8 - 15 (display at col = 8 row = 9)
update_input(1, 8, 9);
if(kbhit())
{
key = getchar();
if (key == 'Q' || key == 'q') // check if it's the q or Q key
{
while(kbhit()) getchar();
exit(0);
}
}
}
}
///////////////////////////////////////////////////////////////////////////
|
digidotcom/DCRabbit_9
|
Samples/LP3500/IO/DIGBANKIN.C
|
C++
|
mpl-2.0
| 3,774
|
var lizLayerActionButtons = function() {
var tooltipControl = null;
var tooltipLayers = [];
var featureTypes = null;
var opacityLayers = {};
function fillSubDock( html ){
$('#sub-dock').html( html );
// Style opacity button
$('#sub-dock a.btn-opacity-layer').each(function(){
var v = $(this).text();
var op = parseInt(v) / 100 - 0.3;
$(this).css('background-color', 'rgba(0,0,0,'+op+')' );
$(this).css('background-image', 'none');
$(this).css('text-shadow', 'none');
if( parseInt(v) > 60 )
$(this).css('color', 'lightgrey');
})
// activate link buttons
$('div.sub-metadata button.link')
.click(function(){
var self = $(this);
if (self.hasClass('disabled'))
return false;
var windowLink = self.val();
// Test if the link is internal
var mediaRegex = /^(\/)?media\//;
if(mediaRegex.test(windowLink)){
var mediaLink = OpenLayers.Util.urlAppend(lizUrls.media
,OpenLayers.Util.getParameterString(lizUrls.params)
)
windowLink = mediaLink+'&path=/'+windowLink;
}
// Open link in a new window
window.open(windowLink);
});
$('#hide-sub-dock').click(function(){
var itemName = $(this).val();
var itemConfig = lizMap.config.layers[itemName];
if('type' in itemConfig)
var itemType = itemConfig.type;
else
var itemType = 'baselayer';
lizMap.events.triggerEvent(
"lizmapswitcheritemselected",
{ 'name': itemName, 'type': itemType, 'selected': false}
);
$('#switcher tr.selected').removeClass('selected');
});
}
function getLayerMetadataHtml( aName ){
var html = ''; var metadatas = null;
if( aName in lizMap.config.layers ){
var layerConfig = lizMap.config.layers[aName];
metadatas = {
title: layerConfig.title,
type: layerConfig.type,
abstract: null,
link: null,
styles: null,
isBaselayer: false
};
if( layerConfig.abstract )
metadatas.abstract = layerConfig.abstract;
if( layerConfig.link )
metadatas.link = layerConfig.link;
if( layerConfig.styles )
metadatas.styles = layerConfig.styles
}
if( lizMap.map.baseLayer && lizMap.map.baseLayer.name == aName ){
metadatas.abstract = metadatas.title;
metadatas.type = 'layer';
metadatas.link = null;
metadatas.isBaselayer = true;
}
if( metadatas ){
var layerConfig = lizMap.config.layers[aName];
// Header
html+= '<div class="sub-metadata">';
html+= '<h3>';
html+=' <span class="title">';
html+=' <span class="icon"></span>';
html+=' <span class="text">'+lizDict['layer.metadata.title']+'</span>';
html+=' </span>';
html+='</h3>';
// Content
html+= '<div class="menu-content">';
// Metadata
html+= ' <dl class="dl-vertical" style="font-size:0.8em;">';
html+= ' <dt>'+lizDict['layer.metadata.layer.name']+'</dt>';
html+= ' <dd>'+metadatas.title+'</dd>';
html+= ' <dt>'+lizDict['layer.metadata.layer.type']+'</dt>';
html+= ' <dd>'+lizDict['layer.metadata.layer.type.' + metadatas.type]+'</dd>';
// Tools
if( metadatas.type == 'layer'){
// Zoom
html+= ' <dt>'+lizDict['layer.metadata.zoomToExtent.title']+'</dt>';
html+= '<dd><button class="btn btn-mini layerActionZoom" title="'+lizDict['layer.metadata.zoomToExtent.title']+'" value="'+aName+'"><i class="icon-zoom-in"></i></button></dd>';
var isBaselayer = '';
if(metadatas.isBaselayer)
isBaselayer = 'baselayer';
// Styles
if( metadatas.styles ){
var selectedStyle = '';
var oLayer = lizMap.map.getLayersByName( aName )[0];
if( oLayer && 'STYLES' in oLayer.params) {
selectedStyle = oLayer.params['STYLES'];
}
options = '';
for( var st in metadatas.styles ){
if( st == selectedStyle )
options += '<option value="'+metadatas.styles[st]+'" selected>'+metadatas.styles[st]+'</option>';
else
options += '<option value="'+metadatas.styles[st]+'">'+metadatas.styles[st]+'</option>';
}
if( options != '' ){
html+= ' <dt>'+lizDict['layer.metadata.style.title']+'</dt>';
html+= '<dd>';
html+= '<input type="hidden" class="styleLayer '+isBaselayer+'" value="'+aName+'">';
html+= '<select class="styleLayer '+isBaselayer+'">';
html+= options;
html+= '</select>';
html+= '</dd>';
}
}
// Opacity
html+= ' <dt>'+lizDict['layer.metadata.opacity.title']+'</dt>';
html+= '<dd>';
var currentOpacity = 1;
if( aName in opacityLayers ){
currentOpacity = opacityLayers[aName];
}
html+= '<input type="hidden" class="opacityLayer '+isBaselayer+'" value="'+aName+'">';
var opacities = [0.2, 0.4, 0.6, 0.8, 1];
for ( var i=0, len=opacities.length; i<len; i++ ) {
var oactive = '';
if(currentOpacity == opacities[i])
oactive = 'active';
html+= '<a href="#" class="btn btn-mini btn-opacity-layer '+ oactive+' '+ opacities[i]*100+'">'+opacities[i]*100+'</a>';
}
html+= '</dd>';
// Export
if ( 'exportLayers' in lizMap.config.options
&& lizMap.config.options.exportLayers == 'True'
&& featureTypes != null
&& featureTypes.length != 0 ) {
var exportFormats = lizMap.getVectorLayerResultFormat();
var options = '';
for ( var i=0, len=exportFormats.length; i<len; i++ ) {
var format = exportFormats[i].tagName;
options += '<option value="'+format+'">'+format+'</option>';
}
// Export layer
// Only if layer is in attribute table
var showExport = false;
if( options != '' ) {
featureTypes.each( function(){
var self = $(this);
var typeName = self.find('Name').text();
if ( typeName == aName ) {
showExport = true;
return false;
} else if (typeName == aName.split(' ').join('_') ) {
showExport = true;
return false;
}
});
}
if( showExport ) {
html+= ' <dt>'+lizDict['layer.metadata.export.title']+'</dt>';
html+= '<dd>';
html+= '<select class="exportLayer '+isBaselayer+'">';
html+= options;
html+= '</select>';
html+= '<button class="btn btn-mini exportLayer '+isBaselayer+'" title="'+lizDict['layer.metadata.export.title']+'" value="'+aName+'"><i class="icon-download"></i></button>';
html+= '</dd>';
}
}
}
if( metadatas.abstract ){
html+= ' <dt>'+lizDict['layer.metadata.layer.abstract']+'</dt>';
html+= ' <dd>'+metadatas.abstract+'</dd>';
}
html+= ' </dl>';
// Link
if( metadatas.link ){
html+= ' <button class="btn link layer-info" name="link" title="'+lizDict['layer.metadata.layer.info.see']+'" value="'+metadatas.link+'">'+lizDict['layer.metadata.layer.info.see']+'</button>';
}
// Style
html+= '</div>';
html+= '</div>';
html+= '<button id="hide-sub-dock" class="btn btn-mini pull-right" style="margin-top:5px;" name="close" title="'+lizDict['generic.btn.close.title']+'" value="'+aName+'">'+lizDict['generic.btn.close.title']+'</button>';
}
return html;
}
function toggleMetadataSubDock(layerName, selected){
if( selected ){
var html = getLayerMetadataHtml( layerName );
fillSubDock( html );
}else{
$('#sub-dock').hide().html( '' );
return;
}
var subDockVisible = ( $('#sub-dock').css('display') != 'none' );
if( !subDockVisible ){
if( !lizMap.checkMobile() ){
var leftPos = lizMap.getDockRightPosition();
$('#sub-dock').css('left', leftPos).css('width', leftPos);
}
$('#sub-dock').show();
var mh = $('#sub-dock').height();
mh -= parseInt($('#sub-dock').css('padding-top'));
mh -= parseInt($('#sub-dock').css('padding-bottom'));
mh -= $('#sub-dock > .sub-metadata > h3').outerHeight();
mh -= parseInt($('#sub-dock > .sub-metadata > h3').css('margin-bottom'));
mh -= $('#sub-dock > button').outerHeight();
mh -= parseInt($('#sub-dock > button').css('margin-top'));
mh -= parseInt($('#sub-dock > .sub-metadata > .menu-content').css('padding-top'));
mh -= parseInt($('#sub-dock > .sub-metadata > .menu-content').css('padding-bottom'));
$('#sub-dock > .sub-metadata > .menu-content')
.css('max-height', mh)
.css('overflow', 'auto');
$(this).addClass('active');
}
}
lizMap.events.on({
'uicreated': function(evt){
featureTypes = lizMap.getVectorLayerFeatureTypes();
// title tooltip
$('#switcher-layers-actions .btn, #get-baselayer-metadata').tooltip( {
placement: 'bottom'
} );
// Expand all of unfold all
$('#layers-unfold-all').click(function(){
$('#switcher table.tree tr:not(.liz-layer.disabled) a.expander').click();
return false;
});
$('#layers-fold-all').click(function(){
$('#switcher table.tree').collapseAll();
return false;
});
// Activate get-baselayer-metadata button
$('#get-baselayer-metadata').click(function(){
$('#hide-sub-dock').click();
if( !lizMap.map.baseLayer)
return false;
var layerName = lizMap.map.baseLayer.name;
if( !layerName )
return false;
lizMap.events.triggerEvent(
"lizmapswitcheritemselected",
{ 'name': layerName, 'type': 'baselayer', 'selected': true}
);
return false;
});
// Zoom
$('#content').on('click', 'button.layerActionZoom', function(){
var layerName = $(this).val();
if( !layerName )
return false;
var itemConfig = lizMap.config.layers[layerName];
if( itemConfig.type == 'group' || !( 'extent' in itemConfig ) || !( 'crs' in itemConfig ) )
return false;
var lex = itemConfig['extent'];
var lBounds = new OpenLayers.Bounds(
lex[0],
lex[1],
lex[2],
lex[3]
);
var layerProj = new OpenLayers.Projection( itemConfig.crs );
var mapProj = lizMap.map.getProjectionObject();
mapProj = new OpenLayers.Projection( 'EPSG:3857' );
lBounds.transform(
layerProj,
mapProj
);
lizMap.map.zoomToExtent( lBounds );
// Close subdock and dock
if( lizMap.checkMobile() ){
$('#hide-sub-dock').click();
$('#button-switcher').click();
}
return false;
});
// Opacity
$('#content').on('change', 'select.styleLayer', function(){
// Get chosen style
var eStyle = $(this).val();
// Get layer name and type
var h = $(this).parent().find('input.styleLayer');
var eName = h.val();
var isBaselayer = h.hasClass('baselayer');
if( !eName )
return false;
// Get layer
var layer = null;
if( isBaselayer){
layer = lizMap.map.baseLayer;
}else{
layer = lizMap.map.getLayersByName( lizMap.cleanName(eName) )[0];
}
// Set style
if( layer && layer.params) {
layer.params['STYLES'] = eStyle;
layer.redraw( true );
lizMap.events.triggerEvent(
"layerstylechanged",
{ 'featureType': eName}
);
}
});
// Opacity
$('#content').on('click', 'a.btn-opacity-layer', function(){
// Get chosen opacity
var eVal = $(this).text();
var opacity = parseInt(eVal) / 100;
// Get layer name and type
var h = $(this).parent().find('input.opacityLayer');
var eName = h.val();
var isBaselayer = h.hasClass('baselayer');
if( !eName )
return false;
// Get layer
var layer = null;
if( isBaselayer){
layer = lizMap.map.baseLayer;
}else{
layer = lizMap.map.getLayersByName( lizMap.cleanName(eName) )[0];
}
// Set opacity
if( layer && layer.params) {
layer.setOpacity(opacity);
opacityLayers[eName] = opacity;
$('a.btn-opacity-layer').removeClass('active');
$('a.btn-opacity-layer.' + opacity*100).addClass('active');
}
// Blur dropdown or baselayer button
$('#switcher').click();
// Close subdock and dock
if( lizMap.checkMobile() ){
$('#hide-sub-dock').click();
$('#button-switcher').click();
}
return false;
});
// Export
$('#content').on('click', 'button.exportLayer', function(){
var eName = $(this).val();
var eFormat = $(this).parent().find('select.exportLayer').val();
lizMap.exportVectorLayer( eName, eFormat );
return false;
});
// Cancel Lizmap global filter
$('#layerActionUnfilter').click(function(){
var layerName = lizMap.lizmapLayerFilterActive;
if( !layerName )
return false;
lizMap.events.triggerEvent(
"layerfeatureremovefilter",
{ 'featureType': layerName}
);
lizMap.lizmapLayerFilterActive = null;
$(this).hide();
return false;
});
lizMap.events.on({
dockclosed: function(e) {
if ( e.id == 'switcher' ) {
$('#hide-sub-dock').click();
}
}
});
},
'lizmapswitcheritemselected': function(evt){
// Get item properties
var itemName = '';
var itemType = evt.type;
var itemSelected = evt.selected;
var itemConfig = {};
// Get item Lizmap config
if( itemType == 'baselayer'){
itemName = evt.name;
}else{
var layerName = lizMap.getLayerNameByCleanName( lizMap.cleanName(evt.name) );
if( layerName ){
itemName = layerName;
itemConfig = lizMap.config.layers[layerName];
}
else{
return false;
}
}
// Change action buttons values
var btValue = itemName;
if( !itemSelected )
btValue = '';
$('#switcher-layers-actions button').val( btValue );
// Toggle buttons depending on itemType
// Zoom to layer
var zoomStatus = (itemType == 'group' || !itemSelected || !('extent' in itemConfig) );
$('button.layerActionZoom').attr( 'disable', zoomStatus ).toggleClass( 'disabled', zoomStatus );
// Refresh sub-dock content
toggleMetadataSubDock(itemName, itemSelected);
}
});
//console.log($('#layers-unfold-all').length);
}();
|
aeag/lizmap-web-client
|
lizmap/www/js/switcher-layers-actions.js
|
JavaScript
|
mpl-2.0
| 17,683
|
Components.utils.import("resource://gre/modules/Services.jsm");
const nsIInterfaceRequestor = Components.interfaces.nsIInterfaceRequestor;
const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
const nsIDocShellTreeItem = Components.interfaces.nsIDocShellTreeItem;
const nsIDOMWindow = Components.interfaces.nsIDOMWindow;
var bgWindow = null;
function OnShortcutsPaneLoad()
{
GetUIElements();
bgWindow = Services.wm.getMostRecentWindow("bluegriffon");
if (bgWindow) {
gDialog.commandsShortcutsTree.disabled = false;
GetMenuItems(gDialog.menubarShortcutsTreechildren,
bgWindow.gDialog["composer-main-menubar"],
"#composer-main-menubar");
var toolbars = bgWindow.document.querySelectorAll("toolbar");
for (var i = 0; i < toolbars.length; i++) {
var toolbar = toolbars[i];
if (toolbar.id)
GetToolbarItems(gDialog.toolbarsShortcutsTreechildren,
toolbar,
"#" + toolbar.id);
else
GetToolbarItems(gDialog.toolbarsShortcutsTreechildren,
toolbar,
"toolbar:nth-of-type(" + (i+1) + ")");
}
}
else { // certainly only on Mac...
Services.prompt.alert(null, gDialog.shortcutsBundle.getString("NoMainWindowAvaialble"),
gDialog.shortcutsBundle.getString("PleaseOpenOneMainWindow"));
gDialog.commandsShortcutsTree.disabled = true;
}
}
function GetToolbarItems(aTreechildren, aElt, aSelector)
{
var child = aElt.firstChild;
var index = 1;
while (child) {
switch (child.nodeName.toLowerCase()) {
case "toolbaritem":
case "menupopup":
if (child.id)
GetToolbarItems(aTreechildren, child, "#" + child.id);
else
GetToolbarItems(aTreechildren, child, aSelector + "> :nth-child(" + index + ")");
break;
case "menulist":
{
var item = document.createElement("treeitem");
var row = document.createElement("treerow");
var cell = document.createElement("treecell");
var children = document.createElement("treechildren");
item.setAttribute("container", "true");
cell.setAttribute("label", child.getAttribute("tooltiptext"));
row.appendChild(cell);
item.appendChild(row);
item.appendChild(children);
aTreechildren.appendChild(item);
if (child.id)
GetToolbarItems(children, child, "#" + child.id);
else
GetToolbarItems(children, child, aSelector + "> :nth-child(" + index + ")");
}
break;
case "menuitem":
case "toolbarbutton":
{
var label = "";
if (child.hasAttribute("label"))
label = child.getAttribute("label");
else if (child.hasAttribute("command")) {
var cmdElt = bgWindow.document.getElementById(child.getAttribute("command"));
if (cmdElt && cmdElt.hasAttribute("label"))
label = cmdElt.getAttribute("label");
}
if (!label && child.hasAttribute("tooltiptext"))
label = child.getAttribute("tooltiptext")
// wait, wait, wait, we have the case of a toolbarbutton type="menu" thing... sigh
if (child.nodeName.toLowerCase() == "toolbarbutton"
&& (child.getAttribute("type") == "menu"
|| child.getAttribute("type") == "menu-button")) {
var item = document.createElement("treeitem");
var row = document.createElement("treerow");
var cell = document.createElement("treecell");
var children = document.createElement("treechildren");
item.setAttribute("container", "true");
cell.setAttribute("label", label);
row.appendChild(cell);
item.appendChild(row);
item.appendChild(children);
aTreechildren.appendChild(item);
if (child.id)
GetToolbarItems(children, child, "#" + child.id);
else
GetToolbarItems(children, child, aSelector + "> :nth-child(" + index + ")");
break;
}
if (true) { // here, we must keep everything
var item = document.createElement("treeitem");
var row = document.createElement("treerow");
var cell = document.createElement("treecell");
cell.setAttribute("label", label);
row.appendChild(cell);
if (child.hasAttribute("key")) {
var keyElt = bgWindow.document.getElementById(child.getAttribute("key"));
if (keyElt) {
var cell2 = document.createElement("treecell");
var modifiers = keyElt.getAttribute("modifiers");
var modifiersArray = modifiers.split(",");
var keyString = (keyElt.hasAttribute("keycode")
? keyElt.getAttribute("keycode").replace( /VK_/ , "")
: keyElt.getAttribute("key")).toUpperCase();
var str = GetModifiersStringFromModifiersArray(modifiersArray);
cell2.setAttribute("label", str + keyString);
item.setAttribute("shortcut", str + keyString);
item.setAttribute("modifiers", modifiers);
item.setAttribute("kbdkey", keyString);
item.setAttribute("toolbaritem", "true");
row.appendChild(cell2);
}
}
item.appendChild(row);
aTreechildren.appendChild(item);
if (child.id)
item.setAttribute("selector", "#" + child.id);
else
item.setAttribute("selector", aSelector + "> :nth-child(" + index + ")");
}
}
break;
default: break;
}
child = child.nextElementSibling;
index++;
}
}
function GetMenuItems(aTreechildren, aElt, aSelector)
{
var child = aElt.firstChild;
var index = 1;
while (child) {
switch (child.nodeName.toLowerCase()) {
case "menu":
{
var item = document.createElement("treeitem");
var row = document.createElement("treerow");
var cell = document.createElement("treecell");
var children = document.createElement("treechildren");
item.setAttribute("container", "true");
cell.setAttribute("label", child.getAttribute("label"));
row.appendChild(cell);
item.appendChild(row);
item.appendChild(children);
aTreechildren.appendChild(item);
if (child.id)
GetMenuItems(children, child, "#" + child.id);
else
GetMenuItems(children, child, aSelector + "> :nth-child(" + index + ")");
}
break;
case "menupopup":
if (child.id)
GetMenuItems(aTreechildren, child, "#" + child.id);
else
GetMenuItems(aTreechildren, child, aSelector + "> :nth-child(" + index + ")");
break;
case "menuitem":
{
var label = "";
if (child.hasAttribute("label"))
label = child.getAttribute("label");
else if (child.hasAttribute("command")) {
var cmdElt = bgWindow.document.getElementById(child.getAttribute("command"));
if (cmdElt && cmdElt.hasAttribute("label"))
label = cmdElt.getAttribute("label");
}
if (label) {
var item = document.createElement("treeitem");
var row = document.createElement("treerow");
var cell = document.createElement("treecell");
cell.setAttribute("label", label);
row.appendChild(cell);
if (child.hasAttribute("key")) {
var keyElt = bgWindow.document.getElementById(child.getAttribute("key"));
if (keyElt) {
var cell2 = document.createElement("treecell");
var modifiers = keyElt.getAttribute("modifiers");
var modifiersArray = modifiers.split(",");
var keyString = (keyElt.hasAttribute("keycode")
? keyElt.getAttribute("keycode").replace( /VK_/ , "")
: keyElt.getAttribute("key")).toUpperCase();
var str = GetModifiersStringFromModifiersArray(modifiersArray);
cell2.setAttribute("label", str + keyString);
item.setAttribute("shortcut", str + keyString);
item.setAttribute("modifiers", modifiers);
item.setAttribute("kbdkey", keyString);
row.appendChild(cell2);
}
}
item.appendChild(row);
aTreechildren.appendChild(item);
if (child.id)
item.setAttribute("selector", "#" + child.id);
else
item.setAttribute("selector", aSelector + "> :nth-child(" + index + ")");
break;
}
}
break;
default: break;
}
child = child.nextElementSibling;
index++;
}
}
function GetModifiersStringFromModifiersArray(modifiersArray)
{
var str = "";
if (modifiersArray.indexOf("shift") != -1)
#ifdef XP_MACOSX
str += "⇧";
#else
str += "shift-";
#endif
if (modifiersArray.indexOf("control") != -1)
#ifdef XP_MACOSX
str += "⌃";
#else
str += "ctrl-";
#endif
if (modifiersArray.indexOf("alt") != -1)
#ifdef XP_MACOSX
str += "⌥";
#else
str += "alt";
#endif
if (modifiersArray.indexOf("meta") != -1)
#ifdef XP_UNIX
#ifdef XP_MACOSX
str += "⌘";
#else
str += "meta-";
#endif
#else
str += "windows-"
#endif
if (modifiersArray.indexOf("accel") != -1)
#ifdef XP_MACOSX
str += "⌘";
#else
str += "ctrl-";
#endif
return str;
}
function EditShortCut()
{
var tree = gDialog.commandsShortcutsTree;
var contentView = tree.contentView;
var view = tree.view;
if (!view || !view.selection || !view.selection.count) { // no selection...
return;
}
var index = view.selection.currentIndex;
var item = contentView.getItemAtIndex(index);
if (item.hasAttribute("container"))
return;
var selector = item.getAttribute("selector");
var modifiers = item.getAttribute("modifiers");
var kbdkey = item.getAttribute("kbdkey");
var shortcut = item.getAttribute("shortcut");
var rv = {};
window.openDialog("chrome://bluegriffon/content/prefs/editShortcut.xul",
"_blank",
"chrome,modal,titlebar,resizable=no",
item.firstChild.firstChild.getAttribute("label"),
selector, modifiers, kbdkey, shortcut, rv);
if (rv && ("cancelled" in rv))
return;
if (rv && ("deleted" in rv)) {
DeleteShortCut(item);
return;
}
AddShortCut(item, rv);
}
function _DeleteShortCut(aItem)
{
aItem.removeAttribute("shortcut");
aItem.removeAttribute("modifiers");
aItem.removeAttribute("kbdkey");
aItem.firstChild.removeChild(aItem.firstChild.lastChild);
var selector = aItem.getAttribute("selector");
var ee = Services.wm.getEnumerator("bluegriffon");
while (ee.hasMoreElements()) {
var w = ee.getNext();
var navNav = w.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIWebNavigation);
var rootItem = navNav.QueryInterface(nsIDocShellTreeItem).rootTreeItem;
var rootWin = rootItem.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIDOMWindow);
var elt = rootWin.document.querySelector(selector);
if (elt) { // sanity check
var keyId = elt.getAttribute("key");
if (keyId) {
try {
var keyElt = rootWin.document.getElementById(keyId)
if (keyElt) {
elt.setAttribute("key", "");
elt.removeAttribute("key");
var keyset = keyElt.parentNode;
keyElt.parentNode.removeChild(keyElt);
// need to reinstall the keyset...
var parent = keyset.parentNode;
var nextSibling = parent.nextSibling;
parent.removeChild(keyset);
parent.insertBefore(keyset, nextSibling);
}
}
catch(e) {}
}
}
}
}
function DeleteShortCut(aItem)
{
_DeleteShortCut(aItem);
StoreAllShortcuts();
}
function AddShortCut(aItem, aRv)
{
// modify the tree in the prefs window
var mArray = [];
if (aRv.shiftKey) mArray.push("shift");
if (aRv.altKey) mArray.push("alt");
if (aRv.ctrlKey) mArray.push("control");
if (aRv.metaKey) mArray.push("meta");
aItem.setAttribute("modifiers", mArray.length ? mArray.join(",") : "");
aItem.setAttribute("kbdkey", aRv.key);
// check if shortcut is already used...
var conflictItems = document.querySelectorAll("treeitem[kbdkey='" + aRv.key +"']");
for (var i = 0; i < conflictItems.length; i++) {
var ci = conflictItems[i];
if (ci != aItem) {
var m = ci.getAttribute("modifiers").toLowerCase()
#ifdef XP_MACOSX
.replace( /accel/ , "meta")
#else
.replace( /accel/ , "control")
#endif
.split(",");
if (m.sort().toSource() == mArray.sort().toSource()) {
// something to remove guys...
var selector = ci.getAttribute("selector");
_DeleteShortCut(ci);
}
}
}
if (aItem.getAttribute("shortcut")) { // already has a key mapping
aItem.firstChild.lastChild.setAttribute("label", aRv.shortcut);
// now modify the menu item itself
// don't forget the menu item already has a key attached
var selector = aItem.getAttribute("selector");
var ee = Services.wm.getEnumerator("bluegriffon");
while (ee.hasMoreElements()) {
var w = ee.getNext();
var navNav = w.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIWebNavigation);
var rootItem = navNav.QueryInterface(nsIDocShellTreeItem).rootTreeItem;
var rootWin = rootItem.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIDOMWindow);
var elt = rootWin.document.querySelector(selector);
if (elt) { // sanity check
var keyId = elt.getAttribute("key");
if (keyId) {
try {
var keyElt = rootWin.document.getElementById(keyId)
if (keyElt) {
elt.removeAttribute("key");
keyElt.setAttribute("modifiers", aItem.getAttribute("modifiers"));
keyElt.removeAttribute("key");
keyElt.removeAttribute("keycode");
if (aRv.key.length == 1)
keyElt.setAttribute("key", aRv.key);
else
keyElt.setAttribute("keycode", aRv.key);
var parent = keyElt.parentNode;
var nextSibling = parent.nextSibling;
parent.parentNode.removeChild(parent);
nextSibling.parentNode.insertBefore(parent, nextSibling);
elt.setAttribute("key", keyId);
}
}
catch(e) {}
}
}
}
}
else {
var cell = document.createElement("treecell");
cell.setAttribute("label", aRv.shortcut);
aItem.firstChild.appendChild(cell);
// no key mapping yet
var selector = aItem.getAttribute("selector");
var isToolbarItem = aItem.hasAttribute("toolbaritem");
var ee = Services.wm.getEnumerator("bluegriffon");
while (ee.hasMoreElements()) {
var w = ee.getNext();
var navNav = w.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIWebNavigation);
var rootItem = navNav.QueryInterface(nsIDocShellTreeItem).rootTreeItem;
var rootWin = rootItem.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIDOMWindow);
var elt = rootWin.document.querySelector(selector);
var keyset = rootWin.document.getElementById("mainKeySet");
if (elt) { // sanity check
var keyElt = rootWin.document.createElement("key");
keyElt.setAttribute("modifiers", mArray.length ? mArray.join(",") : "");
if (aRv.key.length == 1)
keyElt.setAttribute("key", aRv.key);
else
keyElt.setAttribute("keycode", aRv.key);
if (elt.hasAttribute("command"))
keyElt.setAttribute("command", elt.getAttribute("command"));
if (elt.hasAttribute("oncommand"))
keyElt.setAttribute("oncommand", elt.getAttribute("oncommand"));
if (!elt.hasAttribute("command") && !elt.hasAttribute("oncommand")) {
var cmdStr = 'var e = document.createEvent("Events"); e.initEvent("command", true, true); document.querySelector("'
+ selector
+'").dispatchEvent(e);';
keyElt.setAttribute("oncommand", cmdStr);
}
var keyId = "key-" + (mArray.length ? mArray.join("-") : "") + aRv.key;
keyElt.setAttribute("id", keyId);
keyset.appendChild(keyElt);
elt.setAttribute("key", keyId);
var parent = keyset.parentNode;
var nextSibling = parent.nextSibling;
parent.removeChild(keyset);
parent.insertBefore(keyset, nextSibling);
}
}
}
aItem.setAttribute("shortcut", aRv.shortcut);
StoreAllShortcuts();
}
function GetDBConn()
{
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
file.append("shortcuts.sqlite");
var storageService = Components.classes["@mozilla.org/storage/service;1"]
.getService(Components.interfaces.mozIStorageService);
return storageService.openDatabase(file);
}
function InitShortcutDB()
{
// create the SQLite table if it does not exist already
var mDBConn = GetDBConn();
mDBConn.executeSimpleSQL("CREATE TABLE IF NOT EXISTS 'shortcuts' ('id' INTEGER PRIMARY KEY NOT NULL, \
'selector' VARCHAR NOT NULL DEFAULT '', \
'modifiers' VARCHAR NOT NULL DEFAULT '', \
'key' VARCHAR NOT NULL DEFAULT '')");
mDBConn.close();
}
function StoreAllShortcuts()
{
InitShortcutDB();
// clobber all
var mDBConn = GetDBConn();
mDBConn.executeSimpleSQL("DELETE FROM 'shortcuts'");
var items = gDialog.commandsShortcutsTree.querySelectorAll("treeitem[shortcut]");
for (var i = 0; i < items.length; i++) {
var item = items[i];
var selector = item.getAttribute("selector");
var modifiers = item.getAttribute("modifiers");
var kbdkey = item.getAttribute("kbdkey");
var statement = mDBConn.createStatement(
"INSERT INTO 'shortcuts' ('selector','modifiers','key') VALUES(?1, ?2, ?3)");
statement.bindStringParameter(0, selector);
statement.bindStringParameter(1, modifiers);
statement.bindStringParameter(2, kbdkey);
statement.execute();
statement.finalize();
}
mDBConn.close();
}
|
therealglazou/bluegriffon
|
base/content/bluegriffon/prefs/shortcuts.js
|
JavaScript
|
mpl-2.0
| 19,048
|
using System.Collections.Generic;
using L2dotNET.Enums;
using L2dotNET.GameService.Model.Items;
namespace L2dotNET.GameService.Templates
{
public class PcTemplate : CharTemplate
{
public ClassId ClassId { get; set; }
public int FallingHeight { get; }
public int BaseSwimSpd { get; }
public double CollisionRadiusFemale { get; }
public double CollisionHeightFemale { get; }
public int SpawnX { get; }
public int SpawnY { get; }
public int SpawnZ { get; }
public int ClassBaseLevel { get; }
public double[] HpTable { get; }
public double[] MpTable { get; }
public double[] CpTable { get; }
public List<L2Item> Items { get; } = new List<L2Item>();
public PcTemplate(ClassId classId, StatsSet set) : base(set)
{
ClassId = classId;
BaseSwimSpd = set.GetInt("swimSpd", 1);
FallingHeight = set.GetInt("falling_height", 333);
CollisionRadiusFemale = set.GetDouble("radiusFemale");
CollisionHeightFemale = set.GetDouble("heightFemale");
SpawnX = set.GetInt("spawnX");
SpawnY = set.GetInt("spawnY");
SpawnZ = set.GetInt("spawnZ");
ClassBaseLevel = set.GetInt("baseLvl");
string[] hpTable = set.GetString("hpTable").Split(';');
HpTable = new double[hpTable.Length];
for (int i = 0; i < hpTable.Length; i++)
HpTable[i] = double.Parse(hpTable[i]);
string[] mpTable = set.GetString("mpTable").Split(';');
MpTable = new double[mpTable.Length];
for (int i = 0; i < mpTable.Length; i++)
MpTable[i] = double.Parse(mpTable[i]);
string[] cpTable = set.GetString("cpTable").Split(';');
CpTable = new double[cpTable.Length];
for (int i = 0; i < cpTable.Length; i++)
CpTable[i] = double.Parse(cpTable[i]);
}
}
}
|
MartLegion/L2dotNET
|
src/L2dotNET.GameService/templates/PcTemplate.cs
|
C#
|
mpl-2.0
| 2,016
|
<?php
declare(strict_types=1);
namespace CirclicalUser\Exception;
use Exception;
class InvalidResetTokenIpAddressException extends Exception
{
}
|
Saeven/zf3-circlical-user
|
src/Exception/InvalidResetTokenIpAddressException.php
|
PHP
|
mpl-2.0
| 149
|
/**
* Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Contains objects to use optional dependencies.
* @author thierry.bouvet@mpsa.com
*
*/
package org.seedstack.seed.core.spi.dependency;
|
tbouvet/seed
|
specs/src/main/java/org/seedstack/seed/core/spi/dependency/package-info.java
|
Java
|
mpl-2.0
| 429
|
package compute
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// VirtualMachineRunCommandsClient is the compute Client
type VirtualMachineRunCommandsClient struct {
BaseClient
}
// NewVirtualMachineRunCommandsClient creates an instance of the VirtualMachineRunCommandsClient client.
func NewVirtualMachineRunCommandsClient(subscriptionID string) VirtualMachineRunCommandsClient {
return NewVirtualMachineRunCommandsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewVirtualMachineRunCommandsClientWithBaseURI creates an instance of the VirtualMachineRunCommandsClient client.
func NewVirtualMachineRunCommandsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineRunCommandsClient {
return VirtualMachineRunCommandsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get gets specific run command for a subscription in a location.
// Parameters:
// location - the location upon which run commands is queried.
// commandID - the command id.
func (client VirtualMachineRunCommandsClient) Get(ctx context.Context, location string, commandID string) (result RunCommandDocument, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: location,
Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, location, commandID)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client VirtualMachineRunCommandsClient) GetPreparer(ctx context.Context, location string, commandID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"commandId": autorest.Encode("path", commandID),
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-12-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) GetResponder(resp *http.Response) (result RunCommandDocument, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List lists all available run commands for a subscription in a location.
// Parameters:
// location - the location upon which run commands is queried.
func (client VirtualMachineRunCommandsClient) List(ctx context.Context, location string) (result RunCommandListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List")
defer func() {
sc := -1
if result.rclr.Response.Response != nil {
sc = result.rclr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: location,
Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "List", err.Error())
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, location)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.rclr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure sending request")
return
}
result.rclr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client VirtualMachineRunCommandsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-12-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) ListResponder(resp *http.Response) (result RunCommandListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client VirtualMachineRunCommandsClient) listNextResults(ctx context.Context, lastResults RunCommandListResult) (result RunCommandListResult, err error) {
req, err := lastResults.runCommandListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualMachineRunCommandsClient) ListComplete(ctx context.Context, location string) (result RunCommandListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, location)
return
}
|
joelthompson/vault
|
vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-12-01/compute/virtualmachineruncommands.go
|
GO
|
mpl-2.0
| 9,693
|
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec referrer-policy/` -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'no-referrer-when-downgrade'</title>
<meta charset='utf-8'>
<meta name="description" content="Check that non a priori insecure subresource gets the full Referrer URL. A priori insecure subresource gets no referrer information.">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-no-referrer-when-downgrade">
<meta name="assert" content="Referrer Policy: Expects stripped-referrer for xhr to same-https origin and no-redirect redirection from http context.">
<meta name="referrer" content="no-referrer-when-downgrade">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="../../../../generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "stripped-referrer",
"origin": "same-https",
"redirection": "no-redirect",
"source_context_list": [
{
"policyDeliveries": [],
"sourceContextType": "srcdoc"
}
],
"source_scheme": "http",
"subresource": "xhr",
"subresource_policy_deliveries": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
|
UK992/servo
|
tests/wpt/web-platform-tests/referrer-policy/gen/srcdoc-inherit.meta/no-referrer-when-downgrade/xhr/same-https.no-redirect.http.html
|
HTML
|
mpl-2.0
| 1,724
|
/*
* TemporalStability.hpp
*
* Copyright (c) 2015 Alberto Alonso Gonzalez
*
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Created on: 17/07/2015
* Author: Alberto Alonso-Gonzalez
*/
#ifndef TEMPORALSTABILITY_HPP_
#define TEMPORALSTABILITY_HPP_
#include <armadillo>
#include <functional>
namespace tscbpt
{
template <class NodePointer, class ValueType = double>
struct GeodesicVectorChangeMeasureFull: public std::unary_function<NodePointer, ValueType>
{
ValueType operator()(const NodePointer a) const {
ValueType res = ValueType();
const size_t covariances = a->getModel().getNumCovariances();
const size_t comparations = covariances - 1;
arma::cx_mat vma[covariances];
for(size_t i = 0; i < covariances; ++i){
vma[i] = to_arma<arma::cx_mat>::from(a->getModel().getCovariance(i));
}
#pragma omp parallel for num_threads(min(static_cast<int>(comparations), omp_get_max_threads())) schedule(dynamic, 1) shared(vma) reduction(+:res) default(none)
for(size_t i = 0; i < comparations; ++i){
for(size_t j = i+1; j < covariances; ++j){
arma::cx_vec eigval;
arma::cx_mat eigvec;
arma::eig_gen(eigval, eigvec, solve(vma[i], vma[j]));
res += sqrt(accu(pow(log(abs(eigval)),2)));
}
}
return res / (comparations*covariances/2.0);
}
};
template <class NodePointer, class ValueType = double>
struct DiagonalGeodesicVectorChangeMeasureFull: public std::unary_function<NodePointer, ValueType>
{
ValueType operator()(NodePointer a) const {
static const ValueType DG_MIN_THRESHOLD = 1e-12;
ValueType res = ValueType();
for(size_t i = 0; i < a->getModel().getNumCovariances() - 1; ++i){
for(size_t j = i+1; j < a->getModel().getNumCovariances(); ++j){
double tmp = 0;
for(size_t k = 0; k < a->getModel().subMatrix_size; ++k){
tmp += pow(log(max(a->getModel().getCovariance(i)(k, k).real(), DG_MIN_THRESHOLD) / max(a->getModel().getCovariance(j)(k, k).real(), DG_MIN_THRESHOLD)), 2);
}
res += sqrt(tmp);
}
}
return res / ((a->getModel().getNumCovariances() - 1) * (a->getModel().getNumCovariances()) / 2);
}
};
template <class NodePointer, class SimilarityMeasure, class ValueType = double>
struct SimilarityToRegion: public std::unary_function<NodePointer, ValueType>
{
SimilarityToRegion(NodePointer pRefNode, SimilarityMeasure pSim = SimilarityMeasure())
: refNode(pRefNode), measure(pSim){ }
ValueType operator()(NodePointer a) const {
return measure(refNode, a);
}
private:
NodePointer refNode;
SimilarityMeasure measure;
};
template <class NodePointer, class ValueType = double>
struct GeodesicVectorPairChangeMeasure: public std::unary_function<NodePointer, ValueType>
{
GeodesicVectorPairChangeMeasure(size_t a, size_t b): _a(a), _b(b){}
ValueType operator()(const NodePointer a) const {
arma::cx_vec eigval;
arma::cx_mat eigvec;
arma::eig_gen(eigval, eigvec, solve(
to_arma<arma::cx_mat>::from(a->getModel().getCovariance(_a)),
to_arma<arma::cx_mat>::from(a->getModel().getCovariance(_b))));
return ValueType(sqrt(accu(pow(log(abs(eigval)),2))));
}
private:
size_t _a, _b;
};
} /* namespace tscbpt */
#endif /* TEMPORALSTABILITY_HPP_ */
|
aalgo/TSCBPT
|
include/tsc/bpt/TemporalStability.hpp
|
C++
|
mpl-2.0
| 3,330
|
package org.bear.bookstore.lamda;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class LamdaTest {
public static void main(String[] args) {
List<Test1> list = new ArrayList<>();
Test1 t = new Test1() {
};
}
}
interface Test1{
default String f(){
return "";
}
}
|
zhougithui/bookstore-single
|
src/test/java/org/bear/bookstore/lamda/LamdaTest.java
|
Java
|
mpl-2.0
| 338
|
#!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ----------------------------------------------------------------------------------------
# Reads board information from boards/BOARDNAME.py - used by build_board_docs,
# build_pininfo, and build_platform_config
# ----------------------------------------------------------------------------------------
import subprocess;
import re;
import json;
import sys;
import os;
import importlib;
silent = os.getenv("SILENT");
if silent:
class Discarder(object):
def write(self, text):
pass # do nothing
# now discard everything coming out of stdout
sys.stdout = Discarder()
# http://stackoverflow.com/questions/4814970/subprocess-check-output-doesnt-seem-to-exist-python-2-6-5
if "check_output" not in dir( subprocess ):
def f(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
subprocess.check_output = f
# Scans files for comments of the form /*JSON......*/
#
# Comments look like:
#
#/*JSON{ "type":"staticmethod|staticproperty|constructor|method|property|function|variable|class|library|idle|init|kill",
# // class = built-in class that does not require instantiation
# // library = built-in class that needs require('classname')
# // idle = function to run on idle regardless
# // init = function to run on initialisation
# // kill = function to run on deinitialisation
# "class" : "Double", "name" : "doubleToIntBits",
# "needs_parentName":true, // optional - if for a method, this makes the first 2 args parent+parentName (not just parent)
# "generate_full|generate|wrap" : "*(JsVarInt*)&x",
# "description" : " Convert the floating point value given into an integer representing the bits contained in it",
# "params" : [ [ "x" , "float|int|int32|bool|pin|JsVar|JsVarName|JsVarArray", "A floating point number"] ],
# // float - parses into a JsVarFloat which is passed to the function
# // int - parses into a JsVarInt which is passed to the function
# // int32 - parses into a 32 bit int
# // bool - parses into a boolean
# // pin - parses into a pin
# // JsVar - passes a JsVar* to the function (after skipping names)
# // JsVarArray - parses this AND ANY SUBSEQUENT ARGUMENTS into a JsVar of type JSV_ARRAY. THIS IS ALWAYS DEFINED, EVEN IF ZERO LENGTH. Currently it must be the only parameter
# "return" : ["int|float|JsVar", "The integer representation of x"],
# "return_object" : "ObjectName", // optional - used for tern's code analysis - so for example we can do hints for openFile(...).yyy
# "no_create_links":1 // optional - if this is set then hyperlinks are not created when this name is mentioned (good example = bit() )
# "not_real_object" : "anything", // optional - for classes, this means we shouldn't treat this as a built-in object, as internally it isn't stored in a JSV_OBJECT
# "prototype" : "Object", // optional - for classes, this is what their prototype is. It's particlarly helpful if not_real_object, because there is no prototype var in that case
# "check" : "jsvIsFoo(var)", // for classes - this is code that returns true if 'var' is of the given type
# "ifndef" : "SAVE_ON_FLASH", // if the given preprocessor macro is defined, don't implement this
# "ifdef" : "USE_LCD_FOO", // if the given preprocessor macro isn't defined, don't implement this
# "#if" : "A>2", // add a #if statement in the generated C file (ONLY if type==object)
#}*/
#
# description can be an array of strings as well as a simple string (in which case each element is separated by a newline),
# and adding ```sometext``` in the description surrounds it with HTML code tags
#
def get_jsondata(is_for_document, parseArgs = True, board = False):
scriptdir = os.path.dirname (os.path.realpath(__file__))
print("Script location "+scriptdir)
os.chdir(scriptdir+"/..")
jswraps = []
defines = []
if board and ("build" in board.info) and ("defines" in board.info["build"]):
for i in board.info["build"]["defines"]:
print("Got define from board: " + i);
defines.append(i)
if parseArgs and len(sys.argv)>1:
print("Using files from command line")
for i in range(1,len(sys.argv)):
arg = sys.argv[i]
if arg[0]=="-":
if arg[1]=="D":
defines.append(arg[2:])
elif arg[1]=="B":
board = importlib.import_module(arg[2:])
if "usart" in board.chip: defines.append("USART_COUNT="+str(board.chip["usart"]));
if "spi" in board.chip: defines.append("SPI_COUNT="+str(board.chip["spi"]));
if "i2c" in board.chip: defines.append("I2C_COUNT="+str(board.chip["i2c"]));
if "USB" in board.devices: defines.append("defined(USB)=True");
else: defines.append("defined(USB)=False");
elif arg[1]=="F":
"" # -Fxxx.yy in args is filename xxx.yy, which is mandatory for build_jswrapper.py
else:
print("Unknown command-line option")
exit(1)
else:
jswraps.append(arg)
else:
print("Scanning for jswrap.c files")
jswraps = subprocess.check_output(["find", ".", "-name", "jswrap*.c"]).strip().split("\n")
if len(defines)>1:
print("Got #DEFINES:")
for d in defines: print(" "+d)
jsondatas = []
for jswrap in jswraps:
# ignore anything from archives
if jswrap.startswith("./archives/"): continue
# now scan
print("Scanning "+jswrap)
code = open(jswrap, "r").read()
if is_for_document and "DO_NOT_INCLUDE_IN_DOCS" in code:
print("FOUND 'DO_NOT_INCLUDE_IN_DOCS' IN FILE "+jswrap)
continue
for comment in re.findall(r"/\*JSON.*?\*/", code, re.VERBOSE | re.MULTILINE | re.DOTALL):
charnumber = code.find(comment)
linenumber = 1+code.count("\n", 0, charnumber)
# Strip off /*JSON .. */ bit
comment = comment[6:-2]
endOfJson = comment.find("\n}")+2;
jsonstring = comment[0:endOfJson];
description = comment[endOfJson:].strip();
# print("Parsing "+jsonstring)
try:
jsondata = json.loads(jsonstring)
if len(description): jsondata["description"] = description;
jsondata["filename"] = jswrap
jsondata["include"] = jswrap[:-2]+".h"
jsondata["githublink"] = "https://github.com/espruino/Espruino/blob/master/"+jswrap+"#L"+str(linenumber)
dropped_prefix = "Dropped "
if "name" in jsondata: dropped_prefix += jsondata["name"]+" "
elif "class" in jsondata: dropped_prefix += jsondata["class"]+" "
drop = False
if not is_for_document:
if ("ifndef" in jsondata) and (jsondata["ifndef"] in defines):
print(dropped_prefix+" because of #ifndef "+jsondata["ifndef"])
drop = True
if ("ifdef" in jsondata) and not (jsondata["ifdef"] in defines):
print(dropped_prefix+" because of #ifdef "+jsondata["ifdef"])
drop = True
if ("#if" in jsondata):
expr = jsondata["#if"]
for defn in defines:
if defn.find('=')!=-1:
dname = defn[:defn.find('=')]
dkey = defn[defn.find('=')+1:]
expr = expr.replace(dname, dkey);
try:
r = eval(expr)
except:
print("WARNING: error evaluating '"+expr+"' - from '"+jsondata["#if"]+"'")
r = True
if not r:
print(dropped_prefix+" because of #if "+jsondata["#if"]+ " -> "+expr)
drop = True
if not drop:
jsondatas.append(jsondata)
except ValueError as e:
sys.stderr.write( "JSON PARSE FAILED for " + jsonstring + " - "+ str(e) + "\n")
exit(1)
except:
sys.stderr.write( "JSON PARSE FAILED for " + jsonstring + " - "+str(sys.exc_info()[0]) + "\n" )
exit(1)
print("Scanning finished.")
return jsondatas
# Takes the data from get_jsondata and restructures it in prepartion for output as JS
#
# Results look like:,
#{
# "Pin": {
# "desc": [
# "This is the built-in class for Pins, such as D0,D1,LED1, or BTN",
# "You can call the methods on Pin, or you can use Wiring-style functions such as digitalWrite"
# ],
# "methods": {
# "read": {
# "desc": "Returns the input state of the pin as a boolean",
# "params": [],
# "return": [
# "bool",
# "Whether pin is a logical 1 or 0"
# ]
# },
# "reset": {
# "desc": "Sets the output state of the pin to a 0",
# "params": [],
# "return": []
# },
# ...
# },
# "props": {},
# "staticmethods": {},
# "staticprops": {}
# },
# "print": {
# "desc": "Print the supplied string",
# "return": []
# },
# ...
#}
#
def get_struct_from_jsondata(jsondata):
context = {"modules": {}}
def checkClass(details):
cl = details["class"]
if not cl in context:
context[cl] = {"type": "class", "methods": {}, "props": {}, "staticmethods": {}, "staticprops": {}, "desc": details.get("description", "")}
return cl
def addConstructor(details):
cl = checkClass(details)
context[cl]["constructor"] = {"params": details.get("params", []), "return": details.get("return", []), "desc": details.get("description", "")}
def addMethod(details, type = ""):
cl = checkClass(details)
context[cl][type + "methods"][details["name"]] = {"params": details.get("params", []), "return": details.get("return", []), "desc": details.get("description", "")}
def addProp(details, type = ""):
cl = checkClass(details)
context[cl][type + "props"][details["name"]] = {"return": details.get("return", []), "desc": details.get("description", "")}
def addFunc(details):
context[details["name"]] = {"type": "function", "return": details.get("return", []), "desc": details.get("description", "")}
def addObj(details):
context[details["name"]] = {"type": "object", "instanceof": details.get("instanceof", ""), "desc": details.get("description", "")}
def addLib(details):
context["modules"][details["class"]] = {"desc": details.get("description", "")}
def addVar(details):
return
for data in jsondata:
type = data["type"]
if type=="class":
checkClass(data)
elif type=="constructor":
addConstructor(data)
elif type=="method":
addMethod(data)
elif type=="property":
addProp(data)
elif type=="staticmethod":
addMethod(data, "static")
elif type=="staticproperty":
addProp(data, "static")
elif type=="function":
addFunc(data)
elif type=="object":
addObj(data)
elif type=="library":
addLib(data)
elif type=="variable":
addVar(data)
else:
print(json.dumps(data, sort_keys=True, indent=2))
return context
def get_includes_from_jsondata(jsondatas):
includes = []
for jsondata in jsondatas:
include = jsondata["include"]
if not include in includes:
includes.append(include)
return includes
def is_property(jsondata):
return jsondata["type"]=="property" or jsondata["type"]=="staticproperty" or jsondata["type"]=="variable"
def is_function(jsondata):
return jsondata["type"]=="function" or jsondata["type"]=="method"
def get_prefix_name(jsondata):
if jsondata["type"]=="event": return "event"
if jsondata["type"]=="constructor": return "constructor"
if jsondata["type"]=="function": return "function"
if jsondata["type"]=="method": return "function"
if jsondata["type"]=="variable": return "variable"
if jsondata["type"]=="property": return "property"
return ""
def get_ifdef_description(d):
if d=="SAVE_ON_FLASH": return "devices with low flash memory"
if d=="STM32F1": return "STM32F1 devices (including Espruino Board)"
if d=="USE_LCD_SDL": return "Linux with SDL support compiled in"
if d=="USE_TLS": return "devices with TLS and SSL support (Espruino Pico only)"
if d=="RELEASE": return "release builds"
if d=="LINUX": return "Linux-based builds"
if d=="USE_USB_HID": return "devices that support USB HID (Espruino Pico)"
if d=="USE_AES": return "devices that support AES (Espruino Pico, Espruino Wifi or Linux)"
if d=="USE_CRYPTO": return "devices that support Crypto Functionality (Espruino Pico, Espruino Wifi, Linux or ESP8266)"
print("WARNING: Unknown ifdef '"+d+"' in common.get_ifdef_description")
return d
def get_script_dir():
return os.path.dirname(os.path.realpath(__file__))
def get_version():
# Warning: the same release label derivation is also in the Makefile
scriptdir = get_script_dir()
jsutils = scriptdir+"/../src/jsutils.h"
version = re.compile("^.*JS_VERSION.*\"(.*)\"");
alt_release = os.getenv("ALT_RELEASE")
if alt_release == None:
# Default release labeling based on commits since last release tag
latest_release = subprocess.check_output('git tag 2>nul | grep RELEASE_ | sort | tail -1', shell=True).strip()
commits_since_release = subprocess.check_output('git log --oneline 2>nul '+latest_release.decode("utf-8")+'..HEAD | wc -l', shell=True).decode("utf-8").strip()
else:
# Alternate release labeling with fork name (in ALT_RELEASE env var) plus branch
# name plus commit SHA
sha = subprocess.check_output('git rev-parse --short HEAD 2>nul', shell=True).strip()
branch = subprocess.check_output('git name-rev --name-only HEAD 2>nul', shell=True).strip()
commits_since_release = alt_release + '_' + branch + '_' + sha
for line in open(jsutils):
match = version.search(line);
if (match != None):
v = match.group(1);
if commits_since_release=="0": return v
else: return v+"."+commits_since_release
return "UNKNOWN"
def get_name_or_space(jsondata):
if "name" in jsondata: return jsondata["name"]
return ""
def get_bootloader_size(board):
if board.chip["family"]=="STM32F4": return 16*1024; # 16kb Pages, so we have no choice
return 10*1024;
# On normal chips this is 0x00000000
# On boards with bootloaders it's generally + 10240
# On F401, because of the setup of pages we put the bootloader in the first 16k, then in the 16+16+16 we put the saved code, and then finally we but the binary somewhere else
def get_espruino_binary_address(board):
if "place_text_section" in board.chip:
return board.chip["place_text_section"]
if "bootloader" in board.info and board.info["bootloader"]==1:
return get_bootloader_size(board);
return 0;
def get_board_binary_name(board):
return board.info["binary_name"].replace("%v", get_version());
|
redbear/Espruino
|
scripts/common.py
|
Python
|
mpl-2.0
| 16,565
|
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# System imports
import json
import logging
import re
import uuid
from threading import Event
# Third-party imports
from pyre import Pyre
# Local imports
from ..tools import zmq, green # , spy_call, w_spy_call, spy_object
logger = logging.getLogger(__name__)
class PyreNode(Pyre):
def __init__(self, *args, **kwargs):
# spy_object(self, class_=Pyre, except_=['name', 'uuid'], with_caller=False)
# spy_call(self.__init__, args, kwargs, with_caller=False); print
self._name = None
self._uuid = None
super(self.__class__, self).__init__(*args, **kwargs)
self.request_results = {} # TODO: Fuse the two dicts
self.request_events = {}
self.poller = zmq.Poller()
self.poller.register(self.inbox, zmq.POLLIN)
self.join('SURVEY')
def run(self):
self.task = green.spawn(self._run, 100)
def _run(self, timeout=None):
self._running = True
self.start()
while self._running:
try:
# logger.debug('Polling')
items = dict(self.poller.poll(timeout))
# logger.debug('polled out: %s, %s', len(items), items)
while len(items) > 0:
for fd, ev in items.items():
if (self.inbox == fd) and (ev == zmq.POLLIN):
self._process_message()
# logger.debug('quick polling')
items = dict(self.poller.poll(0))
# logger.debug('qpoll: %s, %s', len(items), items)
except (KeyboardInterrupt, SystemExit):
logger.debug('(%s) KeyboardInterrupt or SystemExit', self.name())
break
logger.debug('(%s) Exiting loop and stopping', self.name())
self.stop()
def _process_message(self):
logger.debug('(%s) processing message', self.name())
msg = self.recv()
logger.debug('(%s) received stuff: %s', self.name(), msg)
msg_type = msg.pop(0)
logger.debug('(%s) msg_type: %s', self.name(), msg_type)
peer_id = uuid.UUID(bytes=msg.pop(0))
logger.debug('(%s) peer_id: %s', self.name(), peer_id)
peer_name = msg.pop(0)
logger.debug('(%s) peer_name: %s', self.name(), peer_name)
if msg_type == b'ENTER':
self.on_peer_enter(peer_id, peer_name, msg)
elif msg_type == b'EXIT':
self.on_peer_exit(peer_id, peer_name, msg)
elif msg_type == b'SHOUT':
self.on_peer_shout(peer_id, peer_name, msg)
elif msg_type == b'WHISPER':
self.on_peer_whisper(peer_id, peer_name, msg)
def on_peer_enter(self, peer_id, peer_name, msg):
logger.debug('(%s) ZRE ENTER: %s, %s', self.name(), peer_name, peer_id)
pub_endpoint = self.get_peer_endpoint(peer_id, 'pub')
rpc_endpoint = self.get_peer_endpoint(peer_id, 'rpc')
self.on_new_peer(peer_id, peer_name, pub_endpoint, rpc_endpoint)
def on_new_peer(self, peer_id, peer_name, pub_endpoint, rpc_endpoint):
pass
def on_peer_exit(self, peer_id, peer_name, msg):
logger.debug('(%s) ZRE EXIT: %s, %s', self.name(), peer_name, peer_id)
self.on_peer_gone(peer_id, peer_name)
def on_peer_gone(self, peer_id, peer_name):
pass
def on_peer_shout(self, peer_id, peer_name, msg):
group = msg.pop(0)
data = msg.pop(0)
logger.debug('(%s) ZRE SHOUT: %s, %s > (%s) %s',
self.name(), peer_name, peer_id, group, data)
if group == b'SURVEY':
self.on_survey(peer_id, peer_name, json.loads(data))
elif group == b'EVENT':
self.on_event(peer_id, peer_name, json.loads(data))
def on_survey(self, peer_id, peer_name, request):
pass
def on_event(self, peer_id, peer_name, request):
pass
def on_peer_whisper(self, peer_id, peer_name, msg):
logger.debug('(%s) ZRE WHISPER: %s, %s > %s', self.name(), peer_name, peer_id, msg)
reply = json.loads(msg[0])
if reply['req_id'] in self.request_results:
logger.debug('(%s) Received reply from %s: %s', self.name(), peer_name, reply['data'])
self.request_results[reply['req_id']].append((peer_name, reply['data']))
ev, limit_peers = self.request_events[reply['req_id']]
if limit_peers and (len(self.request_results[reply['req_id']]) >= limit_peers):
ev.set()
green.sleep(0) # Yield
else:
logger.warning(
'(%s) Discarding reply from %s because the request ID is unknown',
self.name(), peer_name
)
def get_peer_endpoint(self, peer, prefix):
pyre_endpoint = self.peer_address(peer)
ip = re.search('.*://(.*):.*', pyre_endpoint).group(1)
return '%s://%s:%s' % (
self.peer_header_value(peer, prefix + '_proto'),
ip,
self.peer_header_value(peer, prefix + '_port')
)
def join_event(self):
self.join('EVENT')
def leave_event(self):
self.leave('EVENT')
def send_survey(self, request, timeout, limit_peers):
# request['req_id'] = ('%x' % randint(0, 0xFFFFFFFF)).encode()
self.request_results[request['req_id']] = []
ev = Event()
self.request_events[request['req_id']] = (ev, limit_peers)
self.shout('SURVEY', json.dumps(request).encode())
ev.wait(timeout)
result = self.request_results[request['req_id']]
del self.request_results[request['req_id']]
del self.request_events[request['req_id']]
return result
def send_event(self, request):
self.shout('EVENT', json.dumps(request).encode())
def reply_survey(self, peer_id, reply):
self.whisper(peer_id, json.dumps(reply).encode())
def shutdown(self):
self._running = False
def name(self):
if self._name is None:
# f = w_spy_call(super(self.__class__, self).name, with_caller=False)
f = super(self.__class__, self).name
self._name = f()
return self._name
def uuid(self):
if self._uuid is None:
# f = w_spy_call(super(self.__class__, self).uuid, with_caller=False)
f = super(self.__class__, self).uuid
self._uuid = f()
return self._uuid
|
Alidron/alidron-isac
|
isac/transport/pyre_node.py
|
Python
|
mpl-2.0
| 6,714
|
package aws
import (
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAwsAutoscalingLifecycleHook() *schema.Resource {
return &schema.Resource{
Create: resourceAwsAutoscalingLifecycleHookPut,
Read: resourceAwsAutoscalingLifecycleHookRead,
Update: resourceAwsAutoscalingLifecycleHookPut,
Delete: resourceAwsAutoscalingLifecycleHookDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsAutoscalingLifecycleHookImport,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"autoscaling_group_name": {
Type: schema.TypeString,
Required: true,
},
"default_result": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"heartbeat_timeout": {
Type: schema.TypeInt,
Optional: true,
},
"lifecycle_transition": {
Type: schema.TypeString,
Required: true,
},
"notification_metadata": {
Type: schema.TypeString,
Optional: true,
},
"notification_target_arn": {
Type: schema.TypeString,
Optional: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAwsAutoscalingLifecycleHookPutOp(conn *autoscaling.AutoScaling, params *autoscaling.PutLifecycleHookInput) error {
log.Printf("[DEBUG] AutoScaling PutLifecyleHook: %s", params)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := conn.PutLifecycleHook(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if strings.Contains(awsErr.Message(), "Unable to publish test message to notification target") {
return resource.RetryableError(fmt.Errorf("Retrying AWS AutoScaling Lifecycle Hook: %s", awsErr))
}
}
return resource.NonRetryableError(fmt.Errorf("Error putting lifecycle hook: %s", err))
}
return nil
})
if isResourceTimeoutError(err) {
_, err = conn.PutLifecycleHook(params)
}
if err != nil {
return fmt.Errorf("Error putting autoscaling lifecycle hook: %s", err)
}
return nil
}
func resourceAwsAutoscalingLifecycleHookPut(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).autoscalingconn
params := getAwsAutoscalingPutLifecycleHookInput(d)
if err := resourceAwsAutoscalingLifecycleHookPutOp(conn, ¶ms); err != nil {
return err
}
d.SetId(d.Get("name").(string))
return resourceAwsAutoscalingLifecycleHookRead(d, meta)
}
func resourceAwsAutoscalingLifecycleHookRead(d *schema.ResourceData, meta interface{}) error {
p, err := getAwsAutoscalingLifecycleHook(d, meta)
if err != nil {
return err
}
if p == nil {
log.Printf("[WARN] Autoscaling Lifecycle Hook (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
log.Printf("[DEBUG] Read Lifecycle Hook: ASG: %s, SH: %s, Obj: %#v", d.Get("autoscaling_group_name"), d.Get("name"), p)
d.Set("default_result", p.DefaultResult)
d.Set("heartbeat_timeout", p.HeartbeatTimeout)
d.Set("lifecycle_transition", p.LifecycleTransition)
d.Set("notification_metadata", p.NotificationMetadata)
d.Set("notification_target_arn", p.NotificationTargetARN)
d.Set("name", p.LifecycleHookName)
d.Set("role_arn", p.RoleARN)
return nil
}
func resourceAwsAutoscalingLifecycleHookDelete(d *schema.ResourceData, meta interface{}) error {
autoscalingconn := meta.(*AWSClient).autoscalingconn
p, err := getAwsAutoscalingLifecycleHook(d, meta)
if err != nil {
return err
}
if p == nil {
return nil
}
params := autoscaling.DeleteLifecycleHookInput{
AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
LifecycleHookName: aws.String(d.Get("name").(string)),
}
if _, err := autoscalingconn.DeleteLifecycleHook(¶ms); err != nil {
return fmt.Errorf("Autoscaling Lifecycle Hook: %s", err)
}
return nil
}
func getAwsAutoscalingPutLifecycleHookInput(d *schema.ResourceData) autoscaling.PutLifecycleHookInput {
var params = autoscaling.PutLifecycleHookInput{
AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
LifecycleHookName: aws.String(d.Get("name").(string)),
}
if v, ok := d.GetOk("default_result"); ok {
params.DefaultResult = aws.String(v.(string))
}
if v, ok := d.GetOk("heartbeat_timeout"); ok {
params.HeartbeatTimeout = aws.Int64(int64(v.(int)))
}
if v, ok := d.GetOk("lifecycle_transition"); ok {
params.LifecycleTransition = aws.String(v.(string))
}
if v, ok := d.GetOk("notification_metadata"); ok {
params.NotificationMetadata = aws.String(v.(string))
}
if v, ok := d.GetOk("notification_target_arn"); ok {
params.NotificationTargetARN = aws.String(v.(string))
}
if v, ok := d.GetOk("role_arn"); ok {
params.RoleARN = aws.String(v.(string))
}
return params
}
func getAwsAutoscalingLifecycleHook(d *schema.ResourceData, meta interface{}) (*autoscaling.LifecycleHook, error) {
autoscalingconn := meta.(*AWSClient).autoscalingconn
params := autoscaling.DescribeLifecycleHooksInput{
AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
LifecycleHookNames: []*string{aws.String(d.Get("name").(string))},
}
log.Printf("[DEBUG] AutoScaling Lifecycle Hook Describe Params: %#v", params)
resp, err := autoscalingconn.DescribeLifecycleHooks(¶ms)
if err != nil {
return nil, fmt.Errorf("Error retrieving lifecycle hooks: %s", err)
}
// find lifecycle hooks
name := d.Get("name")
for idx, sp := range resp.LifecycleHooks {
if *sp.LifecycleHookName == name {
return resp.LifecycleHooks[idx], nil
}
}
// lifecycle hook not found
return nil, nil
}
func resourceAwsAutoscalingLifecycleHookImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
idParts := strings.SplitN(d.Id(), "/", 2)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
return nil, fmt.Errorf("unexpected format (%q), expected <asg-name>/<lifecycle-hook-name>", d.Id())
}
asgName := idParts[0]
lifecycleHookName := idParts[1]
d.Set("name", lifecycleHookName)
d.Set("autoscaling_group_name", asgName)
d.SetId(lifecycleHookName)
return []*schema.ResourceData{d}, nil
}
|
kjmkznr/terraform-provider-aws
|
aws/resource_aws_autoscaling_lifecycle_hook.go
|
GO
|
mpl-2.0
| 6,407
|
/* -*- Mode: C; tab-width: 8; c-basic-offset: 8 -*- */
/* vim:set softtabstop=8 shiftwidth=8: */
/*-
* Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
* 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(s), this list of conditions and the following disclaimer as
* the first lines of this file unmodified other than the possible
* addition of one or more copyright notices.
* 2. Redistributions in binary form must reproduce the above copyright
* notice(s), this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``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(S) 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 allocator implementation is designed to provide scalable performance
* for multi-threaded programs on multi-processor systems. The following
* features are included for this purpose:
*
* + Multiple arenas are used if there are multiple CPUs, which reduces lock
* contention and cache sloshing.
*
* + Cache line sharing between arenas is avoided for internal data
* structures.
*
* + Memory is managed in chunks and runs (chunks can be split into runs),
* rather than as individual pages. This provides a constant-time
* mechanism for associating allocations with particular arenas.
*
* Allocation requests are rounded up to the nearest size class, and no record
* of the original request size is maintained. Allocations are broken into
* categories according to size class. Assuming runtime defaults, 4 kB pages
* and a 16 byte quantum on a 32-bit system, the size classes in each category
* are as follows:
*
* |=====================================|
* | Category | Subcategory | Size |
* |=====================================|
* | Small | Tiny | 2 |
* | | | 4 |
* | | | 8 |
* | |----------------+---------|
* | | Quantum-spaced | 16 |
* | | | 32 |
* | | | 48 |
* | | | ... |
* | | | 480 |
* | | | 496 |
* | | | 512 |
* | |----------------+---------|
* | | Sub-page | 1 kB |
* | | | 2 kB |
* |=====================================|
* | Large | 4 kB |
* | | 8 kB |
* | | 12 kB |
* | | ... |
* | | 1012 kB |
* | | 1016 kB |
* | | 1020 kB |
* |=====================================|
* | Huge | 1 MB |
* | | 2 MB |
* | | 3 MB |
* | | ... |
* |=====================================|
*
* A different mechanism is used for each category:
*
* Small : Each size class is segregated into its own set of runs. Each run
* maintains a bitmap of which regions are free/allocated.
*
* Large : Each allocation is backed by a dedicated run. Metadata are stored
* in the associated arena chunk header maps.
*
* Huge : Each allocation is backed by a dedicated contiguous set of chunks.
* Metadata are stored in a separate red-black tree.
*
*******************************************************************************
*/
/*
* MALLOC_PRODUCTION disables assertions and statistics gathering. It also
* defaults the A and J runtime options to off. These settings are appropriate
* for production systems.
*/
#ifndef MOZ_MEMORY_DEBUG
# define MALLOC_PRODUCTION
#endif
/*
* Use only one arena by default. Mozilla does not currently make extensive
* use of concurrent allocation, so the increased fragmentation associated with
* multiple arenas is not warranted.
*/
#define MOZ_MEMORY_NARENAS_DEFAULT_ONE
/*
* MALLOC_STATS enables statistics calculation, and is required for
* jemalloc_stats().
*/
#define MALLOC_STATS
#ifndef MALLOC_PRODUCTION
/*
* MALLOC_DEBUG enables assertions and other sanity checks, and disables
* inline functions.
*/
# define MALLOC_DEBUG
/* Memory filling (junk/zero). */
# define MALLOC_FILL
/* Allocation tracing. */
# ifndef MOZ_MEMORY_WINDOWS
# define MALLOC_UTRACE
# endif
/* Support optional abort() on OOM. */
# define MALLOC_XMALLOC
/* Support SYSV semantics. */
# define MALLOC_SYSV
#endif
/*
* MALLOC_VALIDATE causes malloc_usable_size() to perform some pointer
* validation. There are many possible errors that validation does not even
* attempt to detect.
*/
#define MALLOC_VALIDATE
/* Embed no-op macros that support memory allocation tracking via valgrind. */
#ifdef MOZ_VALGRIND
# define MALLOC_VALGRIND
#endif
#ifdef MALLOC_VALGRIND
# include <valgrind/valgrind.h>
#else
# define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed)
# define VALGRIND_FREELIKE_BLOCK(addr, rzB)
#endif
/*
* MALLOC_BALANCE enables monitoring of arena lock contention and dynamically
* re-balances arena load if exponentially averaged contention exceeds a
* certain threshold.
*/
/* #define MALLOC_BALANCE */
#if (!defined(MOZ_MEMORY_WINDOWS) && !defined(MOZ_MEMORY_DARWIN))
/*
* MALLOC_PAGEFILE causes all mmap()ed memory to be backed by temporary
* files, so that if a chunk is mapped, it is guaranteed to be swappable.
* This avoids asynchronous OOM failures that are due to VM over-commit.
*
* XXX OS X over-commits, so we should probably use mmap() instead of
* vm_allocate(), so that MALLOC_PAGEFILE works.
*/
# define MALLOC_PAGEFILE
#endif
#ifdef MALLOC_PAGEFILE
/* Write size when initializing a page file. */
# define MALLOC_PAGEFILE_WRITE_SIZE 512
#endif
#ifdef MOZ_MEMORY_LINUX
#define _GNU_SOURCE /* For mremap(2). */
#define issetugid() 0
#if 0 /* Enable in order to test decommit code on Linux. */
# define MALLOC_DECOMMIT
#endif
#endif
#include <sys/types.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef MOZ_MEMORY_WINDOWS
#include <cruntime.h>
#include <internal.h>
#include <windows.h>
#include <io.h>
#pragma warning( disable: 4267 4996 4146 )
#define false FALSE
#define true TRUE
#define inline __inline
#define SIZE_T_MAX SIZE_MAX
#define STDERR_FILENO 2
#define PATH_MAX MAX_PATH
#define vsnprintf _vsnprintf
static unsigned long tlsIndex = 0xffffffff;
#define __thread
#define _pthread_self() __threadid()
#define issetugid() 0
/* use MSVC intrinsics */
#pragma intrinsic(_BitScanForward)
static __forceinline int
ffs(int x)
{
unsigned long i;
if (_BitScanForward(&i, x) != 0)
return (i + 1);
return (0);
}
/* Implement getenv without using malloc */
static char mozillaMallocOptionsBuf[64];
#define getenv xgetenv
static char *
getenv(const char *name)
{
if (GetEnvironmentVariableA(name, (LPSTR)&mozillaMallocOptionsBuf,
sizeof(mozillaMallocOptionsBuf)) > 0)
return (mozillaMallocOptionsBuf);
return (NULL);
}
typedef unsigned char uint8_t;
typedef unsigned uint32_t;
typedef unsigned long long uint64_t;
typedef unsigned long long uintmax_t;
typedef long ssize_t;
#define MALLOC_DECOMMIT
#endif
#ifndef MOZ_MEMORY_WINDOWS
#ifndef MOZ_MEMORY_SOLARIS
#include <sys/cdefs.h>
#endif
#ifndef __DECONST
# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
#endif
#ifndef MOZ_MEMORY
__FBSDID("$FreeBSD: head/lib/libc/stdlib/malloc.c 180599 2008-07-18 19:35:44Z jasone $");
#include "libc_private.h"
#ifdef MALLOC_DEBUG
# define _LOCK_DEBUG
#endif
#include "spinlock.h"
#include "namespace.h"
#endif
#include <sys/mman.h>
#ifndef MADV_FREE
# define MADV_FREE MADV_DONTNEED
#endif
#ifndef MAP_NOSYNC
# define MAP_NOSYNC 0
#endif
#include <sys/param.h>
#ifndef MOZ_MEMORY
#include <sys/stddef.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#ifndef MOZ_MEMORY_SOLARIS
#include <sys/sysctl.h>
#endif
#include <sys/uio.h>
#ifndef MOZ_MEMORY
#include <sys/ktrace.h> /* Must come after several other sys/ includes. */
#include <machine/atomic.h>
#include <machine/cpufunc.h>
#include <machine/vmparam.h>
#endif
#include <errno.h>
#include <limits.h>
#ifndef SIZE_T_MAX
# define SIZE_T_MAX SIZE_MAX
#endif
#include <pthread.h>
#ifdef MOZ_MEMORY_DARWIN
#define _pthread_self pthread_self
#define _pthread_mutex_init pthread_mutex_init
#define _pthread_mutex_trylock pthread_mutex_trylock
#define _pthread_mutex_lock pthread_mutex_lock
#define _pthread_mutex_unlock pthread_mutex_unlock
#endif
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef MOZ_MEMORY_DARWIN
#include <strings.h>
#endif
#include <unistd.h>
#ifdef MOZ_MEMORY_DARWIN
#include <libkern/OSAtomic.h>
#include <mach/mach_error.h>
#include <mach/mach_init.h>
#include <mach/vm_map.h>
#include <malloc/malloc.h>
#endif
#ifndef MOZ_MEMORY
#include "un-namespace.h"
#endif
#endif
#include "jemalloc.h"
#ifdef MOZ_MEMORY_DARWIN
static const bool __isthreaded = true;
#endif
#define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
#include "qr.h"
#include "ql.h"
#ifdef MOZ_MEMORY_WINDOWS
/* MSVC++ does not support C99 variable-length arrays. */
# define RB_NO_C99_VARARRAYS
#endif
#include "rb.h"
#ifdef MALLOC_DEBUG
/* Disable inlining to make debugging easier. */
#ifdef inline
#undef inline
#endif
# define inline
#endif
/* Size of stack-allocated buffer passed to strerror_r(). */
#define STRERROR_BUF 64
/* Minimum alignment of allocations is 2^QUANTUM_2POW_MIN bytes. */
# define QUANTUM_2POW_MIN 4
#ifdef MOZ_MEMORY_SIZEOF_PTR_2POW
# define SIZEOF_PTR_2POW MOZ_MEMORY_SIZEOF_PTR_2POW
#else
# define SIZEOF_PTR_2POW 2
#endif
#define PIC
#ifndef MOZ_MEMORY_DARWIN
static const bool __isthreaded = true;
#else
# define NO_TLS
#endif
#if 0
#ifdef __i386__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
# define CPU_SPINWAIT __asm__ volatile("pause")
#endif
#ifdef __ia64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
#endif
#ifdef __alpha__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define NO_TLS
#endif
#ifdef __sparc64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define NO_TLS
#endif
#ifdef __amd64__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 3
# define CPU_SPINWAIT __asm__ volatile("pause")
#endif
#ifdef __arm__
# define QUANTUM_2POW_MIN 3
# define SIZEOF_PTR_2POW 2
# define NO_TLS
#endif
#ifdef __mips__
# define QUANTUM_2POW_MIN 3
# define SIZEOF_PTR_2POW 2
# define NO_TLS
#endif
#ifdef __powerpc__
# define QUANTUM_2POW_MIN 4
# define SIZEOF_PTR_2POW 2
#endif
#endif
#define SIZEOF_PTR (1U << SIZEOF_PTR_2POW)
/* sizeof(int) == (1U << SIZEOF_INT_2POW). */
#ifndef SIZEOF_INT_2POW
# define SIZEOF_INT_2POW 2
#endif
/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */
#if (!defined(PIC) && !defined(NO_TLS))
# define NO_TLS
#endif
#ifdef NO_TLS
/* MALLOC_BALANCE requires TLS. */
# ifdef MALLOC_BALANCE
# undef MALLOC_BALANCE
# endif
#endif
/*
* Size and alignment of memory chunks that are allocated by the OS's virtual
* memory system.
*/
#define CHUNK_2POW_DEFAULT 20
/* Maximum number of dirty pages per arena. */
#define DIRTY_MAX_DEFAULT (1U << 10)
/* Default reserve chunks. */
#define RESERVE_MIN_2POW_DEFAULT 1
/*
* Default range (in chunks) between reserve_min and reserve_max, in addition
* to the mandatory one chunk per arena.
*/
#ifdef MALLOC_PAGEFILE
# define RESERVE_RANGE_2POW_DEFAULT 5
#else
# define RESERVE_RANGE_2POW_DEFAULT 0
#endif
/*
* Maximum size of L1 cache line. This is used to avoid cache line aliasing,
* so over-estimates are okay (up to a point), but under-estimates will
* negatively affect performance.
*/
#define CACHELINE_2POW 6
#define CACHELINE ((size_t)(1U << CACHELINE_2POW))
/* Smallest size class to support. */
#define TINY_MIN_2POW 1
/*
* Maximum size class that is a multiple of the quantum, but not (necessarily)
* a power of 2. Above this size, allocations are rounded up to the nearest
* power of 2.
*/
#define SMALL_MAX_2POW_DEFAULT 9
#define SMALL_MAX_DEFAULT (1U << SMALL_MAX_2POW_DEFAULT)
/*
* RUN_MAX_OVRHD indicates maximum desired run header overhead. Runs are sized
* as small as possible such that this setting is still honored, without
* violating other constraints. The goal is to make runs as small as possible
* without exceeding a per run external fragmentation threshold.
*
* We use binary fixed point math for overhead computations, where the binary
* point is implicitly RUN_BFP bits to the left.
*
* Note that it is possible to set RUN_MAX_OVRHD low enough that it cannot be
* honored for some/all object sizes, since there is one bit of header overhead
* per object (plus a constant). This constraint is relaxed (ignored) for runs
* that are so small that the per-region overhead is greater than:
*
* (RUN_MAX_OVRHD / (reg_size << (3+RUN_BFP))
*/
#define RUN_BFP 12
/* \/ Implicit binary fixed point. */
#define RUN_MAX_OVRHD 0x0000003dU
#define RUN_MAX_OVRHD_RELAX 0x00001800U
/* Put a cap on small object run size. This overrides RUN_MAX_OVRHD. */
#define RUN_MAX_SMALL_2POW 15
#define RUN_MAX_SMALL (1U << RUN_MAX_SMALL_2POW)
/*
* Hyper-threaded CPUs may need a special instruction inside spin loops in
* order to yield to another virtual CPU. If no such instruction is defined
* above, make CPU_SPINWAIT a no-op.
*/
#ifndef CPU_SPINWAIT
# define CPU_SPINWAIT
#endif
/*
* Adaptive spinning must eventually switch to blocking, in order to avoid the
* potential for priority inversion deadlock. Backing off past a certain point
* can actually waste time.
*/
#define SPIN_LIMIT_2POW 11
/*
* Conversion from spinning to blocking is expensive; we use (1U <<
* BLOCK_COST_2POW) to estimate how many more times costly blocking is than
* worst-case spinning.
*/
#define BLOCK_COST_2POW 4
#ifdef MALLOC_BALANCE
/*
* We use an exponential moving average to track recent lock contention,
* where the size of the history window is N, and alpha=2/(N+1).
*
* Due to integer math rounding, very small values here can cause
* substantial degradation in accuracy, thus making the moving average decay
* faster than it would with precise calculation.
*/
# define BALANCE_ALPHA_INV_2POW 9
/*
* Threshold value for the exponential moving contention average at which to
* re-assign a thread.
*/
# define BALANCE_THRESHOLD_DEFAULT (1U << (SPIN_LIMIT_2POW-4))
#endif
/******************************************************************************/
/*
* Mutexes based on spinlocks. We can't use normal pthread spinlocks in all
* places, because they require malloc()ed memory, which causes bootstrapping
* issues in some cases.
*/
#if defined(MOZ_MEMORY_WINDOWS)
#define malloc_mutex_t CRITICAL_SECTION
#define malloc_spinlock_t CRITICAL_SECTION
#elif defined(MOZ_MEMORY_DARWIN)
typedef struct {
OSSpinLock lock;
} malloc_mutex_t;
typedef struct {
OSSpinLock lock;
} malloc_spinlock_t;
#elif defined(MOZ_MEMORY)
typedef pthread_mutex_t malloc_mutex_t;
typedef pthread_mutex_t malloc_spinlock_t;
#else
/* XXX these should #ifdef these for freebsd (and linux?) only */
typedef struct {
spinlock_t lock;
} malloc_mutex_t;
typedef malloc_spinlock_t malloc_mutex_t;
#endif
/* Set to true once the allocator has been initialized. */
static bool malloc_initialized = false;
#if defined(MOZ_MEMORY_WINDOWS)
/* No init lock for Windows. */
#elif defined(MOZ_MEMORY_DARWIN)
static malloc_mutex_t init_lock = {OS_SPINLOCK_INIT};
#elif defined(MOZ_MEMORY_LINUX)
static malloc_mutex_t init_lock = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
#elif defined(MOZ_MEMORY)
static malloc_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER;
#else
static malloc_mutex_t init_lock = {_SPINLOCK_INITIALIZER};
#endif
/******************************************************************************/
/*
* Statistics data structures.
*/
#ifdef MALLOC_STATS
typedef struct malloc_bin_stats_s malloc_bin_stats_t;
struct malloc_bin_stats_s {
/*
* Number of allocation requests that corresponded to the size of this
* bin.
*/
uint64_t nrequests;
/* Total number of runs created for this bin's size class. */
uint64_t nruns;
/*
* Total number of runs reused by extracting them from the runs tree for
* this bin's size class.
*/
uint64_t reruns;
/* High-water mark for this bin. */
unsigned long highruns;
/* Current number of runs in this bin. */
unsigned long curruns;
};
typedef struct arena_stats_s arena_stats_t;
struct arena_stats_s {
/* Number of bytes currently mapped. */
size_t mapped;
/*
* Total number of purge sweeps, total number of madvise calls made,
* and total pages purged in order to keep dirty unused memory under
* control.
*/
uint64_t npurge;
uint64_t nmadvise;
uint64_t purged;
#ifdef MALLOC_DECOMMIT
/*
* Total number of decommit/commit operations, and total number of
* pages decommitted.
*/
uint64_t ndecommit;
uint64_t ncommit;
uint64_t decommitted;
#endif
/* Per-size-category statistics. */
size_t allocated_small;
uint64_t nmalloc_small;
uint64_t ndalloc_small;
size_t allocated_large;
uint64_t nmalloc_large;
uint64_t ndalloc_large;
#ifdef MALLOC_BALANCE
/* Number of times this arena reassigned a thread due to contention. */
uint64_t nbalance;
#endif
};
typedef struct chunk_stats_s chunk_stats_t;
struct chunk_stats_s {
/* Number of chunks that were allocated. */
uint64_t nchunks;
/* High-water mark for number of chunks allocated. */
unsigned long highchunks;
/*
* Current number of chunks allocated. This value isn't maintained for
* any other purpose, so keep track of it in order to be able to set
* highchunks.
*/
unsigned long curchunks;
};
#endif /* #ifdef MALLOC_STATS */
/******************************************************************************/
/*
* Extent data structures.
*/
/* Tree of extents. */
typedef struct extent_node_s extent_node_t;
struct extent_node_s {
/* Linkage for the size/address-ordered tree. */
rb_node(extent_node_t) link_szad;
/* Linkage for the address-ordered tree. */
rb_node(extent_node_t) link_ad;
/* Pointer to the extent that this tree node is responsible for. */
void *addr;
/* Total region size. */
size_t size;
};
typedef rb_tree(extent_node_t) extent_tree_t;
/******************************************************************************/
/*
* Radix tree data structures.
*/
#ifdef MALLOC_VALIDATE
/*
* Size of each radix tree node (must be a power of 2). This impacts tree
* depth.
*/
# if (SIZEOF_PTR == 4)
# define MALLOC_RTREE_NODESIZE (1U << 14)
# else
# define MALLOC_RTREE_NODESIZE CACHELINE
# endif
typedef struct malloc_rtree_s malloc_rtree_t;
struct malloc_rtree_s {
malloc_spinlock_t lock;
void **root;
unsigned height;
unsigned level2bits[1]; /* Dynamically sized. */
};
#endif
/******************************************************************************/
/*
* Reserve data structures.
*/
/* Callback registration. */
typedef struct reserve_reg_s reserve_reg_t;
struct reserve_reg_s {
/* Linkage for list of all registered callbacks. */
ql_elm(reserve_reg_t) link;
/* Callback function pointer. */
reserve_cb_t *cb;
/* Opaque application data pointer. */
void *ctx;
/*
* Sequence number of condition notification most recently sent to this
* callback.
*/
uint64_t seq;
};
/******************************************************************************/
/*
* Arena data structures.
*/
typedef struct arena_s arena_t;
typedef struct arena_bin_s arena_bin_t;
/* Each element of the chunk map corresponds to one page within the chunk. */
typedef struct arena_chunk_map_s arena_chunk_map_t;
struct arena_chunk_map_s {
/*
* Linkage for run trees. There are two disjoint uses:
*
* 1) arena_t's runs_avail tree.
* 2) arena_run_t conceptually uses this linkage for in-use non-full
* runs, rather than directly embedding linkage.
*/
rb_node(arena_chunk_map_t) link;
/*
* Run address (or size) and various flags are stored together. The bit
* layout looks like (assuming 32-bit system):
*
* ???????? ???????? ????---- --ckdzla
*
* ? : Unallocated: Run address for first/last pages, unset for internal
* pages.
* Small: Run address.
* Large: Run size for first page, unset for trailing pages.
* - : Unused.
* c : decommitted?
* k : key?
* d : dirty?
* z : zeroed?
* l : large?
* a : allocated?
*
* Following are example bit patterns for the three types of runs.
*
* r : run address
* s : run size
* x : don't care
* - : 0
* [cdzla] : bit set
*
* Unallocated:
* ssssssss ssssssss ssss---- --c-----
* xxxxxxxx xxxxxxxx xxxx---- ----d---
* ssssssss ssssssss ssss---- -----z--
*
* Small:
* rrrrrrrr rrrrrrrr rrrr---- -------a
* rrrrrrrr rrrrrrrr rrrr---- -------a
* rrrrrrrr rrrrrrrr rrrr---- -------a
*
* Large:
* ssssssss ssssssss ssss---- ------la
* -------- -------- -------- ------la
* -------- -------- -------- ------la
*/
size_t bits;
#ifdef MALLOC_DECOMMIT
#define CHUNK_MAP_DECOMMITTED ((size_t)0x20U)
#endif
#define CHUNK_MAP_KEY ((size_t)0x10U)
#define CHUNK_MAP_DIRTY ((size_t)0x08U)
#define CHUNK_MAP_ZEROED ((size_t)0x04U)
#define CHUNK_MAP_LARGE ((size_t)0x02U)
#define CHUNK_MAP_ALLOCATED ((size_t)0x01U)
};
typedef rb_tree(arena_chunk_map_t) arena_avail_tree_t;
typedef rb_tree(arena_chunk_map_t) arena_run_tree_t;
/* Arena chunk header. */
typedef struct arena_chunk_s arena_chunk_t;
struct arena_chunk_s {
/* Arena that owns the chunk. */
arena_t *arena;
/* Linkage for the arena's chunks_dirty tree. */
rb_node(arena_chunk_t) link_dirty;
/* Number of dirty pages. */
size_t ndirty;
/* Map of pages within chunk that keeps track of free/large/small. */
arena_chunk_map_t map[1]; /* Dynamically sized. */
};
typedef rb_tree(arena_chunk_t) arena_chunk_tree_t;
typedef struct arena_run_s arena_run_t;
struct arena_run_s {
#ifdef MALLOC_DEBUG
uint32_t magic;
# define ARENA_RUN_MAGIC 0x384adf93
#endif
/* Bin this run is associated with. */
arena_bin_t *bin;
/* Index of first element that might have a free region. */
unsigned regs_minelm;
/* Number of free regions in run. */
unsigned nfree;
/* Bitmask of in-use regions (0: in use, 1: free). */
unsigned regs_mask[1]; /* Dynamically sized. */
};
struct arena_bin_s {
/*
* Current run being used to service allocations of this bin's size
* class.
*/
arena_run_t *runcur;
/*
* Tree of non-full runs. This tree is used when looking for an
* existing run when runcur is no longer usable. We choose the
* non-full run that is lowest in memory; this policy tends to keep
* objects packed well, and it can also help reduce the number of
* almost-empty chunks.
*/
arena_run_tree_t runs;
/* Size of regions in a run for this bin's size class. */
size_t reg_size;
/* Total size of a run for this bin's size class. */
size_t run_size;
/* Total number of regions in a run for this bin's size class. */
uint32_t nregs;
/* Number of elements in a run's regs_mask for this bin's size class. */
uint32_t regs_mask_nelms;
/* Offset of first region in a run for this bin's size class. */
uint32_t reg0_offset;
#ifdef MALLOC_STATS
/* Bin statistics. */
malloc_bin_stats_t stats;
#endif
};
struct arena_s {
#ifdef MALLOC_DEBUG
uint32_t magic;
# define ARENA_MAGIC 0x947d3d24
#endif
/* All operations on this arena require that lock be locked. */
#ifdef MOZ_MEMORY
malloc_spinlock_t lock;
#else
pthread_mutex_t lock;
#endif
#ifdef MALLOC_STATS
arena_stats_t stats;
#endif
/*
* Chunk allocation sequence number, used to detect races with other
* threads during chunk allocation, and then discard unnecessary chunks.
*/
uint64_t chunk_seq;
/* Tree of dirty-page-containing chunks this arena manages. */
arena_chunk_tree_t chunks_dirty;
/*
* In order to avoid rapid chunk allocation/deallocation when an arena
* oscillates right on the cusp of needing a new chunk, cache the most
* recently freed chunk. The spare is left in the arena's chunk trees
* until it is deleted.
*
* There is one spare chunk per arena, rather than one spare total, in
* order to avoid interactions between multiple threads that could make
* a single spare inadequate.
*/
arena_chunk_t *spare;
/*
* Current count of pages within unused runs that are potentially
* dirty, and for which madvise(... MADV_FREE) has not been called. By
* tracking this, we can institute a limit on how much dirty unused
* memory is mapped for each arena.
*/
size_t ndirty;
/*
* Size/address-ordered tree of this arena's available runs. This tree
* is used for first-best-fit run allocation.
*/
arena_avail_tree_t runs_avail;
#ifdef MALLOC_BALANCE
/*
* The arena load balancing machinery needs to keep track of how much
* lock contention there is. This value is exponentially averaged.
*/
uint32_t contention;
#endif
/*
* bins is used to store rings of free regions of the following sizes,
* assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
*
* bins[i] | size |
* --------+------+
* 0 | 2 |
* 1 | 4 |
* 2 | 8 |
* --------+------+
* 3 | 16 |
* 4 | 32 |
* 5 | 48 |
* 6 | 64 |
* : :
* : :
* 33 | 496 |
* 34 | 512 |
* --------+------+
* 35 | 1024 |
* 36 | 2048 |
* --------+------+
*/
arena_bin_t bins[1]; /* Dynamically sized. */
};
/******************************************************************************/
/*
* Data.
*/
/* Number of CPUs. */
static unsigned ncpus;
/* VM page size. */
static size_t pagesize;
static size_t pagesize_mask;
static size_t pagesize_2pow;
/* Various bin-related settings. */
static size_t bin_maxclass; /* Max size class for bins. */
static unsigned ntbins; /* Number of (2^n)-spaced tiny bins. */
static unsigned nqbins; /* Number of quantum-spaced bins. */
static unsigned nsbins; /* Number of (2^n)-spaced sub-page bins. */
static size_t small_min;
static size_t small_max;
/* Various quantum-related settings. */
static size_t quantum;
static size_t quantum_mask; /* (quantum - 1). */
/* Various chunk-related settings. */
static size_t chunksize;
static size_t chunksize_mask; /* (chunksize - 1). */
static size_t chunk_npages;
static size_t arena_chunk_header_npages;
static size_t arena_maxclass; /* Max size class for arenas. */
/********/
/*
* Chunks.
*/
#ifdef MALLOC_VALIDATE
static malloc_rtree_t *chunk_rtree;
#endif
/* Protects chunk-related data structures. */
static malloc_mutex_t huge_mtx;
/* Tree of chunks that are stand-alone huge allocations. */
static extent_tree_t huge;
#ifdef MALLOC_STATS
/* Huge allocation statistics. */
static uint64_t huge_nmalloc;
static uint64_t huge_ndalloc;
static size_t huge_allocated;
#endif
/****************/
/*
* Memory reserve.
*/
#ifdef MALLOC_PAGEFILE
static char pagefile_templ[PATH_MAX];
#endif
/* Protects reserve-related data structures. */
static malloc_mutex_t reserve_mtx;
/*
* Bounds on acceptable reserve size, and current reserve size. Reserve
* depletion may cause (reserve_cur < reserve_min).
*/
static size_t reserve_min;
static size_t reserve_cur;
static size_t reserve_max;
/* List of registered callbacks. */
static ql_head(reserve_reg_t) reserve_regs;
/*
* Condition notification sequence number, used to determine whether all
* registered callbacks have been notified of the most current condition.
*/
static uint64_t reserve_seq;
/*
* Trees of chunks currently in the memory reserve. Depending on function,
* different tree orderings are needed, which is why there are two trees with
* the same contents.
*/
static extent_tree_t reserve_chunks_szad;
static extent_tree_t reserve_chunks_ad;
/****************************/
/*
* base (internal allocation).
*/
/*
* Current pages that are being used for internal memory allocations. These
* pages are carved up in cacheline-size quanta, so that there is no chance of
* false cache line sharing.
*/
static void *base_pages;
static void *base_next_addr;
#ifdef MALLOC_DECOMMIT
static void *base_next_decommitted;
#endif
static void *base_past_addr; /* Addr immediately past base_pages. */
static extent_node_t *base_nodes;
static reserve_reg_t *base_reserve_regs;
static malloc_mutex_t base_mtx;
#ifdef MALLOC_STATS
static size_t base_mapped;
#endif
/********/
/*
* Arenas.
*/
/*
* Arenas that are used to service external requests. Not all elements of the
* arenas array are necessarily used; arenas are created lazily as needed.
*/
static arena_t **arenas;
static unsigned narenas;
static unsigned narenas_2pow;
#ifndef NO_TLS
# ifdef MALLOC_BALANCE
static unsigned narenas_2pow;
# else
static unsigned next_arena;
# endif
#endif
#ifdef MOZ_MEMORY
static malloc_spinlock_t arenas_lock; /* Protects arenas initialization. */
#else
static pthread_mutex_t arenas_lock; /* Protects arenas initialization. */
#endif
#ifndef NO_TLS
/*
* Map of pthread_self() --> arenas[???], used for selecting an arena to use
* for allocations.
*/
#ifndef MOZ_MEMORY_WINDOWS
static __thread arena_t *arenas_map;
#endif
#endif
#ifdef MALLOC_STATS
/* Chunk statistics. */
static chunk_stats_t stats_chunks;
#endif
/*******************************/
/*
* Runtime configuration options.
*/
const char *_malloc_options;
#ifndef MALLOC_PRODUCTION
static bool opt_abort = true;
#ifdef MALLOC_FILL
static bool opt_junk = true;
#endif
#else
static bool opt_abort = false;
#ifdef MALLOC_FILL
static bool opt_junk = false;
#endif
#endif
static size_t opt_dirty_max = DIRTY_MAX_DEFAULT;
#ifdef MALLOC_BALANCE
static uint64_t opt_balance_threshold = BALANCE_THRESHOLD_DEFAULT;
#endif
static bool opt_print_stats = false;
static size_t opt_quantum_2pow = QUANTUM_2POW_MIN;
static size_t opt_small_max_2pow = SMALL_MAX_2POW_DEFAULT;
static size_t opt_chunk_2pow = CHUNK_2POW_DEFAULT;
static int opt_reserve_min_lshift = 0;
static int opt_reserve_range_lshift = 0;
#ifdef MALLOC_PAGEFILE
static bool opt_pagefile = true;
#endif
#ifdef MALLOC_UTRACE
static bool opt_utrace = false;
#endif
#ifdef MALLOC_SYSV
static bool opt_sysv = false;
#endif
#ifdef MALLOC_XMALLOC
static bool opt_xmalloc = false;
#endif
#ifdef MALLOC_FILL
static bool opt_zero = false;
#endif
static int opt_narenas_lshift = 0;
#ifdef MALLOC_UTRACE
typedef struct {
void *p;
size_t s;
void *r;
} malloc_utrace_t;
#define UTRACE(a, b, c) \
if (opt_utrace) { \
malloc_utrace_t ut; \
ut.p = (a); \
ut.s = (b); \
ut.r = (c); \
utrace(&ut, sizeof(ut)); \
}
#else
#define UTRACE(a, b, c)
#endif
/******************************************************************************/
/*
* Begin function prototypes for non-inline static functions.
*/
static char *umax2s(uintmax_t x, char *s);
static bool malloc_mutex_init(malloc_mutex_t *mutex);
static bool malloc_spin_init(malloc_spinlock_t *lock);
static void wrtmessage(const char *p1, const char *p2, const char *p3,
const char *p4);
#ifdef MALLOC_STATS
#ifdef MOZ_MEMORY_DARWIN
/* Avoid namespace collision with OS X's malloc APIs. */
#define malloc_printf moz_malloc_printf
#endif
static void malloc_printf(const char *format, ...);
#endif
static bool base_pages_alloc_mmap(size_t minsize);
static bool base_pages_alloc(size_t minsize);
static void *base_alloc(size_t size);
static void *base_calloc(size_t number, size_t size);
static extent_node_t *base_node_alloc(void);
static void base_node_dealloc(extent_node_t *node);
static reserve_reg_t *base_reserve_reg_alloc(void);
static void base_reserve_reg_dealloc(reserve_reg_t *reg);
#ifdef MALLOC_STATS
static void stats_print(arena_t *arena);
#endif
static void *pages_map(void *addr, size_t size, int pfd);
static void pages_unmap(void *addr, size_t size);
static void *chunk_alloc_mmap(size_t size, bool pagefile);
#ifdef MALLOC_PAGEFILE
static int pagefile_init(size_t size);
static void pagefile_close(int pfd);
#endif
static void *chunk_recycle_reserve(size_t size, bool zero);
static void *chunk_alloc(size_t size, bool zero, bool pagefile);
static extent_node_t *chunk_dealloc_reserve(void *chunk, size_t size);
static void chunk_dealloc_mmap(void *chunk, size_t size);
static void chunk_dealloc(void *chunk, size_t size);
#ifndef NO_TLS
static arena_t *choose_arena_hard(void);
#endif
static void arena_run_split(arena_t *arena, arena_run_t *run, size_t size,
bool large, bool zero);
static void arena_chunk_init(arena_t *arena, arena_chunk_t *chunk);
static void arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk);
static arena_run_t *arena_run_alloc(arena_t *arena, arena_bin_t *bin,
size_t size, bool large, bool zero);
static void arena_purge(arena_t *arena);
static void arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty);
static void arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk,
arena_run_t *run, size_t oldsize, size_t newsize);
static void arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk,
arena_run_t *run, size_t oldsize, size_t newsize, bool dirty);
static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin);
static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin);
static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size);
#ifdef MALLOC_BALANCE
static void arena_lock_balance_hard(arena_t *arena);
#endif
static void *arena_malloc_large(arena_t *arena, size_t size, bool zero);
static void *arena_palloc(arena_t *arena, size_t alignment, size_t size,
size_t alloc_size);
static size_t arena_salloc(const void *ptr);
static void arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk,
void *ptr);
static void arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk,
void *ptr, size_t size, size_t oldsize);
static bool arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk,
void *ptr, size_t size, size_t oldsize);
static bool arena_ralloc_large(void *ptr, size_t size, size_t oldsize);
static void *arena_ralloc(void *ptr, size_t size, size_t oldsize);
static bool arena_new(arena_t *arena);
static arena_t *arenas_extend(unsigned ind);
static void *huge_malloc(size_t size, bool zero);
static void *huge_palloc(size_t alignment, size_t size);
static void *huge_ralloc(void *ptr, size_t size, size_t oldsize);
static void huge_dalloc(void *ptr);
static void malloc_print_stats(void);
#ifndef MOZ_MEMORY_WINDOWS
static
#endif
bool malloc_init_hard(void);
static void reserve_shrink(void);
static uint64_t reserve_notify(reserve_cnd_t cnd, size_t size, uint64_t seq);
static uint64_t reserve_crit(size_t size, const char *fname, uint64_t seq);
static void reserve_fail(size_t size, const char *fname);
/*
* End function prototypes.
*/
/******************************************************************************/
/*
* umax2s() provides minimal integer printing functionality, which is
* especially useful for situations where allocation in vsnprintf() calls would
* potentially cause deadlock.
*/
#define UMAX2S_BUFSIZE 21
static char *
umax2s(uintmax_t x, char *s)
{
unsigned i;
i = UMAX2S_BUFSIZE - 1;
s[i] = '\0';
do {
i--;
s[i] = "0123456789"[x % 10];
x /= 10;
} while (x > 0);
return (&s[i]);
}
static void
wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
{
#if defined(MOZ_MEMORY) && !defined(MOZ_MEMORY_WINDOWS)
#define _write write
#endif
_write(STDERR_FILENO, p1, (unsigned int) strlen(p1));
_write(STDERR_FILENO, p2, (unsigned int) strlen(p2));
_write(STDERR_FILENO, p3, (unsigned int) strlen(p3));
_write(STDERR_FILENO, p4, (unsigned int) strlen(p4));
}
#define _malloc_message malloc_message
void (*_malloc_message)(const char *p1, const char *p2, const char *p3,
const char *p4) = wrtmessage;
#ifdef MALLOC_DEBUG
# define assert(e) do { \
if (!(e)) { \
char line_buf[UMAX2S_BUFSIZE]; \
_malloc_message(__FILE__, ":", umax2s(__LINE__, \
line_buf), ": Failed assertion: "); \
_malloc_message("\"", #e, "\"\n", ""); \
abort(); \
} \
} while (0)
#else
#define assert(e)
#endif
/******************************************************************************/
/*
* Begin mutex. We can't use normal pthread mutexes in all places, because
* they require malloc()ed memory, which causes bootstrapping issues in some
* cases.
*/
static bool
malloc_mutex_init(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
if (__isthreaded)
if (! __crtInitCritSecAndSpinCount(mutex, _CRT_SPINCOUNT))
return (true);
#elif defined(MOZ_MEMORY_DARWIN)
mutex->lock = OS_SPINLOCK_INIT;
#elif defined(MOZ_MEMORY_LINUX)
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0)
return (true);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
if (pthread_mutex_init(mutex, &attr) != 0) {
pthread_mutexattr_destroy(&attr);
return (true);
}
pthread_mutexattr_destroy(&attr);
#elif defined(MOZ_MEMORY)
if (pthread_mutex_init(mutex, NULL) != 0)
return (true);
#else
static const spinlock_t lock = _SPINLOCK_INITIALIZER;
mutex->lock = lock;
#endif
return (false);
}
static inline void
malloc_mutex_lock(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
EnterCriticalSection(mutex);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockLock(&mutex->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_lock(mutex);
#else
if (__isthreaded)
_SPINLOCK(&mutex->lock);
#endif
}
static inline void
malloc_mutex_unlock(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
LeaveCriticalSection(mutex);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockUnlock(&mutex->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_unlock(mutex);
#else
if (__isthreaded)
_SPINUNLOCK(&mutex->lock);
#endif
}
static bool
malloc_spin_init(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
if (__isthreaded)
if (! __crtInitCritSecAndSpinCount(lock, _CRT_SPINCOUNT))
return (true);
#elif defined(MOZ_MEMORY_DARWIN)
lock->lock = OS_SPINLOCK_INIT;
#elif defined(MOZ_MEMORY_LINUX)
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0)
return (true);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
if (pthread_mutex_init(lock, &attr) != 0) {
pthread_mutexattr_destroy(&attr);
return (true);
}
pthread_mutexattr_destroy(&attr);
#elif defined(MOZ_MEMORY)
if (pthread_mutex_init(lock, NULL) != 0)
return (true);
#else
lock->lock = _SPINLOCK_INITIALIZER;
#endif
return (false);
}
static inline void
malloc_spin_lock(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
EnterCriticalSection(lock);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockLock(&lock->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_lock(lock);
#else
if (__isthreaded)
_SPINLOCK(&lock->lock);
#endif
}
static inline void
malloc_spin_unlock(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
LeaveCriticalSection(lock);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockUnlock(&lock->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_unlock(lock);
#else
if (__isthreaded)
_SPINUNLOCK(&lock->lock);
#endif
}
/*
* End mutex.
*/
/******************************************************************************/
/*
* Begin spin lock. Spin locks here are actually adaptive mutexes that block
* after a period of spinning, because unbounded spinning would allow for
* priority inversion.
*/
#if defined(MOZ_MEMORY) && !defined(MOZ_MEMORY_DARWIN)
# define malloc_spin_init malloc_mutex_init
# define malloc_spin_lock malloc_mutex_lock
# define malloc_spin_unlock malloc_mutex_unlock
#endif
#ifndef MOZ_MEMORY
/*
* We use an unpublished interface to initialize pthread mutexes with an
* allocation callback, in order to avoid infinite recursion.
*/
int _pthread_mutex_init_calloc_cb(pthread_mutex_t *mutex,
void *(calloc_cb)(size_t, size_t));
__weak_reference(_pthread_mutex_init_calloc_cb_stub,
_pthread_mutex_init_calloc_cb);
int
_pthread_mutex_init_calloc_cb_stub(pthread_mutex_t *mutex,
void *(calloc_cb)(size_t, size_t))
{
return (0);
}
static bool
malloc_spin_init(pthread_mutex_t *lock)
{
if (_pthread_mutex_init_calloc_cb(lock, base_calloc) != 0)
return (true);
return (false);
}
static inline unsigned
malloc_spin_lock(pthread_mutex_t *lock)
{
unsigned ret = 0;
if (__isthreaded) {
if (_pthread_mutex_trylock(lock) != 0) {
unsigned i;
volatile unsigned j;
/* Exponentially back off. */
for (i = 1; i <= SPIN_LIMIT_2POW; i++) {
for (j = 0; j < (1U << i); j++)
ret++;
CPU_SPINWAIT;
if (_pthread_mutex_trylock(lock) == 0)
return (ret);
}
/*
* Spinning failed. Block until the lock becomes
* available, in order to avoid indefinite priority
* inversion.
*/
_pthread_mutex_lock(lock);
assert((ret << BLOCK_COST_2POW) != 0);
return (ret << BLOCK_COST_2POW);
}
}
return (ret);
}
static inline void
malloc_spin_unlock(pthread_mutex_t *lock)
{
if (__isthreaded)
_pthread_mutex_unlock(lock);
}
#endif
/*
* End spin lock.
*/
/******************************************************************************/
/*
* Begin Utility functions/macros.
*/
/* Return the chunk address for allocation address a. */
#define CHUNK_ADDR2BASE(a) \
((void *)((uintptr_t)(a) & ~chunksize_mask))
/* Return the chunk offset of address a. */
#define CHUNK_ADDR2OFFSET(a) \
((size_t)((uintptr_t)(a) & chunksize_mask))
/* Return the smallest chunk multiple that is >= s. */
#define CHUNK_CEILING(s) \
(((s) + chunksize_mask) & ~chunksize_mask)
/* Return the smallest cacheline multiple that is >= s. */
#define CACHELINE_CEILING(s) \
(((s) + (CACHELINE - 1)) & ~(CACHELINE - 1))
/* Return the smallest quantum multiple that is >= a. */
#define QUANTUM_CEILING(a) \
(((a) + quantum_mask) & ~quantum_mask)
/* Return the smallest pagesize multiple that is >= s. */
#define PAGE_CEILING(s) \
(((s) + pagesize_mask) & ~pagesize_mask)
/* Compute the smallest power of 2 that is >= x. */
static inline size_t
pow2_ceil(size_t x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
#if (SIZEOF_PTR == 8)
x |= x >> 32;
#endif
x++;
return (x);
}
#ifdef MALLOC_BALANCE
/*
* Use a simple linear congruential pseudo-random number generator:
*
* prn(y) = (a*x + c) % m
*
* where the following constants ensure maximal period:
*
* a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4.
* c == Odd number (relatively prime to 2^n).
* m == 2^32
*
* See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints.
*
* This choice of m has the disadvantage that the quality of the bits is
* proportional to bit position. For example. the lowest bit has a cycle of 2,
* the next has a cycle of 4, etc. For this reason, we prefer to use the upper
* bits.
*/
# define PRN_DEFINE(suffix, var, a, c) \
static inline void \
sprn_##suffix(uint32_t seed) \
{ \
var = seed; \
} \
\
static inline uint32_t \
prn_##suffix(uint32_t lg_range) \
{ \
uint32_t ret, x; \
\
assert(lg_range > 0); \
assert(lg_range <= 32); \
\
x = (var * (a)) + (c); \
var = x; \
ret = x >> (32 - lg_range); \
\
return (ret); \
}
# define SPRN(suffix, seed) sprn_##suffix(seed)
# define PRN(suffix, lg_range) prn_##suffix(lg_range)
#endif
#ifdef MALLOC_BALANCE
/* Define the PRNG used for arena assignment. */
static __thread uint32_t balance_x;
PRN_DEFINE(balance, balance_x, 1297, 1301)
#endif
#ifdef MALLOC_UTRACE
static int
utrace(const void *addr, size_t len)
{
malloc_utrace_t *ut = (malloc_utrace_t *)addr;
assert(len == sizeof(malloc_utrace_t));
if (ut->p == NULL && ut->s == 0 && ut->r == NULL)
malloc_printf("%d x USER malloc_init()\n", getpid());
else if (ut->p == NULL && ut->r != NULL) {
malloc_printf("%d x USER %p = malloc(%zu)\n", getpid(), ut->r,
ut->s);
} else if (ut->p != NULL && ut->r != NULL) {
malloc_printf("%d x USER %p = realloc(%p, %zu)\n", getpid(),
ut->r, ut->p, ut->s);
} else
malloc_printf("%d x USER free(%p)\n", getpid(), ut->p);
return (0);
}
#endif
static inline const char *
_getprogname(void)
{
return ("<jemalloc>");
}
#ifdef MALLOC_STATS
/*
* Print to stderr in such a way as to (hopefully) avoid memory allocation.
*/
static void
malloc_printf(const char *format, ...)
{
char buf[4096];
va_list ap;
va_start(ap, format);
vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
_malloc_message(buf, "", "", "");
}
#endif
/******************************************************************************/
#ifdef MALLOC_DECOMMIT
static inline void
pages_decommit(void *addr, size_t size)
{
#ifdef MOZ_MEMORY_WINDOWS
VirtualFree(addr, size, MEM_DECOMMIT);
#else
if (mmap(addr, size, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1,
0) == MAP_FAILED)
abort();
#endif
}
static inline void
pages_commit(void *addr, size_t size)
{
# ifdef MOZ_MEMORY_WINDOWS
VirtualAlloc(addr, size, MEM_COMMIT, PAGE_READWRITE);
# else
if (mmap(addr, size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE |
MAP_ANON, -1, 0) == MAP_FAILED)
abort();
# endif
}
#endif
static bool
base_pages_alloc_mmap(size_t minsize)
{
bool ret;
size_t csize;
#ifdef MALLOC_DECOMMIT
size_t pminsize;
#endif
int pfd;
assert(minsize != 0);
csize = CHUNK_CEILING(minsize);
#ifdef MALLOC_PAGEFILE
if (opt_pagefile) {
pfd = pagefile_init(csize);
if (pfd == -1)
return (true);
} else
#endif
pfd = -1;
base_pages = pages_map(NULL, csize, pfd);
if (base_pages == NULL) {
ret = true;
goto RETURN;
}
base_next_addr = base_pages;
base_past_addr = (void *)((uintptr_t)base_pages + csize);
#ifdef MALLOC_DECOMMIT
/*
* Leave enough pages for minsize committed, since otherwise they would
* have to be immediately recommitted.
*/
pminsize = PAGE_CEILING(minsize);
base_next_decommitted = (void *)((uintptr_t)base_pages + pminsize);
if (pminsize < csize)
pages_decommit(base_next_decommitted, csize - pminsize);
#endif
#ifdef MALLOC_STATS
base_mapped += csize;
#endif
ret = false;
RETURN:
#ifdef MALLOC_PAGEFILE
if (pfd != -1)
pagefile_close(pfd);
#endif
return (false);
}
static bool
base_pages_alloc(size_t minsize)
{
if (base_pages_alloc_mmap(minsize) == false)
return (false);
return (true);
}
static void *
base_alloc(size_t size)
{
void *ret;
size_t csize;
/* Round size up to nearest multiple of the cacheline size. */
csize = CACHELINE_CEILING(size);
malloc_mutex_lock(&base_mtx);
/* Make sure there's enough space for the allocation. */
if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
if (base_pages_alloc(csize)) {
malloc_mutex_unlock(&base_mtx);
return (NULL);
}
}
/* Allocate. */
ret = base_next_addr;
base_next_addr = (void *)((uintptr_t)base_next_addr + csize);
#ifdef MALLOC_DECOMMIT
/* Make sure enough pages are committed for the new allocation. */
if ((uintptr_t)base_next_addr > (uintptr_t)base_next_decommitted) {
void *pbase_next_addr =
(void *)(PAGE_CEILING((uintptr_t)base_next_addr));
pages_commit(base_next_decommitted, (uintptr_t)pbase_next_addr -
(uintptr_t)base_next_decommitted);
base_next_decommitted = pbase_next_addr;
}
#endif
malloc_mutex_unlock(&base_mtx);
VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, false);
return (ret);
}
static void *
base_calloc(size_t number, size_t size)
{
void *ret;
ret = base_alloc(number * size);
#ifdef MALLOC_VALGRIND
if (ret != NULL) {
VALGRIND_FREELIKE_BLOCK(ret, 0);
VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, true);
}
#endif
memset(ret, 0, number * size);
return (ret);
}
static extent_node_t *
base_node_alloc(void)
{
extent_node_t *ret;
malloc_mutex_lock(&base_mtx);
if (base_nodes != NULL) {
ret = base_nodes;
base_nodes = *(extent_node_t **)ret;
VALGRIND_FREELIKE_BLOCK(ret, 0);
VALGRIND_MALLOCLIKE_BLOCK(ret, sizeof(extent_node_t), 0, false);
malloc_mutex_unlock(&base_mtx);
} else {
malloc_mutex_unlock(&base_mtx);
ret = (extent_node_t *)base_alloc(sizeof(extent_node_t));
}
return (ret);
}
static void
base_node_dealloc(extent_node_t *node)
{
malloc_mutex_lock(&base_mtx);
VALGRIND_FREELIKE_BLOCK(node, 0);
VALGRIND_MALLOCLIKE_BLOCK(node, sizeof(extent_node_t *), 0, false);
*(extent_node_t **)node = base_nodes;
base_nodes = node;
malloc_mutex_unlock(&base_mtx);
}
static reserve_reg_t *
base_reserve_reg_alloc(void)
{
reserve_reg_t *ret;
malloc_mutex_lock(&base_mtx);
if (base_reserve_regs != NULL) {
ret = base_reserve_regs;
base_reserve_regs = *(reserve_reg_t **)ret;
VALGRIND_FREELIKE_BLOCK(ret, 0);
VALGRIND_MALLOCLIKE_BLOCK(ret, sizeof(reserve_reg_t), 0, false);
malloc_mutex_unlock(&base_mtx);
} else {
malloc_mutex_unlock(&base_mtx);
ret = (reserve_reg_t *)base_alloc(sizeof(reserve_reg_t));
}
return (ret);
}
static void
base_reserve_reg_dealloc(reserve_reg_t *reg)
{
malloc_mutex_lock(&base_mtx);
VALGRIND_FREELIKE_BLOCK(reg, 0);
VALGRIND_MALLOCLIKE_BLOCK(reg, sizeof(reserve_reg_t *), 0, false);
*(reserve_reg_t **)reg = base_reserve_regs;
base_reserve_regs = reg;
malloc_mutex_unlock(&base_mtx);
}
/******************************************************************************/
#ifdef MALLOC_STATS
static void
stats_print(arena_t *arena)
{
unsigned i, gap_start;
#ifdef MOZ_MEMORY_WINDOWS
malloc_printf("dirty: %Iu page%s dirty, %I64u sweep%s,"
" %I64u madvise%s, %I64u page%s purged\n",
arena->ndirty, arena->ndirty == 1 ? "" : "s",
arena->stats.npurge, arena->stats.npurge == 1 ? "" : "s",
arena->stats.nmadvise, arena->stats.nmadvise == 1 ? "" : "s",
arena->stats.purged, arena->stats.purged == 1 ? "" : "s");
# ifdef MALLOC_DECOMMIT
malloc_printf("decommit: %I64u decommit%s, %I64u commit%s,"
" %I64u page%s decommitted\n",
arena->stats.ndecommit, (arena->stats.ndecommit == 1) ? "" : "s",
arena->stats.ncommit, (arena->stats.ncommit == 1) ? "" : "s",
arena->stats.decommitted,
(arena->stats.decommitted == 1) ? "" : "s");
# endif
malloc_printf(" allocated nmalloc ndalloc\n");
malloc_printf("small: %12Iu %12I64u %12I64u\n",
arena->stats.allocated_small, arena->stats.nmalloc_small,
arena->stats.ndalloc_small);
malloc_printf("large: %12Iu %12I64u %12I64u\n",
arena->stats.allocated_large, arena->stats.nmalloc_large,
arena->stats.ndalloc_large);
malloc_printf("total: %12Iu %12I64u %12I64u\n",
arena->stats.allocated_small + arena->stats.allocated_large,
arena->stats.nmalloc_small + arena->stats.nmalloc_large,
arena->stats.ndalloc_small + arena->stats.ndalloc_large);
malloc_printf("mapped: %12Iu\n", arena->stats.mapped);
#else
malloc_printf("dirty: %zu page%s dirty, %llu sweep%s,"
" %llu madvise%s, %llu page%s purged\n",
arena->ndirty, arena->ndirty == 1 ? "" : "s",
arena->stats.npurge, arena->stats.npurge == 1 ? "" : "s",
arena->stats.nmadvise, arena->stats.nmadvise == 1 ? "" : "s",
arena->stats.purged, arena->stats.purged == 1 ? "" : "s");
# ifdef MALLOC_DECOMMIT
malloc_printf("decommit: %llu decommit%s, %llu commit%s,"
" %llu page%s decommitted\n",
arena->stats.ndecommit, (arena->stats.ndecommit == 1) ? "" : "s",
arena->stats.ncommit, (arena->stats.ncommit == 1) ? "" : "s",
arena->stats.decommitted,
(arena->stats.decommitted == 1) ? "" : "s");
# endif
malloc_printf(" allocated nmalloc ndalloc\n");
malloc_printf("small: %12zu %12llu %12llu\n",
arena->stats.allocated_small, arena->stats.nmalloc_small,
arena->stats.ndalloc_small);
malloc_printf("large: %12zu %12llu %12llu\n",
arena->stats.allocated_large, arena->stats.nmalloc_large,
arena->stats.ndalloc_large);
malloc_printf("total: %12zu %12llu %12llu\n",
arena->stats.allocated_small + arena->stats.allocated_large,
arena->stats.nmalloc_small + arena->stats.nmalloc_large,
arena->stats.ndalloc_small + arena->stats.ndalloc_large);
malloc_printf("mapped: %12zu\n", arena->stats.mapped);
#endif
malloc_printf("bins: bin size regs pgs requests newruns"
" reruns maxruns curruns\n");
for (i = 0, gap_start = UINT_MAX; i < ntbins + nqbins + nsbins; i++) {
if (arena->bins[i].stats.nrequests == 0) {
if (gap_start == UINT_MAX)
gap_start = i;
} else {
if (gap_start != UINT_MAX) {
if (i > gap_start + 1) {
/* Gap of more than one size class. */
malloc_printf("[%u..%u]\n",
gap_start, i - 1);
} else {
/* Gap of one size class. */
malloc_printf("[%u]\n", gap_start);
}
gap_start = UINT_MAX;
}
malloc_printf(
#if defined(MOZ_MEMORY_WINDOWS)
"%13u %1s %4u %4u %3u %9I64u %9I64u"
" %9I64u %7u %7u\n",
#else
"%13u %1s %4u %4u %3u %9llu %9llu"
" %9llu %7lu %7lu\n",
#endif
i,
i < ntbins ? "T" : i < ntbins + nqbins ? "Q" : "S",
arena->bins[i].reg_size,
arena->bins[i].nregs,
arena->bins[i].run_size >> pagesize_2pow,
arena->bins[i].stats.nrequests,
arena->bins[i].stats.nruns,
arena->bins[i].stats.reruns,
arena->bins[i].stats.highruns,
arena->bins[i].stats.curruns);
}
}
if (gap_start != UINT_MAX) {
if (i > gap_start + 1) {
/* Gap of more than one size class. */
malloc_printf("[%u..%u]\n", gap_start, i - 1);
} else {
/* Gap of one size class. */
malloc_printf("[%u]\n", gap_start);
}
}
}
#endif
/*
* End Utility functions/macros.
*/
/******************************************************************************/
/*
* Begin extent tree code.
*/
static inline int
extent_szad_comp(extent_node_t *a, extent_node_t *b)
{
int ret;
size_t a_size = a->size;
size_t b_size = b->size;
ret = (a_size > b_size) - (a_size < b_size);
if (ret == 0) {
uintptr_t a_addr = (uintptr_t)a->addr;
uintptr_t b_addr = (uintptr_t)b->addr;
ret = (a_addr > b_addr) - (a_addr < b_addr);
}
return (ret);
}
/* Wrap red-black tree macros in functions. */
rb_wrap(static, extent_tree_szad_, extent_tree_t, extent_node_t,
link_szad, extent_szad_comp)
static inline int
extent_ad_comp(extent_node_t *a, extent_node_t *b)
{
uintptr_t a_addr = (uintptr_t)a->addr;
uintptr_t b_addr = (uintptr_t)b->addr;
return ((a_addr > b_addr) - (a_addr < b_addr));
}
/* Wrap red-black tree macros in functions. */
rb_wrap(static, extent_tree_ad_, extent_tree_t, extent_node_t, link_ad,
extent_ad_comp)
/*
* End extent tree code.
*/
/******************************************************************************/
/*
* Begin chunk management functions.
*/
#ifdef MOZ_MEMORY_WINDOWS
static void *
pages_map(void *addr, size_t size, int pfd)
{
void *ret;
ret = VirtualAlloc(addr, size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
return (ret);
}
static void
pages_unmap(void *addr, size_t size)
{
if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
_malloc_message(_getprogname(),
": (malloc) Error in VirtualFree()\n", "", "");
if (opt_abort)
abort();
}
}
#elif (defined(MOZ_MEMORY_DARWIN))
static void *
pages_map(void *addr, size_t size, int pfd)
{
void *ret;
kern_return_t err;
int flags;
if (addr != NULL) {
ret = addr;
flags = 0;
} else
flags = VM_FLAGS_ANYWHERE;
err = vm_allocate((vm_map_t)mach_task_self(), (vm_address_t *)&ret,
(vm_size_t)size, flags);
if (err != KERN_SUCCESS)
ret = NULL;
assert(ret == NULL || (addr == NULL && ret != addr)
|| (addr != NULL && ret == addr));
return (ret);
}
static void
pages_unmap(void *addr, size_t size)
{
kern_return_t err;
err = vm_deallocate((vm_map_t)mach_task_self(), (vm_address_t)addr,
(vm_size_t)size);
if (err != KERN_SUCCESS) {
malloc_message(_getprogname(),
": (malloc) Error in vm_deallocate(): ",
mach_error_string(err), "\n");
if (opt_abort)
abort();
}
}
#define VM_COPY_MIN (pagesize << 5)
static inline void
pages_copy(void *dest, const void *src, size_t n)
{
assert((void *)((uintptr_t)dest & ~pagesize_mask) == dest);
assert(n >= VM_COPY_MIN);
assert((void *)((uintptr_t)src & ~pagesize_mask) == src);
vm_copy(mach_task_self(), (vm_address_t)src, (vm_size_t)n,
(vm_address_t)dest);
}
#else /* MOZ_MEMORY_DARWIN */
static void *
pages_map(void *addr, size_t size, int pfd)
{
void *ret;
/*
* We don't use MAP_FIXED here, because it can cause the *replacement*
* of existing mappings, and we only want to create new mappings.
*/
#ifdef MALLOC_PAGEFILE
if (pfd != -1) {
ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE |
MAP_NOSYNC, pfd, 0);
} else
#endif
{
ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE |
MAP_ANON, -1, 0);
}
assert(ret != NULL);
if (ret == MAP_FAILED)
ret = NULL;
else if (addr != NULL && ret != addr) {
/*
* We succeeded in mapping memory, but not in the right place.
*/
if (munmap(ret, size) == -1) {
char buf[STRERROR_BUF];
strerror_r(errno, buf, sizeof(buf));
_malloc_message(_getprogname(),
": (malloc) Error in munmap(): ", buf, "\n");
if (opt_abort)
abort();
}
ret = NULL;
}
assert(ret == NULL || (addr == NULL && ret != addr)
|| (addr != NULL && ret == addr));
return (ret);
}
static void
pages_unmap(void *addr, size_t size)
{
if (munmap(addr, size) == -1) {
char buf[STRERROR_BUF];
strerror_r(errno, buf, sizeof(buf));
_malloc_message(_getprogname(),
": (malloc) Error in munmap(): ", buf, "\n");
if (opt_abort)
abort();
}
}
#endif
#ifdef MALLOC_VALIDATE
static inline malloc_rtree_t *
malloc_rtree_new(unsigned bits)
{
malloc_rtree_t *ret;
unsigned bits_per_level, height, i;
bits_per_level = ffs(pow2_ceil((MALLOC_RTREE_NODESIZE /
sizeof(void *)))) - 1;
height = bits / bits_per_level;
if (height * bits_per_level != bits)
height++;
assert(height * bits_per_level >= bits);
ret = base_calloc(1, sizeof(malloc_rtree_t) + (sizeof(unsigned) *
(height - 1)));
if (ret == NULL)
return (NULL);
malloc_spin_init(&ret->lock);
ret->height = height;
if (bits_per_level * height > bits)
ret->level2bits[0] = bits % bits_per_level;
else
ret->level2bits[0] = bits_per_level;
for (i = 1; i < height; i++)
ret->level2bits[i] = bits_per_level;
ret->root = base_calloc(1, sizeof(void *) << ret->level2bits[0]);
if (ret->root == NULL) {
/*
* We leak the rtree here, since there's no generic base
* deallocation.
*/
return (NULL);
}
return (ret);
}
/* The least significant bits of the key are ignored. */
static inline void *
malloc_rtree_get(malloc_rtree_t *rtree, uintptr_t key)
{
void *ret;
uintptr_t subkey;
unsigned i, lshift, height, bits;
void **node, **child;
malloc_spin_lock(&rtree->lock);
for (i = lshift = 0, height = rtree->height, node = rtree->root;
i < height - 1;
i++, lshift += bits, node = child) {
bits = rtree->level2bits[i];
subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits);
child = node[subkey];
if (child == NULL) {
malloc_spin_unlock(&rtree->lock);
return (NULL);
}
}
/* node is a leaf, so it contains values rather than node pointers. */
bits = rtree->level2bits[i];
subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits);
ret = node[subkey];
malloc_spin_unlock(&rtree->lock);
return (ret);
}
static inline bool
malloc_rtree_set(malloc_rtree_t *rtree, uintptr_t key, void *val)
{
uintptr_t subkey;
unsigned i, lshift, height, bits;
void **node, **child;
malloc_spin_lock(&rtree->lock);
for (i = lshift = 0, height = rtree->height, node = rtree->root;
i < height - 1;
i++, lshift += bits, node = child) {
bits = rtree->level2bits[i];
subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits);
child = node[subkey];
if (child == NULL) {
child = base_calloc(1, sizeof(void *) <<
rtree->level2bits[i+1]);
if (child == NULL) {
malloc_spin_unlock(&rtree->lock);
return (true);
}
node[subkey] = child;
}
}
/* node is a leaf, so it contains values rather than node pointers. */
bits = rtree->level2bits[i];
subkey = (key << lshift) >> ((SIZEOF_PTR << 3) - bits);
node[subkey] = val;
malloc_spin_unlock(&rtree->lock);
return (false);
}
#endif
static void *
chunk_alloc_mmap(size_t size, bool pagefile)
{
void *ret;
size_t offset;
int pfd;
#ifdef MALLOC_PAGEFILE
if (opt_pagefile && pagefile) {
pfd = pagefile_init(size);
if (pfd == -1)
return (NULL);
} else
#endif
pfd = -1;
/*
* Windows requires that there be a 1:1 mapping between VM
* allocation/deallocation operations. Therefore, take care here to
* acquire the final result via one mapping operation. This means
* unmapping any preliminary result that is not correctly aligned.
*
* The MALLOC_PAGEFILE code also benefits from this mapping algorithm,
* since it reduces the number of page files.
*/
ret = pages_map(NULL, size, pfd);
if (ret == NULL)
goto RETURN;
offset = CHUNK_ADDR2OFFSET(ret);
if (offset != 0) {
/* Deallocate, then try to allocate at (ret + size - offset). */
pages_unmap(ret, size);
ret = pages_map((void *)((uintptr_t)ret + size - offset), size,
pfd);
while (ret == NULL) {
/*
* Over-allocate in order to map a memory region that
* is definitely large enough.
*/
ret = pages_map(NULL, size + chunksize, -1);
if (ret == NULL)
goto RETURN;
/*
* Deallocate, then allocate the correct size, within
* the over-sized mapping.
*/
offset = CHUNK_ADDR2OFFSET(ret);
pages_unmap(ret, size + chunksize);
if (offset == 0)
ret = pages_map(ret, size, pfd);
else {
ret = pages_map((void *)((uintptr_t)ret +
chunksize - offset), size, pfd);
}
/*
* Failure here indicates a race with another thread, so
* try again.
*/
}
}
RETURN:
#ifdef MALLOC_PAGEFILE
if (pfd != -1)
pagefile_close(pfd);
#endif
#ifdef MALLOC_STATS
if (ret != NULL)
stats_chunks.nchunks += (size / chunksize);
#endif
return (ret);
}
#ifdef MALLOC_PAGEFILE
static int
pagefile_init(size_t size)
{
int ret;
size_t i;
char pagefile_path[PATH_MAX];
char zbuf[MALLOC_PAGEFILE_WRITE_SIZE];
/*
* Create a temporary file, then immediately unlink it so that it will
* not persist.
*/
strcpy(pagefile_path, pagefile_templ);
ret = mkstemp(pagefile_path);
if (ret == -1)
return (ret);
if (unlink(pagefile_path)) {
char buf[STRERROR_BUF];
strerror_r(errno, buf, sizeof(buf));
_malloc_message(_getprogname(), ": (malloc) Error in unlink(\"",
pagefile_path, "\"):");
_malloc_message(buf, "\n", "", "");
if (opt_abort)
abort();
}
/*
* Write sequential zeroes to the file in order to assure that disk
* space is committed, with minimal fragmentation. It would be
* sufficient to write one zero per disk block, but that potentially
* results in more system calls, for no real gain.
*/
memset(zbuf, 0, sizeof(zbuf));
for (i = 0; i < size; i += sizeof(zbuf)) {
if (write(ret, zbuf, sizeof(zbuf)) != sizeof(zbuf)) {
if (errno != ENOSPC) {
char buf[STRERROR_BUF];
strerror_r(errno, buf, sizeof(buf));
_malloc_message(_getprogname(),
": (malloc) Error in write(): ", buf, "\n");
if (opt_abort)
abort();
}
pagefile_close(ret);
return (-1);
}
}
return (ret);
}
static void
pagefile_close(int pfd)
{
if (close(pfd)) {
char buf[STRERROR_BUF];
strerror_r(errno, buf, sizeof(buf));
_malloc_message(_getprogname(),
": (malloc) Error in close(): ", buf, "\n");
if (opt_abort)
abort();
}
}
#endif
static void *
chunk_recycle_reserve(size_t size, bool zero)
{
extent_node_t *node, key;
#ifdef MALLOC_DECOMMIT
if (size != chunksize)
return (NULL);
#endif
key.addr = NULL;
key.size = size;
malloc_mutex_lock(&reserve_mtx);
node = extent_tree_szad_nsearch(&reserve_chunks_szad, &key);
if (node != NULL) {
void *ret = node->addr;
/* Remove node from the tree. */
extent_tree_szad_remove(&reserve_chunks_szad, node);
#ifndef MALLOC_DECOMMIT
if (node->size == size) {
#else
assert(node->size == size);
#endif
extent_tree_ad_remove(&reserve_chunks_ad, node);
base_node_dealloc(node);
#ifndef MALLOC_DECOMMIT
} else {
/*
* Insert the remainder of node's address range as a
* smaller chunk. Its position within reserve_chunks_ad
* does not change.
*/
assert(node->size > size);
node->addr = (void *)((uintptr_t)node->addr + size);
node->size -= size;
extent_tree_szad_insert(&reserve_chunks_szad, node);
}
#endif
reserve_cur -= size;
/*
* Try to replenish the reserve if this allocation depleted it.
*/
#ifndef MALLOC_DECOMMIT
if (reserve_cur < reserve_min) {
size_t diff = reserve_min - reserve_cur;
#else
while (reserve_cur < reserve_min) {
# define diff chunksize
#endif
void *chunk;
malloc_mutex_unlock(&reserve_mtx);
chunk = chunk_alloc_mmap(diff, true);
malloc_mutex_lock(&reserve_mtx);
if (chunk == NULL) {
uint64_t seq = 0;
do {
seq = reserve_notify(RESERVE_CND_LOW,
size, seq);
} while (reserve_cur < reserve_min && seq != 0);
} else {
extent_node_t *node;
node = chunk_dealloc_reserve(chunk, diff);
if (node == NULL) {
uint64_t seq = 0;
pages_unmap(chunk, diff);
do {
seq = reserve_notify(
RESERVE_CND_LOW, size, seq);
} while (reserve_cur < reserve_min &&
seq != 0);
}
}
}
malloc_mutex_unlock(&reserve_mtx);
#ifdef MALLOC_DECOMMIT
pages_commit(ret, size);
# undef diff
#else
if (zero)
memset(ret, 0, size);
#endif
return (ret);
}
malloc_mutex_unlock(&reserve_mtx);
return (NULL);
}
static void *
chunk_alloc(size_t size, bool zero, bool pagefile)
{
void *ret;
assert(size != 0);
assert((size & chunksize_mask) == 0);
ret = chunk_recycle_reserve(size, zero);
if (ret != NULL)
goto RETURN;
ret = chunk_alloc_mmap(size, pagefile);
if (ret != NULL) {
goto RETURN;
}
/* All strategies for allocation failed. */
ret = NULL;
RETURN:
#ifdef MALLOC_STATS
if (ret != NULL)
stats_chunks.curchunks += (size / chunksize);
if (stats_chunks.curchunks > stats_chunks.highchunks)
stats_chunks.highchunks = stats_chunks.curchunks;
#endif
#ifdef MALLOC_VALIDATE
if (ret != NULL) {
if (malloc_rtree_set(chunk_rtree, (uintptr_t)ret, ret)) {
chunk_dealloc(ret, size);
return (NULL);
}
}
#endif
assert(CHUNK_ADDR2BASE(ret) == ret);
return (ret);
}
static extent_node_t *
chunk_dealloc_reserve(void *chunk, size_t size)
{
extent_node_t *node;
#ifdef MALLOC_DECOMMIT
if (size != chunksize)
return (NULL);
#else
extent_node_t *prev, key;
key.addr = (void *)((uintptr_t)chunk + size);
node = extent_tree_ad_nsearch(&reserve_chunks_ad, &key);
/* Try to coalesce forward. */
if (node != NULL && node->addr == key.addr) {
/*
* Coalesce chunk with the following address range. This does
* not change the position within reserve_chunks_ad, so only
* remove/insert from/into reserve_chunks_szad.
*/
extent_tree_szad_remove(&reserve_chunks_szad, node);
node->addr = chunk;
node->size += size;
extent_tree_szad_insert(&reserve_chunks_szad, node);
} else {
#endif
/* Coalescing forward failed, so insert a new node. */
node = base_node_alloc();
if (node == NULL)
return (NULL);
node->addr = chunk;
node->size = size;
extent_tree_ad_insert(&reserve_chunks_ad, node);
extent_tree_szad_insert(&reserve_chunks_szad, node);
#ifndef MALLOC_DECOMMIT
}
/* Try to coalesce backward. */
prev = extent_tree_ad_prev(&reserve_chunks_ad, node);
if (prev != NULL && (void *)((uintptr_t)prev->addr + prev->size) ==
chunk) {
/*
* Coalesce chunk with the previous address range. This does
* not change the position within reserve_chunks_ad, so only
* remove/insert node from/into reserve_chunks_szad.
*/
extent_tree_szad_remove(&reserve_chunks_szad, prev);
extent_tree_ad_remove(&reserve_chunks_ad, prev);
extent_tree_szad_remove(&reserve_chunks_szad, node);
node->addr = prev->addr;
node->size += prev->size;
extent_tree_szad_insert(&reserve_chunks_szad, node);
base_node_dealloc(prev);
}
#endif
#ifdef MALLOC_DECOMMIT
pages_decommit(chunk, size);
#else
madvise(chunk, size, MADV_FREE);
#endif
reserve_cur += size;
if (reserve_cur > reserve_max)
reserve_shrink();
return (node);
}
static void
chunk_dealloc_mmap(void *chunk, size_t size)
{
pages_unmap(chunk, size);
}
static void
chunk_dealloc(void *chunk, size_t size)
{
extent_node_t *node;
assert(chunk != NULL);
assert(CHUNK_ADDR2BASE(chunk) == chunk);
assert(size != 0);
assert((size & chunksize_mask) == 0);
#ifdef MALLOC_STATS
stats_chunks.curchunks -= (size / chunksize);
#endif
#ifdef MALLOC_VALIDATE
malloc_rtree_set(chunk_rtree, (uintptr_t)chunk, NULL);
#endif
/* Try to merge chunk into the reserve. */
malloc_mutex_lock(&reserve_mtx);
node = chunk_dealloc_reserve(chunk, size);
malloc_mutex_unlock(&reserve_mtx);
if (node == NULL)
chunk_dealloc_mmap(chunk, size);
}
/*
* End chunk management functions.
*/
/******************************************************************************/
/*
* Begin arena.
*/
/*
* Choose an arena based on a per-thread value (fast-path code, calls slow-path
* code if necessary).
*/
static inline arena_t *
choose_arena(void)
{
arena_t *ret;
/*
* We can only use TLS if this is a PIC library, since for the static
* library version, libc's malloc is used by TLS allocation, which
* introduces a bootstrapping issue.
*/
#ifndef NO_TLS
if (__isthreaded == false) {
/* Avoid the overhead of TLS for single-threaded operation. */
return (arenas[0]);
}
# ifdef MOZ_MEMORY_WINDOWS
ret = TlsGetValue(tlsIndex);
# else
ret = arenas_map;
# endif
if (ret == NULL) {
ret = choose_arena_hard();
assert(ret != NULL);
}
#else
if (__isthreaded && narenas > 1) {
unsigned long ind;
/*
* Hash _pthread_self() to one of the arenas. There is a prime
* number of arenas, so this has a reasonable chance of
* working. Even so, the hashing can be easily thwarted by
* inconvenient _pthread_self() values. Without specific
* knowledge of how _pthread_self() calculates values, we can't
* easily do much better than this.
*/
ind = (unsigned long) _pthread_self() % narenas;
/*
* Optimistially assume that arenas[ind] has been initialized.
* At worst, we find out that some other thread has already
* done so, after acquiring the lock in preparation. Note that
* this lazy locking also has the effect of lazily forcing
* cache coherency; without the lock acquisition, there's no
* guarantee that modification of arenas[ind] by another thread
* would be seen on this CPU for an arbitrary amount of time.
*
* In general, this approach to modifying a synchronized value
* isn't a good idea, but in this case we only ever modify the
* value once, so things work out well.
*/
ret = arenas[ind];
if (ret == NULL) {
/*
* Avoid races with another thread that may have already
* initialized arenas[ind].
*/
malloc_spin_lock(&arenas_lock);
if (arenas[ind] == NULL)
ret = arenas_extend((unsigned)ind);
else
ret = arenas[ind];
malloc_spin_unlock(&arenas_lock);
}
} else
ret = arenas[0];
#endif
assert(ret != NULL);
return (ret);
}
#ifndef NO_TLS
/*
* Choose an arena based on a per-thread value (slow-path code only, called
* only by choose_arena()).
*/
static arena_t *
choose_arena_hard(void)
{
arena_t *ret;
assert(__isthreaded);
#ifdef MALLOC_BALANCE
/* Seed the PRNG used for arena load balancing. */
SPRN(balance, (uint32_t)(uintptr_t)(_pthread_self()));
#endif
if (narenas > 1) {
#ifdef MALLOC_BALANCE
unsigned ind;
ind = PRN(balance, narenas_2pow);
if ((ret = arenas[ind]) == NULL) {
malloc_spin_lock(&arenas_lock);
if ((ret = arenas[ind]) == NULL)
ret = arenas_extend(ind);
malloc_spin_unlock(&arenas_lock);
}
#else
malloc_spin_lock(&arenas_lock);
if ((ret = arenas[next_arena]) == NULL)
ret = arenas_extend(next_arena);
next_arena = (next_arena + 1) % narenas;
malloc_spin_unlock(&arenas_lock);
#endif
} else
ret = arenas[0];
#ifdef MOZ_MEMORY_WINDOWS
TlsSetValue(tlsIndex, ret);
#else
arenas_map = ret;
#endif
return (ret);
}
#endif
static inline int
arena_chunk_comp(arena_chunk_t *a, arena_chunk_t *b)
{
uintptr_t a_chunk = (uintptr_t)a;
uintptr_t b_chunk = (uintptr_t)b;
assert(a != NULL);
assert(b != NULL);
return ((a_chunk > b_chunk) - (a_chunk < b_chunk));
}
/* Wrap red-black tree macros in functions. */
rb_wrap(static, arena_chunk_tree_dirty_, arena_chunk_tree_t,
arena_chunk_t, link_dirty, arena_chunk_comp)
static inline int
arena_run_comp(arena_chunk_map_t *a, arena_chunk_map_t *b)
{
uintptr_t a_mapelm = (uintptr_t)a;
uintptr_t b_mapelm = (uintptr_t)b;
assert(a != NULL);
assert(b != NULL);
return ((a_mapelm > b_mapelm) - (a_mapelm < b_mapelm));
}
/* Wrap red-black tree macros in functions. */
rb_wrap(static, arena_run_tree_, arena_run_tree_t, arena_chunk_map_t, link,
arena_run_comp)
static inline int
arena_avail_comp(arena_chunk_map_t *a, arena_chunk_map_t *b)
{
int ret;
size_t a_size = a->bits & ~pagesize_mask;
size_t b_size = b->bits & ~pagesize_mask;
ret = (a_size > b_size) - (a_size < b_size);
if (ret == 0) {
uintptr_t a_mapelm, b_mapelm;
if ((a->bits & CHUNK_MAP_KEY) == 0)
a_mapelm = (uintptr_t)a;
else {
/*
* Treat keys as though they are lower than anything
* else.
*/
a_mapelm = 0;
}
b_mapelm = (uintptr_t)b;
ret = (a_mapelm > b_mapelm) - (a_mapelm < b_mapelm);
}
return (ret);
}
/* Wrap red-black tree macros in functions. */
rb_wrap(static, arena_avail_tree_, arena_avail_tree_t, arena_chunk_map_t, link,
arena_avail_comp)
static inline void *
arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin)
{
void *ret;
unsigned i, mask, bit, regind;
assert(run->magic == ARENA_RUN_MAGIC);
assert(run->regs_minelm < bin->regs_mask_nelms);
/*
* Move the first check outside the loop, so that run->regs_minelm can
* be updated unconditionally, without the possibility of updating it
* multiple times.
*/
i = run->regs_minelm;
mask = run->regs_mask[i];
if (mask != 0) {
/* Usable allocation found. */
bit = ffs((int)mask) - 1;
regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
assert(regind < bin->nregs);
ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+ (bin->reg_size * regind));
/* Clear bit. */
mask ^= (1U << bit);
run->regs_mask[i] = mask;
return (ret);
}
for (i++; i < bin->regs_mask_nelms; i++) {
mask = run->regs_mask[i];
if (mask != 0) {
/* Usable allocation found. */
bit = ffs((int)mask) - 1;
regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
assert(regind < bin->nregs);
ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+ (bin->reg_size * regind));
/* Clear bit. */
mask ^= (1U << bit);
run->regs_mask[i] = mask;
/*
* Make a note that nothing before this element
* contains a free region.
*/
run->regs_minelm = i; /* Low payoff: + (mask == 0); */
return (ret);
}
}
/* Not reached. */
assert(0);
return (NULL);
}
static inline void
arena_run_reg_dalloc(arena_run_t *run, arena_bin_t *bin, void *ptr, size_t size)
{
/*
* To divide by a number D that is not a power of two we multiply
* by (2^21 / D) and then right shift by 21 positions.
*
* X / D
*
* becomes
*
* (X * size_invs[(D >> QUANTUM_2POW_MIN) - 3]) >> SIZE_INV_SHIFT
*/
#define SIZE_INV_SHIFT 21
#define SIZE_INV(s) (((1U << SIZE_INV_SHIFT) / (s << QUANTUM_2POW_MIN)) + 1)
static const unsigned size_invs[] = {
SIZE_INV(3),
SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7),
SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11),
SIZE_INV(12),SIZE_INV(13), SIZE_INV(14), SIZE_INV(15),
SIZE_INV(16),SIZE_INV(17), SIZE_INV(18), SIZE_INV(19),
SIZE_INV(20),SIZE_INV(21), SIZE_INV(22), SIZE_INV(23),
SIZE_INV(24),SIZE_INV(25), SIZE_INV(26), SIZE_INV(27),
SIZE_INV(28),SIZE_INV(29), SIZE_INV(30), SIZE_INV(31)
#if (QUANTUM_2POW_MIN < 4)
,
SIZE_INV(32), SIZE_INV(33), SIZE_INV(34), SIZE_INV(35),
SIZE_INV(36), SIZE_INV(37), SIZE_INV(38), SIZE_INV(39),
SIZE_INV(40), SIZE_INV(41), SIZE_INV(42), SIZE_INV(43),
SIZE_INV(44), SIZE_INV(45), SIZE_INV(46), SIZE_INV(47),
SIZE_INV(48), SIZE_INV(49), SIZE_INV(50), SIZE_INV(51),
SIZE_INV(52), SIZE_INV(53), SIZE_INV(54), SIZE_INV(55),
SIZE_INV(56), SIZE_INV(57), SIZE_INV(58), SIZE_INV(59),
SIZE_INV(60), SIZE_INV(61), SIZE_INV(62), SIZE_INV(63)
#endif
};
unsigned diff, regind, elm, bit;
assert(run->magic == ARENA_RUN_MAGIC);
assert(((sizeof(size_invs)) / sizeof(unsigned)) + 3
>= (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN));
/*
* Avoid doing division with a variable divisor if possible. Using
* actual division here can reduce allocator throughput by over 20%!
*/
diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset);
if ((size & (size - 1)) == 0) {
/*
* log2_table allows fast division of a power of two in the
* [1..128] range.
*
* (x / divisor) becomes (x >> log2_table[divisor - 1]).
*/
static const unsigned char log2_table[] = {
0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7
};
if (size <= 128)
regind = (diff >> log2_table[size - 1]);
else if (size <= 32768)
regind = diff >> (8 + log2_table[(size >> 8) - 1]);
else {
/*
* The run size is too large for us to use the lookup
* table. Use real division.
*/
regind = diff / size;
}
} else if (size <= ((sizeof(size_invs) / sizeof(unsigned))
<< QUANTUM_2POW_MIN) + 2) {
regind = size_invs[(size >> QUANTUM_2POW_MIN) - 3] * diff;
regind >>= SIZE_INV_SHIFT;
} else {
/*
* size_invs isn't large enough to handle this size class, so
* calculate regind using actual division. This only happens
* if the user increases small_max via the 'S' runtime
* configuration option.
*/
regind = diff / size;
};
assert(diff == regind * size);
assert(regind < bin->nregs);
elm = regind >> (SIZEOF_INT_2POW + 3);
if (elm < run->regs_minelm)
run->regs_minelm = elm;
bit = regind - (elm << (SIZEOF_INT_2POW + 3));
assert((run->regs_mask[elm] & (1U << bit)) == 0);
run->regs_mask[elm] |= (1U << bit);
#undef SIZE_INV
#undef SIZE_INV_SHIFT
}
static void
arena_run_split(arena_t *arena, arena_run_t *run, size_t size, bool large,
bool zero)
{
arena_chunk_t *chunk;
size_t old_ndirty, run_ind, total_pages, need_pages, rem_pages, i;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
old_ndirty = chunk->ndirty;
run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
>> pagesize_2pow);
total_pages = (chunk->map[run_ind].bits & ~pagesize_mask) >>
pagesize_2pow;
need_pages = (size >> pagesize_2pow);
assert(need_pages > 0);
assert(need_pages <= total_pages);
rem_pages = total_pages - need_pages;
arena_avail_tree_remove(&arena->runs_avail, &chunk->map[run_ind]);
/* Keep track of trailing unused pages for later use. */
if (rem_pages > 0) {
chunk->map[run_ind+need_pages].bits = (rem_pages <<
pagesize_2pow) | (chunk->map[run_ind+need_pages].bits &
pagesize_mask);
chunk->map[run_ind+total_pages-1].bits = (rem_pages <<
pagesize_2pow) | (chunk->map[run_ind+total_pages-1].bits &
pagesize_mask);
arena_avail_tree_insert(&arena->runs_avail,
&chunk->map[run_ind+need_pages]);
}
for (i = 0; i < need_pages; i++) {
#ifdef MALLOC_DECOMMIT
/*
* Commit decommitted pages if necessary. If a decommitted
* page is encountered, commit all needed adjacent decommitted
* pages in one operation, in order to reduce system call
* overhead.
*/
if (chunk->map[run_ind + i].bits & CHUNK_MAP_DECOMMITTED) {
size_t j;
/*
* Advance i+j to just past the index of the last page
* to commit. Clear CHUNK_MAP_DECOMMITTED along the
* way.
*/
for (j = 0; i + j < need_pages && (chunk->map[run_ind +
i + j].bits & CHUNK_MAP_DECOMMITTED); j++) {
chunk->map[run_ind + i + j].bits ^=
CHUNK_MAP_DECOMMITTED;
}
pages_commit((void *)((uintptr_t)chunk + ((run_ind + i)
<< pagesize_2pow)), (j << pagesize_2pow));
# ifdef MALLOC_STATS
arena->stats.ncommit++;
# endif
} else /* No need to zero since commit zeros. */
#endif
/* Zero if necessary. */
if (zero) {
if ((chunk->map[run_ind + i].bits & CHUNK_MAP_ZEROED)
== 0) {
VALGRIND_MALLOCLIKE_BLOCK((void *)((uintptr_t)
chunk + ((run_ind + i) << pagesize_2pow)),
pagesize, 0, false);
memset((void *)((uintptr_t)chunk + ((run_ind
+ i) << pagesize_2pow)), 0, pagesize);
VALGRIND_FREELIKE_BLOCK((void *)((uintptr_t)
chunk + ((run_ind + i) << pagesize_2pow)),
0);
/* CHUNK_MAP_ZEROED is cleared below. */
}
}
/* Update dirty page accounting. */
if (chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) {
chunk->ndirty--;
arena->ndirty--;
/* CHUNK_MAP_DIRTY is cleared below. */
}
/* Initialize the chunk map. */
if (large) {
chunk->map[run_ind + i].bits = CHUNK_MAP_LARGE
| CHUNK_MAP_ALLOCATED;
} else {
chunk->map[run_ind + i].bits = (size_t)run
| CHUNK_MAP_ALLOCATED;
}
}
/*
* Set the run size only in the first element for large runs. This is
* primarily a debugging aid, since the lack of size info for trailing
* pages only matters if the application tries to operate on an
* interior pointer.
*/
if (large)
chunk->map[run_ind].bits |= size;
if (chunk->ndirty == 0 && old_ndirty > 0)
arena_chunk_tree_dirty_remove(&arena->chunks_dirty, chunk);
}
static void
arena_chunk_init(arena_t *arena, arena_chunk_t *chunk)
{
arena_run_t *run;
size_t i;
VALGRIND_MALLOCLIKE_BLOCK(chunk, (arena_chunk_header_npages <<
pagesize_2pow), 0, false);
#ifdef MALLOC_STATS
arena->stats.mapped += chunksize;
#endif
chunk->arena = arena;
/*
* Claim that no pages are in use, since the header is merely overhead.
*/
chunk->ndirty = 0;
/* Initialize the map to contain one maximal free untouched run. */
run = (arena_run_t *)((uintptr_t)chunk + (arena_chunk_header_npages <<
pagesize_2pow));
for (i = 0; i < arena_chunk_header_npages; i++)
chunk->map[i].bits = 0;
chunk->map[i].bits = arena_maxclass
#ifdef MALLOC_DECOMMIT
| CHUNK_MAP_DECOMMITTED
#endif
| CHUNK_MAP_ZEROED;
for (i++; i < chunk_npages-1; i++) {
chunk->map[i].bits =
#ifdef MALLOC_DECOMMIT
CHUNK_MAP_DECOMMITTED |
#endif
CHUNK_MAP_ZEROED;
}
chunk->map[chunk_npages-1].bits = arena_maxclass
#ifdef MALLOC_DECOMMIT
| CHUNK_MAP_DECOMMITTED
#endif
| CHUNK_MAP_ZEROED;
#ifdef MALLOC_DECOMMIT
/*
* Start out decommitted, in order to force a closer correspondence
* between dirty pages and committed untouched pages.
*/
pages_decommit(run, arena_maxclass);
# ifdef MALLOC_STATS
arena->stats.ndecommit++;
arena->stats.decommitted += (chunk_npages - arena_chunk_header_npages);
# endif
#endif
/* Insert the run into the runs_avail tree. */
arena_avail_tree_insert(&arena->runs_avail,
&chunk->map[arena_chunk_header_npages]);
}
static void
arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk)
{
if (arena->spare != NULL) {
if (arena->spare->ndirty > 0) {
arena_chunk_tree_dirty_remove(
&chunk->arena->chunks_dirty, arena->spare);
arena->ndirty -= arena->spare->ndirty;
}
VALGRIND_FREELIKE_BLOCK(arena->spare, 0);
chunk_dealloc((void *)arena->spare, chunksize);
#ifdef MALLOC_STATS
arena->stats.mapped -= chunksize;
#endif
}
/*
* Remove run from runs_avail, regardless of whether this chunk
* will be cached, so that the arena does not use it. Dirty page
* flushing only uses the chunks_dirty tree, so leaving this chunk in
* the chunks_* trees is sufficient for that purpose.
*/
arena_avail_tree_remove(&arena->runs_avail,
&chunk->map[arena_chunk_header_npages]);
arena->spare = chunk;
}
static arena_run_t *
arena_run_alloc(arena_t *arena, arena_bin_t *bin, size_t size, bool large,
bool zero)
{
arena_chunk_t *chunk;
arena_run_t *run;
arena_chunk_map_t *mapelm, key;
assert(size <= arena_maxclass);
assert((size & pagesize_mask) == 0);
chunk = NULL;
while (true) {
/* Search the arena's chunks for the lowest best fit. */
key.bits = size | CHUNK_MAP_KEY;
mapelm = arena_avail_tree_nsearch(&arena->runs_avail, &key);
if (mapelm != NULL) {
arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm);
size_t pageind = ((uintptr_t)mapelm -
(uintptr_t)run_chunk->map) /
sizeof(arena_chunk_map_t);
if (chunk != NULL)
chunk_dealloc(chunk, chunksize);
run = (arena_run_t *)((uintptr_t)run_chunk + (pageind
<< pagesize_2pow));
arena_run_split(arena, run, size, large, zero);
return (run);
}
if (arena->spare != NULL) {
/* Use the spare. */
chunk = arena->spare;
arena->spare = NULL;
run = (arena_run_t *)((uintptr_t)chunk +
(arena_chunk_header_npages << pagesize_2pow));
/* Insert the run into the runs_avail tree. */
arena_avail_tree_insert(&arena->runs_avail,
&chunk->map[arena_chunk_header_npages]);
arena_run_split(arena, run, size, large, zero);
return (run);
}
/*
* No usable runs. Create a new chunk from which to allocate
* the run.
*/
if (chunk == NULL) {
uint64_t chunk_seq;
/*
* Record the chunk allocation sequence number in order
* to detect races.
*/
arena->chunk_seq++;
chunk_seq = arena->chunk_seq;
/*
* Drop the arena lock while allocating a chunk, since
* reserve notifications may cause recursive
* allocation. Dropping the lock here opens an
* allocataion race, but we recover.
*/
malloc_mutex_unlock(&arena->lock);
chunk = (arena_chunk_t *)chunk_alloc(chunksize, true,
true);
malloc_mutex_lock(&arena->lock);
/*
* Check whether a race allowed a usable run to appear.
*/
if (bin != NULL && (run = bin->runcur) != NULL &&
run->nfree > 0) {
if (chunk != NULL)
chunk_dealloc(chunk, chunksize);
return (run);
}
/*
* If this thread raced with another such that multiple
* chunks were allocated, make sure that there is still
* inadequate space before using this chunk.
*/
if (chunk_seq != arena->chunk_seq)
continue;
/*
* Check for an error *after* checking for a race,
* since a race could also cause a transient OOM
* condition.
*/
if (chunk == NULL)
return (NULL);
}
arena_chunk_init(arena, chunk);
run = (arena_run_t *)((uintptr_t)chunk +
(arena_chunk_header_npages << pagesize_2pow));
/* Update page map. */
arena_run_split(arena, run, size, large, zero);
return (run);
}
}
static void
arena_purge(arena_t *arena)
{
arena_chunk_t *chunk;
size_t i, npages;
#ifdef MALLOC_DEBUG
size_t ndirty = 0;
rb_foreach_begin(arena_chunk_t, link_dirty, &arena->chunks_dirty,
chunk) {
ndirty += chunk->ndirty;
} rb_foreach_end(arena_chunk_t, link_dirty, &arena->chunks_dirty, chunk)
assert(ndirty == arena->ndirty);
#endif
assert(arena->ndirty > opt_dirty_max);
#ifdef MALLOC_STATS
arena->stats.npurge++;
#endif
/*
* Iterate downward through chunks until enough dirty memory has been
* purged. Terminate as soon as possible in order to minimize the
* number of system calls, even if a chunk has only been partially
* purged.
*/
while (arena->ndirty > (opt_dirty_max >> 1)) {
chunk = arena_chunk_tree_dirty_last(&arena->chunks_dirty);
assert(chunk != NULL);
for (i = chunk_npages - 1; chunk->ndirty > 0; i--) {
assert(i >= arena_chunk_header_npages);
if (chunk->map[i].bits & CHUNK_MAP_DIRTY) {
#ifdef MALLOC_DECOMMIT
assert((chunk->map[i].bits &
CHUNK_MAP_DECOMMITTED) == 0);
#endif
chunk->map[i].bits ^=
#ifdef MALLOC_DECOMMIT
CHUNK_MAP_DECOMMITTED |
#endif
CHUNK_MAP_DIRTY;
/* Find adjacent dirty run(s). */
for (npages = 1; i > arena_chunk_header_npages
&& (chunk->map[i - 1].bits &
CHUNK_MAP_DIRTY); npages++) {
i--;
#ifdef MALLOC_DECOMMIT
assert((chunk->map[i].bits &
CHUNK_MAP_DECOMMITTED) == 0);
#endif
chunk->map[i].bits ^=
#ifdef MALLOC_DECOMMIT
CHUNK_MAP_DECOMMITTED |
#endif
CHUNK_MAP_DIRTY;
}
chunk->ndirty -= npages;
arena->ndirty -= npages;
#ifdef MALLOC_DECOMMIT
pages_decommit((void *)((uintptr_t)
chunk + (i << pagesize_2pow)),
(npages << pagesize_2pow));
# ifdef MALLOC_STATS
arena->stats.ndecommit++;
arena->stats.decommitted += npages;
# endif
#else
madvise((void *)((uintptr_t)chunk + (i <<
pagesize_2pow)), (npages << pagesize_2pow),
MADV_FREE);
#endif
#ifdef MALLOC_STATS
arena->stats.nmadvise++;
arena->stats.purged += npages;
#endif
if (arena->ndirty <= (opt_dirty_max >> 1))
break;
}
}
if (chunk->ndirty == 0) {
arena_chunk_tree_dirty_remove(&arena->chunks_dirty,
chunk);
}
}
}
static void
arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty)
{
arena_chunk_t *chunk;
size_t size, run_ind, run_pages;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk)
>> pagesize_2pow);
assert(run_ind >= arena_chunk_header_npages);
assert(run_ind < chunk_npages);
if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0)
size = chunk->map[run_ind].bits & ~pagesize_mask;
else
size = run->bin->run_size;
run_pages = (size >> pagesize_2pow);
/* Mark pages as unallocated in the chunk map. */
if (dirty) {
size_t i;
for (i = 0; i < run_pages; i++) {
assert((chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY)
== 0);
chunk->map[run_ind + i].bits = CHUNK_MAP_DIRTY;
}
if (chunk->ndirty == 0) {
arena_chunk_tree_dirty_insert(&arena->chunks_dirty,
chunk);
}
chunk->ndirty += run_pages;
arena->ndirty += run_pages;
} else {
size_t i;
for (i = 0; i < run_pages; i++) {
chunk->map[run_ind + i].bits &= ~(CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED);
}
}
chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits &
pagesize_mask);
chunk->map[run_ind+run_pages-1].bits = size |
(chunk->map[run_ind+run_pages-1].bits & pagesize_mask);
/* Try to coalesce forward. */
if (run_ind + run_pages < chunk_npages &&
(chunk->map[run_ind+run_pages].bits & CHUNK_MAP_ALLOCATED) == 0) {
size_t nrun_size = chunk->map[run_ind+run_pages].bits &
~pagesize_mask;
/*
* Remove successor from runs_avail; the coalesced run is
* inserted later.
*/
arena_avail_tree_remove(&arena->runs_avail,
&chunk->map[run_ind+run_pages]);
size += nrun_size;
run_pages = size >> pagesize_2pow;
assert((chunk->map[run_ind+run_pages-1].bits & ~pagesize_mask)
== nrun_size);
chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits &
pagesize_mask);
chunk->map[run_ind+run_pages-1].bits = size |
(chunk->map[run_ind+run_pages-1].bits & pagesize_mask);
}
/* Try to coalesce backward. */
if (run_ind > arena_chunk_header_npages && (chunk->map[run_ind-1].bits &
CHUNK_MAP_ALLOCATED) == 0) {
size_t prun_size = chunk->map[run_ind-1].bits & ~pagesize_mask;
run_ind -= prun_size >> pagesize_2pow;
/*
* Remove predecessor from runs_avail; the coalesced run is
* inserted later.
*/
arena_avail_tree_remove(&arena->runs_avail,
&chunk->map[run_ind]);
size += prun_size;
run_pages = size >> pagesize_2pow;
assert((chunk->map[run_ind].bits & ~pagesize_mask) ==
prun_size);
chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits &
pagesize_mask);
chunk->map[run_ind+run_pages-1].bits = size |
(chunk->map[run_ind+run_pages-1].bits & pagesize_mask);
}
/* Insert into runs_avail, now that coalescing is complete. */
arena_avail_tree_insert(&arena->runs_avail, &chunk->map[run_ind]);
/* Deallocate chunk if it is now completely unused. */
if ((chunk->map[arena_chunk_header_npages].bits & (~pagesize_mask |
CHUNK_MAP_ALLOCATED)) == arena_maxclass)
arena_chunk_dealloc(arena, chunk);
/* Enforce opt_dirty_max. */
if (arena->ndirty > opt_dirty_max)
arena_purge(arena);
}
static void
arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run,
size_t oldsize, size_t newsize)
{
size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> pagesize_2pow;
size_t head_npages = (oldsize - newsize) >> pagesize_2pow;
assert(oldsize > newsize);
/*
* Update the chunk map so that arena_run_dalloc() can treat the
* leading run as separately allocated.
*/
chunk->map[pageind].bits = (oldsize - newsize) | CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED;
chunk->map[pageind+head_npages].bits = newsize | CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED;
arena_run_dalloc(arena, run, false);
}
static void
arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run,
size_t oldsize, size_t newsize, bool dirty)
{
size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> pagesize_2pow;
size_t npages = newsize >> pagesize_2pow;
assert(oldsize > newsize);
/*
* Update the chunk map so that arena_run_dalloc() can treat the
* trailing run as separately allocated.
*/
chunk->map[pageind].bits = newsize | CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED;
chunk->map[pageind+npages].bits = (oldsize - newsize) | CHUNK_MAP_LARGE
| CHUNK_MAP_ALLOCATED;
arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)run + newsize),
dirty);
}
static arena_run_t *
arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin)
{
arena_chunk_map_t *mapelm;
arena_run_t *run;
unsigned i, remainder;
/* Look for a usable run. */
mapelm = arena_run_tree_first(&bin->runs);
if (mapelm != NULL) {
/* run is guaranteed to have available space. */
arena_run_tree_remove(&bin->runs, mapelm);
run = (arena_run_t *)(mapelm->bits & ~pagesize_mask);
#ifdef MALLOC_STATS
bin->stats.reruns++;
#endif
return (run);
}
/* No existing runs have any space available. */
/* Allocate a new run. */
run = arena_run_alloc(arena, bin, bin->run_size, false, false);
if (run == NULL)
return (NULL);
/*
* Don't initialize if a race in arena_run_alloc() allowed an existing
* run to become usable.
*/
if (run == bin->runcur)
return (run);
VALGRIND_MALLOCLIKE_BLOCK(run, sizeof(arena_run_t) + (sizeof(unsigned) *
(bin->regs_mask_nelms - 1)), 0, false);
/* Initialize run internals. */
run->bin = bin;
for (i = 0; i < bin->regs_mask_nelms - 1; i++)
run->regs_mask[i] = UINT_MAX;
remainder = bin->nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1);
if (remainder == 0)
run->regs_mask[i] = UINT_MAX;
else {
/* The last element has spare bits that need to be unset. */
run->regs_mask[i] = (UINT_MAX >> ((1U << (SIZEOF_INT_2POW + 3))
- remainder));
}
run->regs_minelm = 0;
run->nfree = bin->nregs;
#ifdef MALLOC_DEBUG
run->magic = ARENA_RUN_MAGIC;
#endif
#ifdef MALLOC_STATS
bin->stats.nruns++;
bin->stats.curruns++;
if (bin->stats.curruns > bin->stats.highruns)
bin->stats.highruns = bin->stats.curruns;
#endif
return (run);
}
/* bin->runcur must have space available before this function is called. */
static inline void *
arena_bin_malloc_easy(arena_t *arena, arena_bin_t *bin, arena_run_t *run)
{
void *ret;
assert(run->magic == ARENA_RUN_MAGIC);
assert(run->nfree > 0);
ret = arena_run_reg_alloc(run, bin);
assert(ret != NULL);
run->nfree--;
return (ret);
}
/* Re-fill bin->runcur, then call arena_bin_malloc_easy(). */
static void *
arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin)
{
bin->runcur = arena_bin_nonfull_run_get(arena, bin);
if (bin->runcur == NULL)
return (NULL);
assert(bin->runcur->magic == ARENA_RUN_MAGIC);
assert(bin->runcur->nfree > 0);
return (arena_bin_malloc_easy(arena, bin, bin->runcur));
}
/*
* Calculate bin->run_size such that it meets the following constraints:
*
* *) bin->run_size >= min_run_size
* *) bin->run_size <= arena_maxclass
* *) bin->run_size <= RUN_MAX_SMALL
* *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed).
*
* bin->nregs, bin->regs_mask_nelms, and bin->reg0_offset are
* also calculated here, since these settings are all interdependent.
*/
static size_t
arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size)
{
size_t try_run_size, good_run_size;
unsigned good_nregs, good_mask_nelms, good_reg0_offset;
unsigned try_nregs, try_mask_nelms, try_reg0_offset;
assert(min_run_size >= pagesize);
assert(min_run_size <= arena_maxclass);
assert(min_run_size <= RUN_MAX_SMALL);
/*
* Calculate known-valid settings before entering the run_size
* expansion loop, so that the first part of the loop always copies
* valid settings.
*
* The do..while loop iteratively reduces the number of regions until
* the run header and the regions no longer overlap. A closed formula
* would be quite messy, since there is an interdependency between the
* header's mask length and the number of regions.
*/
try_run_size = min_run_size;
try_nregs = ((try_run_size - sizeof(arena_run_t)) / bin->reg_size)
+ 1; /* Counter-act try_nregs-- in loop. */
do {
try_nregs--;
try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
((try_nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1)) ? 1 : 0);
try_reg0_offset = try_run_size - (try_nregs * bin->reg_size);
} while (sizeof(arena_run_t) + (sizeof(unsigned) * (try_mask_nelms - 1))
> try_reg0_offset);
/* run_size expansion loop. */
do {
/*
* Copy valid settings before trying more aggressive settings.
*/
good_run_size = try_run_size;
good_nregs = try_nregs;
good_mask_nelms = try_mask_nelms;
good_reg0_offset = try_reg0_offset;
/* Try more aggressive settings. */
try_run_size += pagesize;
try_nregs = ((try_run_size - sizeof(arena_run_t)) /
bin->reg_size) + 1; /* Counter-act try_nregs-- in loop. */
do {
try_nregs--;
try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
((try_nregs & ((1U << (SIZEOF_INT_2POW + 3)) - 1)) ?
1 : 0);
try_reg0_offset = try_run_size - (try_nregs *
bin->reg_size);
} while (sizeof(arena_run_t) + (sizeof(unsigned) *
(try_mask_nelms - 1)) > try_reg0_offset);
} while (try_run_size <= arena_maxclass && try_run_size <= RUN_MAX_SMALL
&& RUN_MAX_OVRHD * (bin->reg_size << 3) > RUN_MAX_OVRHD_RELAX
&& (try_reg0_offset << RUN_BFP) > RUN_MAX_OVRHD * try_run_size);
assert(sizeof(arena_run_t) + (sizeof(unsigned) * (good_mask_nelms - 1))
<= good_reg0_offset);
assert((good_mask_nelms << (SIZEOF_INT_2POW + 3)) >= good_nregs);
/* Copy final settings. */
bin->run_size = good_run_size;
bin->nregs = good_nregs;
bin->regs_mask_nelms = good_mask_nelms;
bin->reg0_offset = good_reg0_offset;
return (good_run_size);
}
#ifdef MALLOC_BALANCE
static inline void
arena_lock_balance(arena_t *arena)
{
unsigned contention;
contention = malloc_spin_lock(&arena->lock);
if (narenas > 1) {
/*
* Calculate the exponentially averaged contention for this
* arena. Due to integer math always rounding down, this value
* decays somewhat faster then normal.
*/
arena->contention = (((uint64_t)arena->contention
* (uint64_t)((1U << BALANCE_ALPHA_INV_2POW)-1))
+ (uint64_t)contention) >> BALANCE_ALPHA_INV_2POW;
if (arena->contention >= opt_balance_threshold)
arena_lock_balance_hard(arena);
}
}
static void
arena_lock_balance_hard(arena_t *arena)
{
uint32_t ind;
arena->contention = 0;
#ifdef MALLOC_STATS
arena->stats.nbalance++;
#endif
ind = PRN(balance, narenas_2pow);
if (arenas[ind] != NULL) {
#ifdef MOZ_MEMORY_WINDOWS
TlsSetValue(tlsIndex, arenas[ind]);
#else
arenas_map = arenas[ind];
#endif
} else {
malloc_spin_lock(&arenas_lock);
if (arenas[ind] != NULL) {
#ifdef MOZ_MEMORY_WINDOWS
TlsSetValue(tlsIndex, arenas[ind]);
#else
arenas_map = arenas[ind];
#endif
} else {
#ifdef MOZ_MEMORY_WINDOWS
TlsSetValue(tlsIndex, arenas_extend(ind));
#else
arenas_map = arenas_extend(ind);
#endif
}
malloc_spin_unlock(&arenas_lock);
}
}
#endif
static inline void *
arena_malloc_small(arena_t *arena, size_t size, bool zero)
{
void *ret;
arena_bin_t *bin;
arena_run_t *run;
if (size < small_min) {
/* Tiny. */
size = pow2_ceil(size);
bin = &arena->bins[ffs((int)(size >> (TINY_MIN_2POW +
1)))];
#if (!defined(NDEBUG) || defined(MALLOC_STATS))
/*
* Bin calculation is always correct, but we may need
* to fix size for the purposes of assertions and/or
* stats accuracy.
*/
if (size < (1U << TINY_MIN_2POW))
size = (1U << TINY_MIN_2POW);
#endif
} else if (size <= small_max) {
/* Quantum-spaced. */
size = QUANTUM_CEILING(size);
bin = &arena->bins[ntbins + (size >> opt_quantum_2pow)
- 1];
} else {
/* Sub-page. */
size = pow2_ceil(size);
bin = &arena->bins[ntbins + nqbins
+ (ffs((int)(size >> opt_small_max_2pow)) - 2)];
}
assert(size == bin->reg_size);
#ifdef MALLOC_BALANCE
arena_lock_balance(arena);
#else
malloc_spin_lock(&arena->lock);
#endif
if ((run = bin->runcur) != NULL && run->nfree > 0)
ret = arena_bin_malloc_easy(arena, bin, run);
else
ret = arena_bin_malloc_hard(arena, bin);
if (ret == NULL) {
malloc_spin_unlock(&arena->lock);
return (NULL);
}
#ifdef MALLOC_STATS
bin->stats.nrequests++;
arena->stats.nmalloc_small++;
arena->stats.allocated_small += size;
#endif
malloc_spin_unlock(&arena->lock);
VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, zero);
if (zero == false) {
#ifdef MALLOC_FILL
if (opt_junk)
memset(ret, 0xa5, size);
else if (opt_zero)
memset(ret, 0, size);
#endif
} else
memset(ret, 0, size);
return (ret);
}
static void *
arena_malloc_large(arena_t *arena, size_t size, bool zero)
{
void *ret;
/* Large allocation. */
size = PAGE_CEILING(size);
#ifdef MALLOC_BALANCE
arena_lock_balance(arena);
#else
malloc_spin_lock(&arena->lock);
#endif
ret = (void *)arena_run_alloc(arena, NULL, size, true, zero);
if (ret == NULL) {
malloc_spin_unlock(&arena->lock);
return (NULL);
}
#ifdef MALLOC_STATS
arena->stats.nmalloc_large++;
arena->stats.allocated_large += size;
#endif
malloc_spin_unlock(&arena->lock);
VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, zero);
if (zero == false) {
#ifdef MALLOC_FILL
if (opt_junk)
memset(ret, 0xa5, size);
else if (opt_zero)
memset(ret, 0, size);
#endif
}
return (ret);
}
static inline void *
arena_malloc(arena_t *arena, size_t size, bool zero)
{
assert(arena != NULL);
assert(arena->magic == ARENA_MAGIC);
assert(size != 0);
assert(QUANTUM_CEILING(size) <= arena_maxclass);
if (size <= bin_maxclass) {
return (arena_malloc_small(arena, size, zero));
} else
return (arena_malloc_large(arena, size, zero));
}
static inline void *
imalloc(size_t size)
{
assert(size != 0);
if (size <= arena_maxclass)
return (arena_malloc(choose_arena(), size, false));
else
return (huge_malloc(size, false));
}
static inline void *
icalloc(size_t size)
{
if (size <= arena_maxclass)
return (arena_malloc(choose_arena(), size, true));
else
return (huge_malloc(size, true));
}
/* Only handles large allocations that require more than page alignment. */
static void *
arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size)
{
void *ret;
size_t offset;
arena_chunk_t *chunk;
assert((size & pagesize_mask) == 0);
assert((alignment & pagesize_mask) == 0);
#ifdef MALLOC_BALANCE
arena_lock_balance(arena);
#else
malloc_spin_lock(&arena->lock);
#endif
ret = (void *)arena_run_alloc(arena, NULL, alloc_size, true, false);
if (ret == NULL) {
malloc_spin_unlock(&arena->lock);
return (NULL);
}
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
offset = (uintptr_t)ret & (alignment - 1);
assert((offset & pagesize_mask) == 0);
assert(offset < alloc_size);
if (offset == 0)
arena_run_trim_tail(arena, chunk, ret, alloc_size, size, false);
else {
size_t leadsize, trailsize;
leadsize = alignment - offset;
if (leadsize > 0) {
arena_run_trim_head(arena, chunk, ret, alloc_size,
alloc_size - leadsize);
ret = (void *)((uintptr_t)ret + leadsize);
}
trailsize = alloc_size - leadsize - size;
if (trailsize != 0) {
/* Trim trailing space. */
assert(trailsize < alloc_size);
arena_run_trim_tail(arena, chunk, ret, size + trailsize,
size, false);
}
}
#ifdef MALLOC_STATS
arena->stats.nmalloc_large++;
arena->stats.allocated_large += size;
#endif
malloc_spin_unlock(&arena->lock);
VALGRIND_MALLOCLIKE_BLOCK(ret, size, 0, false);
#ifdef MALLOC_FILL
if (opt_junk)
memset(ret, 0xa5, size);
else if (opt_zero)
memset(ret, 0, size);
#endif
return (ret);
}
static inline void *
ipalloc(size_t alignment, size_t size)
{
void *ret;
size_t ceil_size;
/*
* Round size up to the nearest multiple of alignment.
*
* This done, we can take advantage of the fact that for each small
* size class, every object is aligned at the smallest power of two
* that is non-zero in the base two representation of the size. For
* example:
*
* Size | Base 2 | Minimum alignment
* -----+----------+------------------
* 96 | 1100000 | 32
* 144 | 10100000 | 32
* 192 | 11000000 | 64
*
* Depending on runtime settings, it is possible that arena_malloc()
* will further round up to a power of two, but that never causes
* correctness issues.
*/
ceil_size = (size + (alignment - 1)) & (-alignment);
/*
* (ceil_size < size) protects against the combination of maximal
* alignment and size greater than maximal alignment.
*/
if (ceil_size < size) {
/* size_t overflow. */
return (NULL);
}
if (ceil_size <= pagesize || (alignment <= pagesize
&& ceil_size <= arena_maxclass))
ret = arena_malloc(choose_arena(), ceil_size, false);
else {
size_t run_size;
/*
* We can't achieve sub-page alignment, so round up alignment
* permanently; it makes later calculations simpler.
*/
alignment = PAGE_CEILING(alignment);
ceil_size = PAGE_CEILING(size);
/*
* (ceil_size < size) protects against very large sizes within
* pagesize of SIZE_T_MAX.
*
* (ceil_size + alignment < ceil_size) protects against the
* combination of maximal alignment and ceil_size large enough
* to cause overflow. This is similar to the first overflow
* check above, but it needs to be repeated due to the new
* ceil_size value, which may now be *equal* to maximal
* alignment, whereas before we only detected overflow if the
* original size was *greater* than maximal alignment.
*/
if (ceil_size < size || ceil_size + alignment < ceil_size) {
/* size_t overflow. */
return (NULL);
}
/*
* Calculate the size of the over-size run that arena_palloc()
* would need to allocate in order to guarantee the alignment.
*/
if (ceil_size >= alignment)
run_size = ceil_size + alignment - pagesize;
else {
/*
* It is possible that (alignment << 1) will cause
* overflow, but it doesn't matter because we also
* subtract pagesize, which in the case of overflow
* leaves us with a very large run_size. That causes
* the first conditional below to fail, which means
* that the bogus run_size value never gets used for
* anything important.
*/
run_size = (alignment << 1) - pagesize;
}
if (run_size <= arena_maxclass) {
ret = arena_palloc(choose_arena(), alignment, ceil_size,
run_size);
} else if (alignment <= chunksize)
ret = huge_malloc(ceil_size, false);
else
ret = huge_palloc(alignment, ceil_size);
}
assert(((uintptr_t)ret & (alignment - 1)) == 0);
return (ret);
}
/* Return the size of the allocation pointed to by ptr. */
static size_t
arena_salloc(const void *ptr)
{
size_t ret;
arena_chunk_t *chunk;
size_t pageind, mapbits;
assert(ptr != NULL);
assert(CHUNK_ADDR2BASE(ptr) != ptr);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow);
mapbits = chunk->map[pageind].bits;
assert((mapbits & CHUNK_MAP_ALLOCATED) != 0);
if ((mapbits & CHUNK_MAP_LARGE) == 0) {
arena_run_t *run = (arena_run_t *)(mapbits & ~pagesize_mask);
assert(run->magic == ARENA_RUN_MAGIC);
ret = run->bin->reg_size;
} else {
ret = mapbits & ~pagesize_mask;
assert(ret != 0);
}
return (ret);
}
#if (defined(MALLOC_VALIDATE) || defined(MOZ_MEMORY_DARWIN))
/*
* Validate ptr before assuming that it points to an allocation. Currently,
* the following validation is performed:
*
* + Check that ptr is not NULL.
*
* + Check that ptr lies within a mapped chunk.
*/
static inline size_t
isalloc_validate(const void *ptr)
{
arena_chunk_t *chunk;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
if (chunk == NULL)
return (0);
if (malloc_rtree_get(chunk_rtree, (uintptr_t)chunk) == NULL)
return (0);
if (chunk != ptr) {
assert(chunk->arena->magic == ARENA_MAGIC);
return (arena_salloc(ptr));
} else {
size_t ret;
extent_node_t *node;
extent_node_t key;
/* Chunk. */
key.addr = (void *)chunk;
malloc_mutex_lock(&huge_mtx);
node = extent_tree_ad_search(&huge, &key);
if (node != NULL)
ret = node->size;
else
ret = 0;
malloc_mutex_unlock(&huge_mtx);
return (ret);
}
}
#endif
static inline size_t
isalloc(const void *ptr)
{
size_t ret;
arena_chunk_t *chunk;
assert(ptr != NULL);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
if (chunk != ptr) {
/* Region. */
assert(chunk->arena->magic == ARENA_MAGIC);
ret = arena_salloc(ptr);
} else {
extent_node_t *node, key;
/* Chunk (huge allocation). */
malloc_mutex_lock(&huge_mtx);
/* Extract from tree of huge allocations. */
key.addr = __DECONST(void *, ptr);
node = extent_tree_ad_search(&huge, &key);
assert(node != NULL);
ret = node->size;
malloc_mutex_unlock(&huge_mtx);
}
return (ret);
}
static inline void
arena_dalloc_small(arena_t *arena, arena_chunk_t *chunk, void *ptr,
arena_chunk_map_t *mapelm)
{
arena_run_t *run;
arena_bin_t *bin;
size_t size;
run = (arena_run_t *)(mapelm->bits & ~pagesize_mask);
assert(run->magic == ARENA_RUN_MAGIC);
bin = run->bin;
size = bin->reg_size;
#ifdef MALLOC_FILL
if (opt_junk)
memset(ptr, 0x5a, size);
#endif
arena_run_reg_dalloc(run, bin, ptr, size);
run->nfree++;
if (run->nfree == bin->nregs) {
/* Deallocate run. */
if (run == bin->runcur)
bin->runcur = NULL;
else if (bin->nregs != 1) {
size_t run_pageind = (((uintptr_t)run -
(uintptr_t)chunk)) >> pagesize_2pow;
arena_chunk_map_t *run_mapelm =
&chunk->map[run_pageind];
/*
* This block's conditional is necessary because if the
* run only contains one region, then it never gets
* inserted into the non-full runs tree.
*/
assert(arena_run_tree_search(&bin->runs, run_mapelm) ==
run_mapelm);
arena_run_tree_remove(&bin->runs, run_mapelm);
}
#ifdef MALLOC_DEBUG
run->magic = 0;
#endif
VALGRIND_FREELIKE_BLOCK(run, 0);
arena_run_dalloc(arena, run, true);
#ifdef MALLOC_STATS
bin->stats.curruns--;
#endif
} else if (run->nfree == 1 && run != bin->runcur) {
/*
* Make sure that bin->runcur always refers to the lowest
* non-full run, if one exists.
*/
if (bin->runcur == NULL)
bin->runcur = run;
else if ((uintptr_t)run < (uintptr_t)bin->runcur) {
/* Switch runcur. */
if (bin->runcur->nfree > 0) {
arena_chunk_t *runcur_chunk =
CHUNK_ADDR2BASE(bin->runcur);
size_t runcur_pageind =
(((uintptr_t)bin->runcur -
(uintptr_t)runcur_chunk)) >> pagesize_2pow;
arena_chunk_map_t *runcur_mapelm =
&runcur_chunk->map[runcur_pageind];
/* Insert runcur. */
assert(arena_run_tree_search(&bin->runs,
runcur_mapelm) == NULL);
arena_run_tree_insert(&bin->runs,
runcur_mapelm);
}
bin->runcur = run;
} else {
size_t run_pageind = (((uintptr_t)run -
(uintptr_t)chunk)) >> pagesize_2pow;
arena_chunk_map_t *run_mapelm =
&chunk->map[run_pageind];
assert(arena_run_tree_search(&bin->runs, run_mapelm) ==
NULL);
arena_run_tree_insert(&bin->runs, run_mapelm);
}
}
#ifdef MALLOC_STATS
arena->stats.allocated_small -= size;
arena->stats.ndalloc_small++;
#endif
}
static void
arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr)
{
/* Large allocation. */
malloc_spin_lock(&arena->lock);
#ifdef MALLOC_FILL
#ifndef MALLOC_STATS
if (opt_junk)
#endif
#endif
{
size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >>
pagesize_2pow;
size_t size = chunk->map[pageind].bits & ~pagesize_mask;
#ifdef MALLOC_FILL
#ifdef MALLOC_STATS
if (opt_junk)
#endif
memset(ptr, 0x5a, size);
#endif
#ifdef MALLOC_STATS
arena->stats.allocated_large -= size;
#endif
}
#ifdef MALLOC_STATS
arena->stats.ndalloc_large++;
#endif
arena_run_dalloc(arena, (arena_run_t *)ptr, true);
malloc_spin_unlock(&arena->lock);
}
static inline void
arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr)
{
size_t pageind;
arena_chunk_map_t *mapelm;
assert(arena != NULL);
assert(arena->magic == ARENA_MAGIC);
assert(chunk->arena == arena);
assert(ptr != NULL);
assert(CHUNK_ADDR2BASE(ptr) != ptr);
pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow);
mapelm = &chunk->map[pageind];
assert((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0);
if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) {
/* Small allocation. */
malloc_spin_lock(&arena->lock);
arena_dalloc_small(arena, chunk, ptr, mapelm);
malloc_spin_unlock(&arena->lock);
} else
arena_dalloc_large(arena, chunk, ptr);
VALGRIND_FREELIKE_BLOCK(ptr, 0);
}
static inline void
idalloc(void *ptr)
{
arena_chunk_t *chunk;
assert(ptr != NULL);
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
if (chunk != ptr)
arena_dalloc(chunk->arena, chunk, ptr);
else
huge_dalloc(ptr);
}
static void
arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, void *ptr,
size_t size, size_t oldsize)
{
assert(size < oldsize);
/*
* Shrink the run, and make trailing pages available for other
* allocations.
*/
#ifdef MALLOC_BALANCE
arena_lock_balance(arena);
#else
malloc_spin_lock(&arena->lock);
#endif
arena_run_trim_tail(arena, chunk, (arena_run_t *)ptr, oldsize, size,
true);
#ifdef MALLOC_STATS
arena->stats.allocated_large -= oldsize - size;
#endif
malloc_spin_unlock(&arena->lock);
}
static bool
arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, void *ptr,
size_t size, size_t oldsize)
{
size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> pagesize_2pow;
size_t npages = oldsize >> pagesize_2pow;
assert(oldsize == (chunk->map[pageind].bits & ~pagesize_mask));
/* Try to extend the run. */
assert(size > oldsize);
#ifdef MALLOC_BALANCE
arena_lock_balance(arena);
#else
malloc_spin_lock(&arena->lock);
#endif
if (pageind + npages < chunk_npages && (chunk->map[pageind+npages].bits
& CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[pageind+npages].bits &
~pagesize_mask) >= size - oldsize) {
/*
* The next run is available and sufficiently large. Split the
* following run, then merge the first part with the existing
* allocation.
*/
arena_run_split(arena, (arena_run_t *)((uintptr_t)chunk +
((pageind+npages) << pagesize_2pow)), size - oldsize, true,
false);
chunk->map[pageind].bits = size | CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED;
chunk->map[pageind+npages].bits = CHUNK_MAP_LARGE |
CHUNK_MAP_ALLOCATED;
#ifdef MALLOC_STATS
arena->stats.allocated_large += size - oldsize;
#endif
malloc_spin_unlock(&arena->lock);
return (false);
}
malloc_spin_unlock(&arena->lock);
return (true);
}
/*
* Try to resize a large allocation, in order to avoid copying. This will
* always fail if growing an object, and the following run is already in use.
*/
static bool
arena_ralloc_large(void *ptr, size_t size, size_t oldsize)
{
size_t psize;
psize = PAGE_CEILING(size);
if (psize == oldsize) {
/* Same size class. */
#ifdef MALLOC_FILL
if (opt_junk && size < oldsize) {
memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize -
size);
}
#endif
return (false);
} else {
arena_chunk_t *chunk;
arena_t *arena;
chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
arena = chunk->arena;
assert(arena->magic == ARENA_MAGIC);
if (psize < oldsize) {
#ifdef MALLOC_FILL
/* Fill before shrinking in order avoid a race. */
if (opt_junk) {
memset((void *)((uintptr_t)ptr + size), 0x5a,
oldsize - size);
}
#endif
arena_ralloc_large_shrink(arena, chunk, ptr, psize,
oldsize);
return (false);
} else {
bool ret = arena_ralloc_large_grow(arena, chunk, ptr,
psize, oldsize);
#ifdef MALLOC_FILL
if (ret == false && opt_zero) {
memset((void *)((uintptr_t)ptr + oldsize), 0,
size - oldsize);
}
#endif
return (ret);
}
}
}
static void *
arena_ralloc(void *ptr, size_t size, size_t oldsize)
{
void *ret;
size_t copysize;
/* Try to avoid moving the allocation. */
if (size < small_min) {
if (oldsize < small_min &&
ffs((int)(pow2_ceil(size) >> (TINY_MIN_2POW + 1)))
== ffs((int)(pow2_ceil(oldsize) >> (TINY_MIN_2POW + 1))))
goto IN_PLACE; /* Same size class. */
} else if (size <= small_max) {
if (oldsize >= small_min && oldsize <= small_max &&
(QUANTUM_CEILING(size) >> opt_quantum_2pow)
== (QUANTUM_CEILING(oldsize) >> opt_quantum_2pow))
goto IN_PLACE; /* Same size class. */
} else if (size <= bin_maxclass) {
if (oldsize > small_max && oldsize <= bin_maxclass &&
pow2_ceil(size) == pow2_ceil(oldsize))
goto IN_PLACE; /* Same size class. */
} else if (oldsize > bin_maxclass && oldsize <= arena_maxclass) {
assert(size > bin_maxclass);
if (arena_ralloc_large(ptr, size, oldsize) == false)
return (ptr);
}
/*
* If we get here, then size and oldsize are different enough that we
* need to move the object. In that case, fall back to allocating new
* space and copying.
*/
ret = arena_malloc(choose_arena(), size, false);
if (ret == NULL)
return (NULL);
/* Junk/zero-filling were already done by arena_malloc(). */
copysize = (size < oldsize) ? size : oldsize;
#ifdef VM_COPY_MIN
if (copysize >= VM_COPY_MIN)
pages_copy(ret, ptr, copysize);
else
#endif
memcpy(ret, ptr, copysize);
idalloc(ptr);
return (ret);
IN_PLACE:
#ifdef MALLOC_FILL
if (opt_junk && size < oldsize)
memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size);
else if (opt_zero && size > oldsize)
memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize);
#endif
return (ptr);
}
static inline void *
iralloc(void *ptr, size_t size)
{
size_t oldsize;
assert(ptr != NULL);
assert(size != 0);
oldsize = isalloc(ptr);
#ifndef MALLOC_VALGRIND
if (size <= arena_maxclass)
return (arena_ralloc(ptr, size, oldsize));
else
return (huge_ralloc(ptr, size, oldsize));
#else
/*
* Valgrind does not provide a public interface for modifying an
* existing allocation, so use malloc/memcpy/free instead.
*/
{
void *ret = imalloc(size);
if (ret != NULL) {
if (oldsize < size)
memcpy(ret, ptr, oldsize);
else
memcpy(ret, ptr, size);
idalloc(ptr);
}
return (ret);
}
#endif
}
static bool
arena_new(arena_t *arena)
{
unsigned i;
arena_bin_t *bin;
size_t pow2_size, prev_run_size;
if (malloc_spin_init(&arena->lock))
return (true);
#ifdef MALLOC_STATS
memset(&arena->stats, 0, sizeof(arena_stats_t));
#endif
arena->chunk_seq = 0;
/* Initialize chunks. */
arena_chunk_tree_dirty_new(&arena->chunks_dirty);
arena->spare = NULL;
arena->ndirty = 0;
arena_avail_tree_new(&arena->runs_avail);
#ifdef MALLOC_BALANCE
arena->contention = 0;
#endif
/* Initialize bins. */
prev_run_size = pagesize;
/* (2^n)-spaced tiny bins. */
for (i = 0; i < ntbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
arena_run_tree_new(&bin->runs);
bin->reg_size = (1U << (TINY_MIN_2POW + i));
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
/* Quantum-spaced bins. */
for (; i < ntbins + nqbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
arena_run_tree_new(&bin->runs);
bin->reg_size = quantum * (i - ntbins + 1);
pow2_size = pow2_ceil(quantum * (i - ntbins + 1));
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
/* (2^n)-spaced sub-page bins. */
for (; i < ntbins + nqbins + nsbins; i++) {
bin = &arena->bins[i];
bin->runcur = NULL;
arena_run_tree_new(&bin->runs);
bin->reg_size = (small_max << (i - (ntbins + nqbins) + 1));
prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
#ifdef MALLOC_STATS
memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
#endif
}
#ifdef MALLOC_DEBUG
arena->magic = ARENA_MAGIC;
#endif
return (false);
}
/* Create a new arena and insert it into the arenas array at index ind. */
static arena_t *
arenas_extend(unsigned ind)
{
arena_t *ret;
/* Allocate enough space for trailing bins. */
ret = (arena_t *)base_alloc(sizeof(arena_t)
+ (sizeof(arena_bin_t) * (ntbins + nqbins + nsbins - 1)));
if (ret != NULL && arena_new(ret) == false) {
arenas[ind] = ret;
return (ret);
}
/* Only reached if there is an OOM error. */
/*
* OOM here is quite inconvenient to propagate, since dealing with it
* would require a check for failure in the fast path. Instead, punt
* by using arenas[0]. In practice, this is an extremely unlikely
* failure.
*/
_malloc_message(_getprogname(),
": (malloc) Error initializing arena\n", "", "");
if (opt_abort)
abort();
return (arenas[0]);
}
/*
* End arena.
*/
/******************************************************************************/
/*
* Begin general internal functions.
*/
static void *
huge_malloc(size_t size, bool zero)
{
void *ret;
size_t csize;
#ifdef MALLOC_DECOMMIT
size_t psize;
#endif
extent_node_t *node;
/* Allocate one or more contiguous chunks for this request. */
csize = CHUNK_CEILING(size);
if (csize == 0) {
/* size is large enough to cause size_t wrap-around. */
return (NULL);
}
/* Allocate an extent node with which to track the chunk. */
node = base_node_alloc();
if (node == NULL)
return (NULL);
ret = chunk_alloc(csize, zero, true);
if (ret == NULL) {
base_node_dealloc(node);
return (NULL);
}
/* Insert node into huge. */
node->addr = ret;
#ifdef MALLOC_DECOMMIT
psize = PAGE_CEILING(size);
node->size = psize;
#else
node->size = csize;
#endif
malloc_mutex_lock(&huge_mtx);
extent_tree_ad_insert(&huge, node);
#ifdef MALLOC_STATS
huge_nmalloc++;
# ifdef MALLOC_DECOMMIT
huge_allocated += psize;
# else
huge_allocated += csize;
# endif
#endif
malloc_mutex_unlock(&huge_mtx);
#ifdef MALLOC_DECOMMIT
if (csize - psize > 0)
pages_decommit((void *)((uintptr_t)ret + psize), csize - psize);
#endif
#ifdef MALLOC_DECOMMIT
VALGRIND_MALLOCLIKE_BLOCK(ret, psize, 0, zero);
#else
VALGRIND_MALLOCLIKE_BLOCK(ret, csize, 0, zero);
#endif
#ifdef MALLOC_FILL
if (zero == false) {
if (opt_junk)
# ifdef MALLOC_DECOMMIT
memset(ret, 0xa5, psize);
# else
memset(ret, 0xa5, csize);
# endif
else if (opt_zero)
# ifdef MALLOC_DECOMMIT
memset(ret, 0, psize);
# else
memset(ret, 0, csize);
# endif
}
#endif
return (ret);
}
/* Only handles large allocations that require more than chunk alignment. */
static void *
huge_palloc(size_t alignment, size_t size)
{
void *ret;
size_t alloc_size, chunk_size, offset;
#ifdef MALLOC_DECOMMIT
size_t psize;
#endif
extent_node_t *node;
int pfd;
/*
* This allocation requires alignment that is even larger than chunk
* alignment. This means that huge_malloc() isn't good enough.
*
* Allocate almost twice as many chunks as are demanded by the size or
* alignment, in order to assure the alignment can be achieved, then
* unmap leading and trailing chunks.
*/
assert(alignment >= chunksize);
chunk_size = CHUNK_CEILING(size);
if (size >= alignment)
alloc_size = chunk_size + alignment - chunksize;
else
alloc_size = (alignment << 1) - chunksize;
/* Allocate an extent node with which to track the chunk. */
node = base_node_alloc();
if (node == NULL)
return (NULL);
/*
* Windows requires that there be a 1:1 mapping between VM
* allocation/deallocation operations. Therefore, take care here to
* acquire the final result via one mapping operation.
*
* The MALLOC_PAGEFILE code also benefits from this mapping algorithm,
* since it reduces the number of page files.
*/
#ifdef MALLOC_PAGEFILE
if (opt_pagefile) {
pfd = pagefile_init(size);
if (pfd == -1)
return (NULL);
} else
#endif
pfd = -1;
do {
void *over;
over = chunk_alloc(alloc_size, false, false);
if (over == NULL) {
base_node_dealloc(node);
ret = NULL;
goto RETURN;
}
offset = (uintptr_t)over & (alignment - 1);
assert((offset & chunksize_mask) == 0);
assert(offset < alloc_size);
ret = (void *)((uintptr_t)over + offset);
chunk_dealloc(over, alloc_size);
ret = pages_map(ret, chunk_size, pfd);
/*
* Failure here indicates a race with another thread, so try
* again.
*/
} while (ret == NULL);
/* Insert node into huge. */
node->addr = ret;
#ifdef MALLOC_DECOMMIT
psize = PAGE_CEILING(size);
node->size = psize;
#else
node->size = chunk_size;
#endif
malloc_mutex_lock(&huge_mtx);
extent_tree_ad_insert(&huge, node);
#ifdef MALLOC_STATS
huge_nmalloc++;
# ifdef MALLOC_DECOMMIT
huge_allocated += psize;
# else
huge_allocated += chunk_size;
# endif
#endif
malloc_mutex_unlock(&huge_mtx);
#ifdef MALLOC_DECOMMIT
if (chunk_size - psize > 0) {
pages_decommit((void *)((uintptr_t)ret + psize),
chunk_size - psize);
}
#endif
#ifdef MALLOC_DECOMMIT
VALGRIND_MALLOCLIKE_BLOCK(ret, psize, 0, false);
#else
VALGRIND_MALLOCLIKE_BLOCK(ret, chunk_size, 0, false);
#endif
#ifdef MALLOC_FILL
if (opt_junk)
# ifdef MALLOC_DECOMMIT
memset(ret, 0xa5, psize);
# else
memset(ret, 0xa5, chunk_size);
# endif
else if (opt_zero)
# ifdef MALLOC_DECOMMIT
memset(ret, 0, psize);
# else
memset(ret, 0, chunk_size);
# endif
#endif
RETURN:
#ifdef MALLOC_PAGEFILE
if (pfd != -1)
pagefile_close(pfd);
#endif
return (ret);
}
static void *
huge_ralloc(void *ptr, size_t size, size_t oldsize)
{
void *ret;
size_t copysize;
/* Avoid moving the allocation if the size class would not change. */
if (oldsize > arena_maxclass &&
CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) {
#ifdef MALLOC_DECOMMIT
size_t psize = PAGE_CEILING(size);
#endif
#ifdef MALLOC_FILL
if (opt_junk && size < oldsize) {
memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize
- size);
}
#endif
#ifdef MALLOC_DECOMMIT
if (psize < oldsize) {
extent_node_t *node, key;
pages_decommit((void *)((uintptr_t)ptr + psize),
oldsize - psize);
/* Update recorded size. */
malloc_mutex_lock(&huge_mtx);
key.addr = __DECONST(void *, ptr);
node = extent_tree_ad_search(&huge, &key);
assert(node != NULL);
assert(node->size == oldsize);
# ifdef MALLOC_STATS
huge_allocated -= oldsize - psize;
# endif
node->size = psize;
malloc_mutex_unlock(&huge_mtx);
} else if (psize > oldsize) {
extent_node_t *node, key;
pages_commit((void *)((uintptr_t)ptr + oldsize),
psize - oldsize);
/* Update recorded size. */
malloc_mutex_lock(&huge_mtx);
key.addr = __DECONST(void *, ptr);
node = extent_tree_ad_search(&huge, &key);
assert(node != NULL);
assert(node->size == oldsize);
# ifdef MALLOC_STATS
huge_allocated += psize - oldsize;
# endif
node->size = psize;
malloc_mutex_unlock(&huge_mtx);
}
#endif
#ifdef MALLOC_FILL
if (opt_zero && size > oldsize) {
memset((void *)((uintptr_t)ptr + oldsize), 0, size
- oldsize);
}
#endif
return (ptr);
}
/*
* If we get here, then size and oldsize are different enough that we
* need to use a different size class. In that case, fall back to
* allocating new space and copying.
*/
ret = huge_malloc(size, false);
if (ret == NULL)
return (NULL);
copysize = (size < oldsize) ? size : oldsize;
#ifdef VM_COPY_MIN
if (copysize >= VM_COPY_MIN)
pages_copy(ret, ptr, copysize);
else
#endif
memcpy(ret, ptr, copysize);
idalloc(ptr);
return (ret);
}
static void
huge_dalloc(void *ptr)
{
extent_node_t *node, key;
malloc_mutex_lock(&huge_mtx);
/* Extract from tree of huge allocations. */
key.addr = ptr;
node = extent_tree_ad_search(&huge, &key);
assert(node != NULL);
assert(node->addr == ptr);
extent_tree_ad_remove(&huge, node);
#ifdef MALLOC_STATS
huge_ndalloc++;
huge_allocated -= node->size;
#endif
malloc_mutex_unlock(&huge_mtx);
/* Unmap chunk. */
#ifdef MALLOC_FILL
if (opt_junk)
memset(node->addr, 0x5a, node->size);
#endif
#ifdef MALLOC_DECOMMIT
chunk_dealloc(node->addr, CHUNK_CEILING(node->size));
#else
chunk_dealloc(node->addr, node->size);
#endif
VALGRIND_FREELIKE_BLOCK(node->addr, 0);
base_node_dealloc(node);
}
#ifdef MOZ_MEMORY_BSD
static inline unsigned
malloc_ncpus(void)
{
unsigned ret;
int mib[2];
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ret);
if (sysctl(mib, 2, &ret, &len, (void *) 0, 0) == -1) {
/* Error. */
return (1);
}
return (ret);
}
#elif (defined(MOZ_MEMORY_LINUX))
#include <fcntl.h>
static inline unsigned
malloc_ncpus(void)
{
unsigned ret;
int fd, nread, column;
char buf[1];
static const char matchstr[] = "processor\t:";
/*
* sysconf(3) would be the preferred method for determining the number
* of CPUs, but it uses malloc internally, which causes untennable
* recursion during malloc initialization.
*/
fd = open("/proc/cpuinfo", O_RDONLY);
if (fd == -1)
return (1); /* Error. */
/*
* Count the number of occurrences of matchstr at the beginnings of
* lines. This treats hyperthreaded CPUs as multiple processors.
*/
column = 0;
ret = 0;
while (true) {
nread = read(fd, &buf, sizeof(buf));
if (nread <= 0)
break; /* EOF or error. */
if (buf[0] == '\n')
column = 0;
else if (column != -1) {
if (buf[0] == matchstr[column]) {
column++;
if (column == sizeof(matchstr) - 1) {
column = -1;
ret++;
}
} else
column = -1;
}
}
if (ret == 0)
ret = 1; /* Something went wrong in the parser. */
close(fd);
return (ret);
}
#elif (defined(MOZ_MEMORY_DARWIN))
#include <mach/mach_init.h>
#include <mach/mach_host.h>
static inline unsigned
malloc_ncpus(void)
{
kern_return_t error;
natural_t n;
processor_info_array_t pinfo;
mach_msg_type_number_t pinfocnt;
error = host_processor_info(mach_host_self(), PROCESSOR_BASIC_INFO,
&n, &pinfo, &pinfocnt);
if (error != KERN_SUCCESS)
return (1); /* Error. */
else
return (n);
}
#elif (defined(MOZ_MEMORY_SOLARIS))
static inline unsigned
malloc_ncpus(void)
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
#else
static inline unsigned
malloc_ncpus(void)
{
/*
* We lack a way to determine the number of CPUs on this platform, so
* assume 1 CPU.
*/
return (1);
}
#endif
static void
malloc_print_stats(void)
{
if (opt_print_stats) {
char s[UMAX2S_BUFSIZE];
_malloc_message("___ Begin malloc statistics ___\n", "", "",
"");
_malloc_message("Assertions ",
#ifdef NDEBUG
"disabled",
#else
"enabled",
#endif
"\n", "");
_malloc_message("Boolean MALLOC_OPTIONS: ",
opt_abort ? "A" : "a", "", "");
#ifdef MALLOC_FILL
_malloc_message(opt_junk ? "J" : "j", "", "", "");
#endif
#ifdef MALLOC_PAGEFILE
_malloc_message(opt_pagefile ? "o" : "O", "", "", "");
#endif
_malloc_message("P", "", "", "");
#ifdef MALLOC_UTRACE
_malloc_message(opt_utrace ? "U" : "u", "", "", "");
#endif
#ifdef MALLOC_SYSV
_malloc_message(opt_sysv ? "V" : "v", "", "", "");
#endif
#ifdef MALLOC_XMALLOC
_malloc_message(opt_xmalloc ? "X" : "x", "", "", "");
#endif
#ifdef MALLOC_FILL
_malloc_message(opt_zero ? "Z" : "z", "", "", "");
#endif
_malloc_message("\n", "", "", "");
_malloc_message("CPUs: ", umax2s(ncpus, s), "\n", "");
_malloc_message("Max arenas: ", umax2s(narenas, s), "\n", "");
#ifdef MALLOC_BALANCE
_malloc_message("Arena balance threshold: ",
umax2s(opt_balance_threshold, s), "\n", "");
#endif
_malloc_message("Pointer size: ", umax2s(sizeof(void *), s),
"\n", "");
_malloc_message("Quantum size: ", umax2s(quantum, s), "\n", "");
_malloc_message("Max small size: ", umax2s(small_max, s), "\n",
"");
_malloc_message("Max dirty pages per arena: ",
umax2s(opt_dirty_max, s), "\n", "");
_malloc_message("Chunk size: ", umax2s(chunksize, s), "", "");
_malloc_message(" (2^", umax2s(opt_chunk_2pow, s), ")\n", "");
#ifdef MALLOC_STATS
{
size_t allocated, mapped;
#ifdef MALLOC_BALANCE
uint64_t nbalance = 0;
#endif
unsigned i;
arena_t *arena;
/* Calculate and print allocated/mapped stats. */
/* arenas. */
for (i = 0, allocated = 0; i < narenas; i++) {
if (arenas[i] != NULL) {
malloc_spin_lock(&arenas[i]->lock);
allocated +=
arenas[i]->stats.allocated_small;
allocated +=
arenas[i]->stats.allocated_large;
#ifdef MALLOC_BALANCE
nbalance += arenas[i]->stats.nbalance;
#endif
malloc_spin_unlock(&arenas[i]->lock);
}
}
/* huge/base. */
malloc_mutex_lock(&huge_mtx);
allocated += huge_allocated;
mapped = stats_chunks.curchunks * chunksize;
malloc_mutex_unlock(&huge_mtx);
malloc_mutex_lock(&base_mtx);
mapped += base_mapped;
malloc_mutex_unlock(&base_mtx);
#ifdef MOZ_MEMORY_WINDOWS
malloc_printf("Allocated: %lu, mapped: %lu\n",
allocated, mapped);
#else
malloc_printf("Allocated: %zu, mapped: %zu\n",
allocated, mapped);
#endif
malloc_mutex_lock(&reserve_mtx);
malloc_printf("Reserve: min "
"cur max\n");
#ifdef MOZ_MEMORY_WINDOWS
malloc_printf(" %12lu %12lu %12lu\n",
CHUNK_CEILING(reserve_min) >> opt_chunk_2pow,
reserve_cur >> opt_chunk_2pow,
reserve_max >> opt_chunk_2pow);
#else
malloc_printf(" %12zu %12zu %12zu\n",
CHUNK_CEILING(reserve_min) >> opt_chunk_2pow,
reserve_cur >> opt_chunk_2pow,
reserve_max >> opt_chunk_2pow);
#endif
malloc_mutex_unlock(&reserve_mtx);
#ifdef MALLOC_BALANCE
malloc_printf("Arena balance reassignments: %llu\n",
nbalance);
#endif
/* Print chunk stats. */
{
chunk_stats_t chunks_stats;
malloc_mutex_lock(&huge_mtx);
chunks_stats = stats_chunks;
malloc_mutex_unlock(&huge_mtx);
malloc_printf("chunks: nchunks "
"highchunks curchunks\n");
malloc_printf(" %13llu%13lu%13lu\n",
chunks_stats.nchunks,
chunks_stats.highchunks,
chunks_stats.curchunks);
}
/* Print chunk stats. */
malloc_printf(
"huge: nmalloc ndalloc allocated\n");
#ifdef MOZ_MEMORY_WINDOWS
malloc_printf(" %12llu %12llu %12lu\n",
huge_nmalloc, huge_ndalloc, huge_allocated);
#else
malloc_printf(" %12llu %12llu %12zu\n",
huge_nmalloc, huge_ndalloc, huge_allocated);
#endif
/* Print stats for each arena. */
for (i = 0; i < narenas; i++) {
arena = arenas[i];
if (arena != NULL) {
malloc_printf(
"\narenas[%u]:\n", i);
malloc_spin_lock(&arena->lock);
stats_print(arena);
malloc_spin_unlock(&arena->lock);
}
}
}
#endif /* #ifdef MALLOC_STATS */
_malloc_message("--- End malloc statistics ---\n", "", "", "");
}
}
/*
* FreeBSD's pthreads implementation calls malloc(3), so the malloc
* implementation has to take pains to avoid infinite recursion during
* initialization.
*/
#if (defined(MOZ_MEMORY_WINDOWS) || defined(MOZ_MEMORY_DARWIN))
#define malloc_init() false
#else
static inline bool
malloc_init(void)
{
if (malloc_initialized == false)
return (malloc_init_hard());
return (false);
}
#endif
#ifndef MOZ_MEMORY_WINDOWS
static
#endif
bool
malloc_init_hard(void)
{
unsigned i;
char buf[PATH_MAX + 1];
const char *opts;
long result;
#ifndef MOZ_MEMORY_WINDOWS
int linklen;
#endif
#ifndef MOZ_MEMORY_WINDOWS
malloc_mutex_lock(&init_lock);
#endif
if (malloc_initialized) {
/*
* Another thread initialized the allocator before this one
* acquired init_lock.
*/
#ifndef MOZ_MEMORY_WINDOWS
malloc_mutex_unlock(&init_lock);
#endif
return (false);
}
#ifdef MOZ_MEMORY_WINDOWS
/* get a thread local storage index */
tlsIndex = TlsAlloc();
#endif
/* Get page size and number of CPUs */
#ifdef MOZ_MEMORY_WINDOWS
{
SYSTEM_INFO info;
GetSystemInfo(&info);
result = info.dwPageSize;
pagesize = (unsigned) result;
ncpus = info.dwNumberOfProcessors;
}
#else
ncpus = malloc_ncpus();
result = sysconf(_SC_PAGESIZE);
assert(result != -1);
pagesize = (unsigned) result;
#endif
/*
* We assume that pagesize is a power of 2 when calculating
* pagesize_mask and pagesize_2pow.
*/
assert(((result - 1) & result) == 0);
pagesize_mask = result - 1;
pagesize_2pow = ffs((int)result) - 1;
#ifdef MALLOC_PAGEFILE
/*
* Determine where to create page files. It is insufficient to
* unconditionally use P_tmpdir (typically "/tmp"), since for some
* operating systems /tmp is a separate filesystem that is rather small.
* Therefore prefer, in order, the following locations:
*
* 1) MALLOC_TMPDIR
* 2) TMPDIR
* 3) P_tmpdir
*/
{
char *s;
size_t slen;
static const char suffix[] = "/jemalloc.XXXXXX";
if ((s = getenv("MALLOC_TMPDIR")) == NULL && (s =
getenv("TMPDIR")) == NULL)
s = P_tmpdir;
slen = strlen(s);
if (slen + sizeof(suffix) > sizeof(pagefile_templ)) {
_malloc_message(_getprogname(),
": (malloc) Page file path too long\n",
"", "");
abort();
}
memcpy(pagefile_templ, s, slen);
memcpy(&pagefile_templ[slen], suffix, sizeof(suffix));
}
#endif
for (i = 0; i < 3; i++) {
unsigned j;
/* Get runtime configuration. */
switch (i) {
case 0:
#ifndef MOZ_MEMORY_WINDOWS
if ((linklen = readlink("/etc/malloc.conf", buf,
sizeof(buf) - 1)) != -1) {
/*
* Use the contents of the "/etc/malloc.conf"
* symbolic link's name.
*/
buf[linklen] = '\0';
opts = buf;
} else
#endif
{
/* No configuration specified. */
buf[0] = '\0';
opts = buf;
}
break;
case 1:
if (issetugid() == 0 && (opts =
getenv("MALLOC_OPTIONS")) != NULL) {
/*
* Do nothing; opts is already initialized to
* the value of the MALLOC_OPTIONS environment
* variable.
*/
} else {
/* No configuration specified. */
buf[0] = '\0';
opts = buf;
}
break;
case 2:
if (_malloc_options != NULL) {
/*
* Use options that were compiled into the
* program.
*/
opts = _malloc_options;
} else {
/* No configuration specified. */
buf[0] = '\0';
opts = buf;
}
break;
default:
/* NOTREACHED */
buf[0] = '\0';
opts = buf;
assert(false);
}
for (j = 0; opts[j] != '\0'; j++) {
unsigned k, nreps;
bool nseen;
/* Parse repetition count, if any. */
for (nreps = 0, nseen = false;; j++, nseen = true) {
switch (opts[j]) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
nreps *= 10;
nreps += opts[j] - '0';
break;
default:
goto MALLOC_OUT;
}
}
MALLOC_OUT:
if (nseen == false)
nreps = 1;
for (k = 0; k < nreps; k++) {
switch (opts[j]) {
case 'a':
opt_abort = false;
break;
case 'A':
opt_abort = true;
break;
case 'b':
#ifdef MALLOC_BALANCE
opt_balance_threshold >>= 1;
#endif
break;
case 'B':
#ifdef MALLOC_BALANCE
if (opt_balance_threshold == 0)
opt_balance_threshold = 1;
else if ((opt_balance_threshold << 1)
> opt_balance_threshold)
opt_balance_threshold <<= 1;
#endif
break;
case 'f':
opt_dirty_max >>= 1;
break;
case 'F':
if (opt_dirty_max == 0)
opt_dirty_max = 1;
else if ((opt_dirty_max << 1) != 0)
opt_dirty_max <<= 1;
break;
case 'g':
opt_reserve_range_lshift--;
break;
case 'G':
opt_reserve_range_lshift++;
break;
#ifdef MALLOC_FILL
case 'j':
opt_junk = false;
break;
case 'J':
opt_junk = true;
break;
#endif
case 'k':
/*
* Chunks always require at least one
* header page, so chunks can never be
* smaller than two pages.
*/
if (opt_chunk_2pow > pagesize_2pow + 1)
opt_chunk_2pow--;
break;
case 'K':
if (opt_chunk_2pow + 1 <
(sizeof(size_t) << 3))
opt_chunk_2pow++;
break;
case 'n':
opt_narenas_lshift--;
break;
case 'N':
opt_narenas_lshift++;
break;
#ifdef MALLOC_PAGEFILE
case 'o':
/* Do not over-commit. */
opt_pagefile = true;
break;
case 'O':
/* Allow over-commit. */
opt_pagefile = false;
break;
#endif
case 'p':
opt_print_stats = false;
break;
case 'P':
opt_print_stats = true;
break;
case 'q':
if (opt_quantum_2pow > QUANTUM_2POW_MIN)
opt_quantum_2pow--;
break;
case 'Q':
if (opt_quantum_2pow < pagesize_2pow -
1)
opt_quantum_2pow++;
break;
case 'r':
opt_reserve_min_lshift--;
break;
case 'R':
opt_reserve_min_lshift++;
break;
case 's':
if (opt_small_max_2pow >
QUANTUM_2POW_MIN)
opt_small_max_2pow--;
break;
case 'S':
if (opt_small_max_2pow < pagesize_2pow
- 1)
opt_small_max_2pow++;
break;
#ifdef MALLOC_UTRACE
case 'u':
opt_utrace = false;
break;
case 'U':
opt_utrace = true;
break;
#endif
#ifdef MALLOC_SYSV
case 'v':
opt_sysv = false;
break;
case 'V':
opt_sysv = true;
break;
#endif
#ifdef MALLOC_XMALLOC
case 'x':
opt_xmalloc = false;
break;
case 'X':
opt_xmalloc = true;
break;
#endif
#ifdef MALLOC_FILL
case 'z':
opt_zero = false;
break;
case 'Z':
opt_zero = true;
break;
#endif
default: {
char cbuf[2];
cbuf[0] = opts[j];
cbuf[1] = '\0';
_malloc_message(_getprogname(),
": (malloc) Unsupported character "
"in malloc options: '", cbuf,
"'\n");
}
}
}
}
}
/* Take care to call atexit() only once. */
if (opt_print_stats) {
#ifndef MOZ_MEMORY_WINDOWS
/* Print statistics at exit. */
atexit(malloc_print_stats);
#endif
}
/* Set variables according to the value of opt_small_max_2pow. */
if (opt_small_max_2pow < opt_quantum_2pow)
opt_small_max_2pow = opt_quantum_2pow;
small_max = (1U << opt_small_max_2pow);
/* Set bin-related variables. */
bin_maxclass = (pagesize >> 1);
assert(opt_quantum_2pow >= TINY_MIN_2POW);
ntbins = opt_quantum_2pow - TINY_MIN_2POW;
assert(ntbins <= opt_quantum_2pow);
nqbins = (small_max >> opt_quantum_2pow);
nsbins = pagesize_2pow - opt_small_max_2pow - 1;
/* Set variables according to the value of opt_quantum_2pow. */
quantum = (1U << opt_quantum_2pow);
quantum_mask = quantum - 1;
if (ntbins > 0)
small_min = (quantum >> 1) + 1;
else
small_min = 1;
assert(small_min <= quantum);
/* Set variables according to the value of opt_chunk_2pow. */
chunksize = (1LU << opt_chunk_2pow);
chunksize_mask = chunksize - 1;
chunk_npages = (chunksize >> pagesize_2pow);
{
size_t header_size;
/*
* Compute the header size such that it is large
* enough to contain the page map and enough nodes for the
* worst case: one node per non-header page plus one extra for
* situations where we briefly have one more node allocated
* than we will need.
*/
header_size = sizeof(arena_chunk_t) +
(sizeof(arena_chunk_map_t) * (chunk_npages - 1));
arena_chunk_header_npages = (header_size >> pagesize_2pow) +
((header_size & pagesize_mask) != 0);
}
arena_maxclass = chunksize - (arena_chunk_header_npages <<
pagesize_2pow);
UTRACE(0, 0, 0);
#ifdef MALLOC_STATS
memset(&stats_chunks, 0, sizeof(chunk_stats_t));
#endif
/* Various sanity checks that regard configuration. */
assert(quantum >= sizeof(void *));
assert(quantum <= pagesize);
assert(chunksize >= pagesize);
assert(quantum * 4 <= chunksize);
/* Initialize chunks data. */
malloc_mutex_init(&huge_mtx);
extent_tree_ad_new(&huge);
#ifdef MALLOC_STATS
huge_nmalloc = 0;
huge_ndalloc = 0;
huge_allocated = 0;
#endif
/* Initialize base allocation data structures. */
#ifdef MALLOC_STATS
base_mapped = 0;
#endif
base_nodes = NULL;
base_reserve_regs = NULL;
malloc_mutex_init(&base_mtx);
#ifdef MOZ_MEMORY_NARENAS_DEFAULT_ONE
narenas = 1;
#else
if (ncpus > 1) {
/*
* For SMP systems, create four times as many arenas as there
* are CPUs by default.
*/
opt_narenas_lshift += 2;
}
/* Determine how many arenas to use. */
narenas = ncpus;
#endif
if (opt_narenas_lshift > 0) {
if ((narenas << opt_narenas_lshift) > narenas)
narenas <<= opt_narenas_lshift;
/*
* Make sure not to exceed the limits of what base_alloc() can
* handle.
*/
if (narenas * sizeof(arena_t *) > chunksize)
narenas = chunksize / sizeof(arena_t *);
} else if (opt_narenas_lshift < 0) {
if ((narenas >> -opt_narenas_lshift) < narenas)
narenas >>= -opt_narenas_lshift;
/* Make sure there is at least one arena. */
if (narenas == 0)
narenas = 1;
}
#ifdef MALLOC_BALANCE
assert(narenas != 0);
for (narenas_2pow = 0;
(narenas >> (narenas_2pow + 1)) != 0;
narenas_2pow++);
#endif
#ifdef NO_TLS
if (narenas > 1) {
static const unsigned primes[] = {1, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
223, 227, 229, 233, 239, 241, 251, 257, 263};
unsigned nprimes, parenas;
/*
* Pick a prime number of hash arenas that is more than narenas
* so that direct hashing of pthread_self() pointers tends to
* spread allocations evenly among the arenas.
*/
assert((narenas & 1) == 0); /* narenas must be even. */
nprimes = (sizeof(primes) >> SIZEOF_INT_2POW);
parenas = primes[nprimes - 1]; /* In case not enough primes. */
for (i = 1; i < nprimes; i++) {
if (primes[i] > narenas) {
parenas = primes[i];
break;
}
}
narenas = parenas;
}
#endif
#ifndef NO_TLS
# ifndef MALLOC_BALANCE
next_arena = 0;
# endif
#endif
/* Allocate and initialize arenas. */
arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas);
if (arenas == NULL) {
#ifndef MOZ_MEMORY_WINDOWS
malloc_mutex_unlock(&init_lock);
#endif
return (true);
}
/*
* Zero the array. In practice, this should always be pre-zeroed,
* since it was just mmap()ed, but let's be sure.
*/
memset(arenas, 0, sizeof(arena_t *) * narenas);
/*
* Initialize one arena here. The rest are lazily created in
* choose_arena_hard().
*/
arenas_extend(0);
if (arenas[0] == NULL) {
#ifndef MOZ_MEMORY_WINDOWS
malloc_mutex_unlock(&init_lock);
#endif
return (true);
}
#ifndef NO_TLS
/*
* Assign the initial arena to the initial thread, in order to avoid
* spurious creation of an extra arena if the application switches to
* threaded mode.
*/
#ifdef MOZ_MEMORY_WINDOWS
TlsSetValue(tlsIndex, arenas[0]);
#else
arenas_map = arenas[0];
#endif
#endif
/*
* Seed here for the initial thread, since choose_arena_hard() is only
* called for other threads. The seed value doesn't really matter.
*/
#ifdef MALLOC_BALANCE
SPRN(balance, 42);
#endif
malloc_spin_init(&arenas_lock);
#ifdef MALLOC_VALIDATE
chunk_rtree = malloc_rtree_new((SIZEOF_PTR << 3) - opt_chunk_2pow);
if (chunk_rtree == NULL)
return (true);
#endif
/*
* Configure and initialize the memory reserve. This needs to happen
* late during initialization, since chunks are allocated.
*/
malloc_mutex_init(&reserve_mtx);
reserve_min = 0;
reserve_cur = 0;
reserve_max = 0;
if (RESERVE_RANGE_2POW_DEFAULT + opt_reserve_range_lshift >= 0) {
reserve_max += chunksize << (RESERVE_RANGE_2POW_DEFAULT +
opt_reserve_range_lshift);
}
ql_new(&reserve_regs);
reserve_seq = 0;
extent_tree_szad_new(&reserve_chunks_szad);
extent_tree_ad_new(&reserve_chunks_ad);
if (RESERVE_MIN_2POW_DEFAULT + opt_reserve_min_lshift >= 0) {
reserve_min_set(chunksize << (RESERVE_MIN_2POW_DEFAULT +
opt_reserve_min_lshift));
}
malloc_initialized = true;
#ifndef MOZ_MEMORY_WINDOWS
malloc_mutex_unlock(&init_lock);
#endif
return (false);
}
/* XXX Why not just expose malloc_print_stats()? */
#ifdef MOZ_MEMORY_WINDOWS
void
malloc_shutdown()
{
malloc_print_stats();
}
#endif
/*
* End general internal functions.
*/
/******************************************************************************/
/*
* Begin malloc(3)-compatible functions.
*/
/*
* Inline the standard malloc functions if they are being subsumed by Darwin's
* zone infrastructure.
*/
#ifdef MOZ_MEMORY_DARWIN
# define ZONE_INLINE inline
#else
# define ZONE_INLINE
#endif
/* Mangle standard interfaces on Darwin, in order to avoid linking problems. */
#ifdef MOZ_MEMORY_DARWIN
#define malloc(a) moz_malloc(a)
#define valloc(a) moz_valloc(a)
#define calloc(a, b) moz_calloc(a, b)
#define realloc(a, b) moz_realloc(a, b)
#define free(a) moz_free(a)
#endif
ZONE_INLINE
void *
malloc(size_t size)
{
void *ret;
if (malloc_init()) {
ret = NULL;
goto RETURN;
}
if (size == 0) {
#ifdef MALLOC_SYSV
if (opt_sysv == false)
#endif
size = 1;
#ifdef MALLOC_SYSV
else {
ret = NULL;
goto RETURN;
}
#endif
}
ret = imalloc(size);
RETURN:
if (ret == NULL) {
#ifdef MALLOC_XMALLOC
if (opt_xmalloc) {
_malloc_message(_getprogname(),
": (malloc) Error in malloc(): out of memory\n", "",
"");
abort();
}
#endif
errno = ENOMEM;
}
UTRACE(0, size, ret);
return (ret);
}
#ifdef MOZ_MEMORY_SOLARIS
# ifdef __SUNPRO_C
void *
memalign(size_t alignment, size_t size);
#pragma no_inline(memalign)
# elif (defined(__GNU_C__))
__attribute__((noinline))
# endif
#else
inline
#endif
void *
memalign(size_t alignment, size_t size)
{
void *ret;
assert(((alignment - 1) & alignment) == 0 && alignment >=
sizeof(void *));
if (malloc_init()) {
ret = NULL;
goto RETURN;
}
ret = ipalloc(alignment, size);
RETURN:
#ifdef MALLOC_XMALLOC
if (opt_xmalloc && ret == NULL) {
_malloc_message(_getprogname(),
": (malloc) Error in memalign(): out of memory\n", "", "");
abort();
}
#endif
UTRACE(0, size, ret);
return (ret);
}
ZONE_INLINE
int
posix_memalign(void **memptr, size_t alignment, size_t size)
{
void *result;
/* Make sure that alignment is a large enough power of 2. */
if (((alignment - 1) & alignment) != 0 || alignment < sizeof(void *)) {
#ifdef MALLOC_XMALLOC
if (opt_xmalloc) {
_malloc_message(_getprogname(),
": (malloc) Error in posix_memalign(): "
"invalid alignment\n", "", "");
abort();
}
#endif
return (EINVAL);
}
#ifdef MOZ_MEMORY_DARWIN
result = moz_memalign(alignment, size);
#else
result = memalign(alignment, size);
#endif
if (result == NULL)
return (ENOMEM);
*memptr = result;
return (0);
}
ZONE_INLINE
void *
valloc(size_t size)
{
#ifdef MOZ_MEMORY_DARWIN
return (moz_memalign(pagesize, size));
#else
return (memalign(pagesize, size));
#endif
}
ZONE_INLINE
void *
calloc(size_t num, size_t size)
{
void *ret;
size_t num_size;
if (malloc_init()) {
num_size = 0;
ret = NULL;
goto RETURN;
}
num_size = num * size;
if (num_size == 0) {
#ifdef MALLOC_SYSV
if ((opt_sysv == false) && ((num == 0) || (size == 0)))
#endif
num_size = 1;
#ifdef MALLOC_SYSV
else {
ret = NULL;
goto RETURN;
}
#endif
/*
* Try to avoid division here. We know that it isn't possible to
* overflow during multiplication if neither operand uses any of the
* most significant half of the bits in a size_t.
*/
} else if (((num | size) & (SIZE_T_MAX << (sizeof(size_t) << 2)))
&& (num_size / size != num)) {
/* size_t overflow. */
ret = NULL;
goto RETURN;
}
ret = icalloc(num_size);
RETURN:
if (ret == NULL) {
#ifdef MALLOC_XMALLOC
if (opt_xmalloc) {
_malloc_message(_getprogname(),
": (malloc) Error in calloc(): out of memory\n", "",
"");
abort();
}
#endif
errno = ENOMEM;
}
UTRACE(0, num_size, ret);
return (ret);
}
ZONE_INLINE
void *
realloc(void *ptr, size_t size)
{
void *ret;
if (size == 0) {
#ifdef MALLOC_SYSV
if (opt_sysv == false)
#endif
size = 1;
#ifdef MALLOC_SYSV
else {
if (ptr != NULL)
idalloc(ptr);
ret = NULL;
goto RETURN;
}
#endif
}
if (ptr != NULL) {
assert(malloc_initialized);
ret = iralloc(ptr, size);
if (ret == NULL) {
#ifdef MALLOC_XMALLOC
if (opt_xmalloc) {
_malloc_message(_getprogname(),
": (malloc) Error in realloc(): out of "
"memory\n", "", "");
abort();
}
#endif
errno = ENOMEM;
}
} else {
if (malloc_init())
ret = NULL;
else
ret = imalloc(size);
if (ret == NULL) {
#ifdef MALLOC_XMALLOC
if (opt_xmalloc) {
_malloc_message(_getprogname(),
": (malloc) Error in realloc(): out of "
"memory\n", "", "");
abort();
}
#endif
errno = ENOMEM;
}
}
#ifdef MALLOC_SYSV
RETURN:
#endif
UTRACE(ptr, size, ret);
return (ret);
}
ZONE_INLINE
void
free(void *ptr)
{
UTRACE(ptr, 0, 0);
if (ptr != NULL) {
assert(malloc_initialized);
idalloc(ptr);
}
}
/*
* End malloc(3)-compatible functions.
*/
/******************************************************************************/
/*
* Begin non-standard functions.
*/
size_t
malloc_usable_size(const void *ptr)
{
#ifdef MALLOC_VALIDATE
return (isalloc_validate(ptr));
#else
assert(ptr != NULL);
return (isalloc(ptr));
#endif
}
void
jemalloc_stats(jemalloc_stats_t *stats)
{
size_t i;
assert(stats != NULL);
/*
* Gather runtime settings.
*/
stats->opt_abort = opt_abort;
stats->opt_junk =
#ifdef MALLOC_FILL
opt_junk ? true :
#endif
false;
stats->opt_utrace =
#ifdef MALLOC_UTRACE
opt_utrace ? true :
#endif
false;
stats->opt_sysv =
#ifdef MALLOC_SYSV
opt_sysv ? true :
#endif
false;
stats->opt_xmalloc =
#ifdef MALLOC_XMALLOC
opt_xmalloc ? true :
#endif
false;
stats->opt_zero =
#ifdef MALLOC_FILL
opt_zero ? true :
#endif
false;
stats->narenas = narenas;
stats->balance_threshold =
#ifdef MALLOC_BALANCE
opt_balance_threshold
#else
SIZE_T_MAX
#endif
;
stats->quantum = quantum;
stats->small_max = small_max;
stats->large_max = arena_maxclass;
stats->chunksize = chunksize;
stats->dirty_max = opt_dirty_max;
malloc_mutex_lock(&reserve_mtx);
stats->reserve_min = reserve_min;
stats->reserve_max = reserve_max;
stats->reserve_cur = reserve_cur;
malloc_mutex_unlock(&reserve_mtx);
/*
* Gather current memory usage statistics.
*/
stats->mapped = 0;
stats->committed = 0;
stats->allocated = 0;
stats->dirty = 0;
/* Get huge mapped/allocated. */
malloc_mutex_lock(&huge_mtx);
stats->mapped += stats_chunks.curchunks * chunksize;
#ifdef MALLOC_DECOMMIT
stats->committed += huge_allocated;
#endif
stats->allocated += huge_allocated;
malloc_mutex_unlock(&huge_mtx);
/* Get base mapped. */
malloc_mutex_lock(&base_mtx);
stats->mapped += base_mapped;
#ifdef MALLOC_DECOMMIT
stats->committed += base_mapped;
#endif
malloc_mutex_unlock(&base_mtx);
/* Iterate over arenas and their chunks. */
for (i = 0; i < narenas; i++) {
arena_t *arena = arenas[i];
if (arena != NULL) {
arena_chunk_t *chunk;
malloc_spin_lock(&arena->lock);
stats->allocated += arena->stats.allocated_small;
stats->allocated += arena->stats.allocated_large;
#ifdef MALLOC_DECOMMIT
rb_foreach_begin(arena_chunk_t, link_dirty,
&arena->chunks_dirty, chunk) {
size_t j;
for (j = 0; j < chunk_npages; j++) {
if ((chunk->map[j].bits &
CHUNK_MAP_DECOMMITTED) == 0)
stats->committed += pagesize;
}
} rb_foreach_end(arena_chunk_t, link_dirty,
&arena->chunks_dirty, chunk)
#endif
stats->dirty += (arena->ndirty << pagesize_2pow);
malloc_spin_unlock(&arena->lock);
}
}
#ifndef MALLOC_DECOMMIT
stats->committed = stats->mapped;
#endif
}
void *
xmalloc(size_t size)
{
void *ret;
if (malloc_init())
reserve_fail(size, "xmalloc");
if (size == 0) {
#ifdef MALLOC_SYSV
if (opt_sysv == false)
#endif
size = 1;
#ifdef MALLOC_SYSV
else {
_malloc_message(_getprogname(),
": (malloc) Error in xmalloc(): ",
"invalid size 0", "\n");
abort();
}
#endif
}
ret = imalloc(size);
if (ret == NULL) {
uint64_t seq = 0;
do {
seq = reserve_crit(size, "xmalloc", seq);
ret = imalloc(size);
} while (ret == NULL);
}
UTRACE(0, size, ret);
return (ret);
}
void *
xcalloc(size_t num, size_t size)
{
void *ret;
size_t num_size;
num_size = num * size;
if (malloc_init())
reserve_fail(num_size, "xcalloc");
if (num_size == 0) {
#ifdef MALLOC_SYSV
if ((opt_sysv == false) && ((num == 0) || (size == 0)))
#endif
num_size = 1;
#ifdef MALLOC_SYSV
else {
_malloc_message(_getprogname(),
": (malloc) Error in xcalloc(): ",
"invalid size 0", "\n");
abort();
}
#endif
/*
* Try to avoid division here. We know that it isn't possible to
* overflow during multiplication if neither operand uses any of the
* most significant half of the bits in a size_t.
*/
} else if (((num | size) & (SIZE_T_MAX << (sizeof(size_t) << 2)))
&& (num_size / size != num)) {
/* size_t overflow. */
_malloc_message(_getprogname(),
": (malloc) Error in xcalloc(): ",
"size overflow", "\n");
abort();
}
ret = icalloc(num_size);
if (ret == NULL) {
uint64_t seq = 0;
do {
seq = reserve_crit(num_size, "xcalloc", seq);
ret = icalloc(num_size);
} while (ret == NULL);
}
UTRACE(0, num_size, ret);
return (ret);
}
void *
xrealloc(void *ptr, size_t size)
{
void *ret;
if (size == 0) {
#ifdef MALLOC_SYSV
if (opt_sysv == false)
#endif
size = 1;
#ifdef MALLOC_SYSV
else {
if (ptr != NULL)
idalloc(ptr);
_malloc_message(_getprogname(),
": (malloc) Error in xrealloc(): ",
"invalid size 0", "\n");
abort();
}
#endif
}
if (ptr != NULL) {
assert(malloc_initialized);
ret = iralloc(ptr, size);
if (ret == NULL) {
uint64_t seq = 0;
do {
seq = reserve_crit(size, "xrealloc", seq);
ret = iralloc(ptr, size);
} while (ret == NULL);
}
} else {
if (malloc_init())
reserve_fail(size, "xrealloc");
ret = imalloc(size);
if (ret == NULL) {
uint64_t seq = 0;
do {
seq = reserve_crit(size, "xrealloc", seq);
ret = imalloc(size);
} while (ret == NULL);
}
}
UTRACE(ptr, size, ret);
return (ret);
}
void *
xmemalign(size_t alignment, size_t size)
{
void *ret;
assert(((alignment - 1) & alignment) == 0 && alignment >=
sizeof(void *));
if (malloc_init())
reserve_fail(size, "xmemalign");
ret = ipalloc(alignment, size);
if (ret == NULL) {
uint64_t seq = 0;
do {
seq = reserve_crit(size, "xmemalign", seq);
ret = ipalloc(alignment, size);
} while (ret == NULL);
}
UTRACE(0, size, ret);
return (ret);
}
static void
reserve_shrink(void)
{
extent_node_t *node;
assert(reserve_cur > reserve_max);
#ifdef MALLOC_DEBUG
{
extent_node_t *node;
size_t reserve_size;
reserve_size = 0;
rb_foreach_begin(extent_node_t, link_szad, &reserve_chunks_szad,
node) {
reserve_size += node->size;
} rb_foreach_end(extent_node_t, link_szad, &reserve_chunks_szad,
node)
assert(reserve_size == reserve_cur);
reserve_size = 0;
rb_foreach_begin(extent_node_t, link_ad, &reserve_chunks_ad,
node) {
reserve_size += node->size;
} rb_foreach_end(extent_node_t, link_ad, &reserve_chunks_ad,
node)
assert(reserve_size == reserve_cur);
}
#endif
/* Discard chunks until the the reserve is below the size limit. */
rb_foreach_reverse_begin(extent_node_t, link_ad, &reserve_chunks_ad,
node) {
#ifndef MALLOC_DECOMMIT
if (node->size <= reserve_cur - reserve_max) {
#endif
extent_node_t *tnode = extent_tree_ad_prev(
&reserve_chunks_ad, node);
#ifdef MALLOC_DECOMMIT
assert(node->size <= reserve_cur - reserve_max);
#endif
/* Discard the entire [multi-]chunk. */
extent_tree_szad_remove(&reserve_chunks_szad, node);
extent_tree_ad_remove(&reserve_chunks_ad, node);
reserve_cur -= node->size;
pages_unmap(node->addr, node->size);
#ifdef MALLOC_STATS
stats_chunks.curchunks -= (node->size / chunksize);
#endif
base_node_dealloc(node);
if (reserve_cur == reserve_max)
break;
rb_foreach_reverse_prev(extent_node_t, link_ad,
extent_ad_comp, &reserve_chunks_ad, tnode);
#ifndef MALLOC_DECOMMIT
} else {
/* Discard the end of the multi-chunk. */
extent_tree_szad_remove(&reserve_chunks_szad, node);
node->size -= reserve_cur - reserve_max;
extent_tree_szad_insert(&reserve_chunks_szad, node);
pages_unmap((void *)((uintptr_t)node->addr +
node->size), reserve_cur - reserve_max);
#ifdef MALLOC_STATS
stats_chunks.curchunks -= ((reserve_cur - reserve_max) /
chunksize);
#endif
reserve_cur = reserve_max;
break;
}
#endif
assert(reserve_cur > reserve_max);
} rb_foreach_reverse_end(extent_node_t, link_ad, &reserve_chunks_ad,
node)
}
/* Send a condition notification. */
static uint64_t
reserve_notify(reserve_cnd_t cnd, size_t size, uint64_t seq)
{
reserve_reg_t *reg;
/* seq is used to keep track of distinct condition-causing events. */
if (seq == 0) {
/* Allocate new sequence number. */
reserve_seq++;
seq = reserve_seq;
}
/*
* Advance to the next callback registration and send a notification,
* unless one has already been sent for this condition-causing event.
*/
reg = ql_first(&reserve_regs);
if (reg == NULL)
return (0);
ql_first(&reserve_regs) = ql_next(&reserve_regs, reg, link);
if (reg->seq == seq)
return (0);
reg->seq = seq;
malloc_mutex_unlock(&reserve_mtx);
reg->cb(reg->ctx, cnd, size);
malloc_mutex_lock(&reserve_mtx);
return (seq);
}
/* Allocation failure due to OOM. Try to free some memory via callbacks. */
static uint64_t
reserve_crit(size_t size, const char *fname, uint64_t seq)
{
/*
* Send one condition notification. Iteration is handled by the
* caller of this function.
*/
malloc_mutex_lock(&reserve_mtx);
seq = reserve_notify(RESERVE_CND_CRIT, size, seq);
malloc_mutex_unlock(&reserve_mtx);
/* If no notification could be sent, then no further recourse exists. */
if (seq == 0)
reserve_fail(size, fname);
return (seq);
}
/* Permanent allocation failure due to OOM. */
static void
reserve_fail(size_t size, const char *fname)
{
uint64_t seq = 0;
/* Send fail notifications. */
malloc_mutex_lock(&reserve_mtx);
do {
seq = reserve_notify(RESERVE_CND_FAIL, size, seq);
} while (seq != 0);
malloc_mutex_unlock(&reserve_mtx);
/* Terminate the application. */
_malloc_message(_getprogname(),
": (malloc) Error in ", fname, "(): out of memory\n");
abort();
}
bool
reserve_cb_register(reserve_cb_t *cb, void *ctx)
{
reserve_reg_t *reg = base_reserve_reg_alloc();
if (reg == NULL)
return (true);
ql_elm_new(reg, link);
reg->cb = cb;
reg->ctx = ctx;
reg->seq = 0;
malloc_mutex_lock(&reserve_mtx);
ql_head_insert(&reserve_regs, reg, link);
malloc_mutex_unlock(&reserve_mtx);
return (false);
}
bool
reserve_cb_unregister(reserve_cb_t *cb, void *ctx)
{
reserve_reg_t *reg = NULL;
malloc_mutex_lock(&reserve_mtx);
ql_foreach(reg, &reserve_regs, link) {
if (reg->cb == cb && reg->ctx == ctx) {
ql_remove(&reserve_regs, reg, link);
break;
}
}
malloc_mutex_unlock(&reserve_mtx);
if (reg != NULL)
base_reserve_reg_dealloc(reg);
return (false);
return (true);
}
size_t
reserve_cur_get(void)
{
size_t ret;
malloc_mutex_lock(&reserve_mtx);
ret = reserve_cur;
malloc_mutex_unlock(&reserve_mtx);
return (ret);
}
size_t
reserve_min_get(void)
{
size_t ret;
malloc_mutex_lock(&reserve_mtx);
ret = reserve_min;
malloc_mutex_unlock(&reserve_mtx);
return (ret);
}
bool
reserve_min_set(size_t min)
{
min = CHUNK_CEILING(min);
malloc_mutex_lock(&reserve_mtx);
/* Keep |reserve_max - reserve_min| the same. */
if (min < reserve_min) {
reserve_max -= reserve_min - min;
reserve_min = min;
} else {
/* Protect against wrap-around. */
if (reserve_max + min - reserve_min < reserve_max) {
reserve_min = SIZE_T_MAX - (reserve_max - reserve_min)
- chunksize + 1;
reserve_max = SIZE_T_MAX - chunksize + 1;
} else {
reserve_max += min - reserve_min;
reserve_min = min;
}
}
/* Resize the reserve if necessary. */
if (reserve_cur < reserve_min) {
size_t size = reserve_min - reserve_cur;
/* Force the reserve to grow by allocating/deallocating. */
malloc_mutex_unlock(&reserve_mtx);
#ifdef MALLOC_DECOMMIT
{
void **chunks;
size_t i, n;
n = size >> opt_chunk_2pow;
chunks = imalloc(n * sizeof(void *));
if (chunks == NULL)
return (true);
for (i = 0; i < n; i++) {
chunks[i] = huge_malloc(chunksize, false);
if (chunks[i] == NULL) {
size_t j;
for (j = 0; j < i; j++) {
huge_dalloc(chunks[j]);
}
idalloc(chunks);
return (true);
}
}
for (i = 0; i < n; i++)
huge_dalloc(chunks[i]);
idalloc(chunks);
}
#else
{
void *x = huge_malloc(size, false);
if (x == NULL) {
return (true);
}
huge_dalloc(x);
}
#endif
} else if (reserve_cur > reserve_max) {
reserve_shrink();
malloc_mutex_unlock(&reserve_mtx);
} else
malloc_mutex_unlock(&reserve_mtx);
return (false);
}
#ifdef MOZ_MEMORY_WINDOWS
void*
_recalloc(void *ptr, size_t count, size_t size)
{
size_t oldsize = (ptr != NULL) ? isalloc(ptr) : 0;
size_t newsize = count * size;
/*
* In order for all trailing bytes to be zeroed, the caller needs to
* use calloc(), followed by recalloc(). However, the current calloc()
* implementation only zeros the bytes requested, so if recalloc() is
* to work 100% correctly, calloc() will need to change to zero
* trailing bytes.
*/
ptr = realloc(ptr, newsize);
if (ptr != NULL && oldsize < newsize) {
memset((void *)((uintptr_t)ptr + oldsize), 0, newsize -
oldsize);
}
return ptr;
}
/*
* This impl of _expand doesn't ever actually expand or shrink blocks: it
* simply replies that you may continue using a shrunk block.
*/
void*
_expand(void *ptr, size_t newsize)
{
if (isalloc(ptr) >= newsize)
return ptr;
return NULL;
}
size_t
_msize(const void *ptr)
{
return malloc_usable_size(ptr);
}
#endif
/*
* End non-standard functions.
*/
/******************************************************************************/
/*
* Begin library-private functions, used by threading libraries for protection
* of malloc during fork(). These functions are only called if the program is
* running in threaded mode, so there is no need to check whether the program
* is threaded here.
*/
void
_malloc_prefork(void)
{
unsigned i;
/* Acquire all mutexes in a safe order. */
malloc_spin_lock(&arenas_lock);
for (i = 0; i < narenas; i++) {
if (arenas[i] != NULL)
malloc_spin_lock(&arenas[i]->lock);
}
malloc_spin_unlock(&arenas_lock);
malloc_mutex_lock(&base_mtx);
malloc_mutex_lock(&huge_mtx);
}
void
_malloc_postfork(void)
{
unsigned i;
/* Release all mutexes, now that fork() has completed. */
malloc_mutex_unlock(&huge_mtx);
malloc_mutex_unlock(&base_mtx);
malloc_spin_lock(&arenas_lock);
for (i = 0; i < narenas; i++) {
if (arenas[i] != NULL)
malloc_spin_unlock(&arenas[i]->lock);
}
malloc_spin_unlock(&arenas_lock);
}
/*
* End library-private functions.
*/
/******************************************************************************/
#ifdef MOZ_MEMORY_DARWIN
static malloc_zone_t zone;
static struct malloc_introspection_t zone_introspect;
static size_t
zone_size(malloc_zone_t *zone, void *ptr)
{
/*
* There appear to be places within Darwin (such as setenv(3)) that
* cause calls to this function with pointers that *no* zone owns. If
* we knew that all pointers were owned by *some* zone, we could split
* our zone into two parts, and use one as the default allocator and
* the other as the default deallocator/reallocator. Since that will
* not work in practice, we must check all pointers to assure that they
* reside within a mapped chunk before determining size.
*/
return (isalloc_validate(ptr));
}
static void *
zone_malloc(malloc_zone_t *zone, size_t size)
{
return (malloc(size));
}
static void *
zone_calloc(malloc_zone_t *zone, size_t num, size_t size)
{
return (calloc(num, size));
}
static void *
zone_valloc(malloc_zone_t *zone, size_t size)
{
void *ret = NULL; /* Assignment avoids useless compiler warning. */
posix_memalign(&ret, pagesize, size);
return (ret);
}
static void
zone_free(malloc_zone_t *zone, void *ptr)
{
free(ptr);
}
static void *
zone_realloc(malloc_zone_t *zone, void *ptr, size_t size)
{
return (realloc(ptr, size));
}
static void *
zone_destroy(malloc_zone_t *zone)
{
/* This function should never be called. */
assert(false);
return (NULL);
}
static size_t
zone_good_size(malloc_zone_t *zone, size_t size)
{
size_t ret;
void *p;
/*
* Actually create an object of the appropriate size, then find out
* how large it could have been without moving up to the next size
* class.
*/
p = malloc(size);
if (p != NULL) {
ret = isalloc(p);
free(p);
} else
ret = size;
return (ret);
}
static void
zone_force_lock(malloc_zone_t *zone)
{
_malloc_prefork();
}
static void
zone_force_unlock(malloc_zone_t *zone)
{
_malloc_postfork();
}
static malloc_zone_t *
create_zone(void)
{
assert(malloc_initialized);
zone.size = (void *)zone_size;
zone.malloc = (void *)zone_malloc;
zone.calloc = (void *)zone_calloc;
zone.valloc = (void *)zone_valloc;
zone.free = (void *)zone_free;
zone.realloc = (void *)zone_realloc;
zone.destroy = (void *)zone_destroy;
zone.zone_name = "jemalloc_zone";
zone.batch_malloc = NULL;
zone.batch_free = NULL;
zone.introspect = &zone_introspect;
zone_introspect.enumerator = NULL;
zone_introspect.good_size = (void *)zone_good_size;
zone_introspect.check = NULL;
zone_introspect.print = NULL;
zone_introspect.log = NULL;
zone_introspect.force_lock = (void *)zone_force_lock;
zone_introspect.force_unlock = (void *)zone_force_unlock;
zone_introspect.statistics = NULL;
return (&zone);
}
__attribute__((constructor))
void
jemalloc_darwin_init(void)
{
extern unsigned malloc_num_zones;
extern malloc_zone_t **malloc_zones;
if (malloc_init_hard())
abort();
/*
* The following code is *not* thread-safe, so it's critical that
* initialization be manually triggered.
*/
/* Register the custom zones. */
malloc_zone_register(create_zone());
assert(malloc_zones[malloc_num_zones - 1] == &zone);
/*
* Shift malloc_zones around so that zone is first, which makes it the
* default zone.
*/
assert(malloc_num_zones > 1);
memmove(&malloc_zones[1], &malloc_zones[0],
sizeof(malloc_zone_t *) * (malloc_num_zones - 1));
malloc_zones[0] = &zone;
}
#endif
|
tmhorne/celtx
|
memory/jemalloc/jemalloc.c
|
C
|
mpl-2.0
| 173,623
|
### Spool
A sub object for transmission, we can say it represent and hold method related to a single attempt of transmission.
* __construct($spool_id = NULL)
create new instance of spool, load existing spool if $spool_id is provided
* validate($field, $value)
before saving, validate current instance
* delete()
delete this spool entry
* get($field, $value)
get value of given field of spool object
* set($field, $value)
set value of a given field of spool object
* save()
save this spool object. If new object then add new record in database, if existing object then update record.
|
ictinnovations/ictcore
|
docs/developer-guide/operation/spool.md
|
Markdown
|
mpl-2.0
| 596
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
pub use lrs_inotify::{Inotify, InodeWatch, InodeData, InodeDataIter};
pub use lrs_inotify::flags::{WatchFlags, InotifyFlags};
pub use lrs_inotify::event::{InodeEvents};
pub mod flags {
pub use lrs_inotify::flags::{
WATCH_NONE, INOTIFY_NONE,
WATCH_DONT_FOLLOW_LINKS, WATCH_NO_UNLINKED, WATCH_OR_EVENTS, WATCH_ONE_SHOT,
WATCH_ONLY_DIRECTORY, INOTIFY_DONT_BLOCK, INOTIFY_CLOSE_ON_EXEC,
};
}
pub mod events {
pub use lrs_inotify::event::{
INEV_ALL, INEV_CLOSE, INEV_MOVE,
INEV_NONE, INEV_ACCESS, INEV_MODIFY, INEV_ATTRIB, INEV_CLOSE_WRITE,
INEV_CLOSE_READ, INEV_OPEN, INEV_MOVED_FROM, INEV_MOVED_TO, INEV_CREATE,
INEV_DELETE, INEV_DELETE_SELF, INEV_MOVE_SELF, INEV_UNMOUNT, INEV_OVERFLOW,
INEV_IGNORED, INEV_DIR,
};
}
|
lrs-lang/lib
|
src/lrs/inotify.rs
|
Rust
|
mpl-2.0
| 999
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `BindTexture` static in crate `gleam`.">
<meta name="keywords" content="rust, rustlang, rust-lang, BindTexture">
<title>gleam::ffi::storage::BindTexture - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>storage</a></p><script>window.sidebarCurrent = {name: 'BindTexture', ty: 'static', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content static">
<h1 class='fqn'><span class='in-band'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>storage</a>::<wbr><a class='static' href=''>BindTexture</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-4435' class='srclink' href='../../../src/gleam/home/servo/buildbot/slave/doc/build/target/debug/build/gleam-8cc6d4d4d5b87928/out/gl_bindings.rs.html#3107-3110' title='goto source code'>[src]</a></span></h1>
<pre class='rust static'>pub static mut BindTexture: <a class='struct' href='../../../gleam/gl/struct.FnPtr.html' title='gleam::gl::FnPtr'>FnPtr</a><code> = </code><code>FnPtr{f: super::missing_fn_panic as *const raw::c_void, is_loaded: false,}</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "gleam";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
gleam/ffi/storage/static.BindTexture.html
|
HTML
|
mpl-2.0
| 4,488
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `GetPerfMonitoringTestCpuRescheduling` fn in crate `js`.">
<meta name="keywords" content="rust, rustlang, rust-lang, GetPerfMonitoringTestCpuRescheduling">
<title>js::jsapi::GetPerfMonitoringTestCpuRescheduling - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a></p><script>window.sidebarCurrent = {name: 'GetPerfMonitoringTestCpuRescheduling', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a>::<wbr><a class='fn' href=''>GetPerfMonitoringTestCpuRescheduling</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-10505' class='srclink' href='../../src/js/jsapi_linux_64.rs.html#9262-9264' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe extern fn GetPerfMonitoringTestCpuRescheduling(arg1: <a class='primitive' href='../../std/primitive.pointer.html'>*mut </a><a class='enum' href='../../js/jsapi/enum.JSRuntime.html' title='js::jsapi::JSRuntime'>JSRuntime</a>, stayed: <a class='primitive' href='../../std/primitive.pointer.html'>*mut </a><a class='primitive' href='../../std/primitive.u64.html'>u64</a>, moved: <a class='primitive' href='../../std/primitive.pointer.html'>*mut </a><a class='primitive' href='../../std/primitive.u64.html'>u64</a>)</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "js";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
js/jsapi/fn.GetPerfMonitoringTestCpuRescheduling.html
|
HTML
|
mpl-2.0
| 4,679
|
{% extends "manage/base.html" %}
{% block page_title %}Admin{% endblock %}
{% block site_css %}
{{ super() }}
<style type="text/css">
</style>
{% endblock %}
{% block admin_title %}Admin Home{% endblock %}
{% block mainbody %}
<div class="panel">
<div class="body">
<p>
<a href="{{ url('manage:featured_versions') }}">Featured Versions</a>
</p>
<p>
<a href="{{ url('manage:fields') }}">Fields</a>
</p>
<p>
<a href="{{ url('manage:skiplist') }}">Skiplist</a>
</p>
<p>
<a href="{{ url('manage:users') }}">Users</a>
</p>
<p>
<a href="{{ url('manage:groups') }}">Groups</a>
</p>
<p>
<a href="{{ url('manage:analyze_model_fetches') }}">Analyze Model Fetches</a>
</p>
<p>
<a href="{{ url('manage:graphics_devices') }}">Graphics Devices</a>
</p>
<p>
<a href="{{ url('manage:symbols_uploads') }}">Symbols Uploads</a>
</p>
<p>
<a href="{{ url('manage:supersearch_fields') }}">Super Search Fields</a>
</p>
<p>
<a href="{{ url('manage:products') }}">Products</a>
</p>
<p>
<a href="{{ url('manage:releases') }}">Releases</a>
</p>
<p>
<a href="{{ url('manage:events') }}">Events</a>
</p>
<p>
<a href="{{ url('manage:api_tokens') }}">API Tokens</a>
</p>
</div>
</div>
{% endblock %}
|
rhelmer/socorro
|
webapp-django/crashstats/manage/templates/manage/home.html
|
HTML
|
mpl-2.0
| 1,478
|
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Leaflet Map</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 100%; min-width: 1000px; min-height: 1000px"></div>
<!--<script>
var myStyle = {
"color": "#000",
"weight": 1,
//"opacity": 0.85,
"fillOpacity": .15,
//"fillColor": "#ffa500" // orange
"fillColor": "#1c6ba0"
};
var urls = ['data/NHDArea.geojson', 'data/NHDFlowline.geojson', 'data/NHDLine.geojson', 'data/NHDPoint.geojson', 'data/NHDPointEventFC.geojson', 'data/NHDWaterbody.geojson', 'data/WBDHU2.geojson', 'data/WBDHU4.geojson', 'data/WBDHU6.geojson', 'data/WBDHU8.geojson', 'data/WBDHU10.geojson', 'data/WBDHU12.geojson', 'data/WBDLine.geojson'];
// http://data.codefordc.org/dataset/fb15f0c6-a2f0-4af6-a973-2c51b155b213/resource/98c0ed27-4e25-49c6-b8e2-99dac8a20a44/download/zip-codes.geojson
var urlX = 'http://data.codefordc.org/dataset/fb15f0c6-a2f0-4af6-a973-2c51b155b213/resource/98c0ed27-4e25-49c6-b8e2-99dac8a20a44/download/zip-codes.geojson';
var zipCodes = new L.LayerGroup()
$.getJSON('http://data.codefordc.org/dataset/fb15f0c6-a2f0-4af6-a973-2c51b155b213/resource/98c0ed27-4e25-49c6-b8e2-99dac8a20a44/download/zip-codes.geojson',function(data){
//L.geoJson(data, { style: myStyle }).addTo(zipCodes);
L.geoJson(data, { style: myStyle }).addTo(map);
//console.log(data.features[0].properties["ZIPCODE"].length);
//console.log(data);
//console.log(data.features.properties);
//console.log(data.features[0].properties);
//console.log(data.features[0].properties["ZIPCODE"]);
var values = [];
var keys = [];
jQuery.each(data, function(key, value) {
//console.log("key: " + key);
//console.log("value: " + value);
values.push(value);
keys.push(key);
})
jQuery.each(values, function(y, x) {
console.log("value nested: " + x[0]);
//console.log("value nested: " + y);
})
for (var z = 0; z < values.length; z++) {
console.log(values[z]);
console.log(data.features[0].properties[z]);
//console.log("Zip Code: " + data.features[0].properties["ZIPCODE"]);
}
});
//L.control.layers(baseLayers, overlays).addTo(map);
var mbAttr = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
var grayscale = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
streets = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr});
var map = L.map('map', {
center: [38.904722, -77.016389],
zoom: 12,
layers: [grayscale]
});
var baseLayers = {
"<strong>Grayscale</strong>": grayscale,
"<strong>Streets/<strong>": streets
};
var overlays = {
"zip-codes.geojson": zipCodes
};
// L.control.layers(baseLayers, overlays).addTo(map);
</script>-->
<script>
var map = L.map('map').setView([38.911206,-77.028961], 12);
//var map = L.map('map').setView([39.5,-98.35], 5);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map);
var myStyle = {
"color": "#000",
"weight": 1,
"opacity": 0.85,
"fillColor": "transparent",
"stroke": "transparent"
//"fillOpacity": 0.45
//"fillColor": "#000"
};
//jQuery.getJSON("dc.gov-zip-codes.geojson", function (data) {
$.getJSON("wards-2012.geojson", function (data){
var geojson = L.geoJson(data, {
onEachFeature: function (feature, layer) {
var wardColor01 = '#ff0000';
var wardColor02 = '#00ff00';
var wardColor03 = '#005500';
var wardColor04 = '#0000ff';
var wardColor05 = '#b0b0ff';
var wardColor06 = '#0000ff';
var wardColor07 = '#ffffff';
var wardColor08 = '#555555';
var wardColor;
if (layer.feature.properties.WARD === 1) {
wardColor = wardColor01;
} else if (layer.feature.properties.WARD === 2) {
wardColor = wardColor02;
} else if (layer.feature.properties.WARD === 3) {
wardColor = wardColor03;
} else if (layer.feature.properties.WARD === 4) {
wardColor = wardColor04;
} else if (layer.feature.properties.WARD === 5) {
wardColor = wardColor05;
} else if (layer.feature.properties.WARD === 6) {
wardColor = wardColor06;
} else if (layer.feature.properties.WARD === 7) {
wardColor = wardColor07;
} else if (layer.feature.properties.WARD === 8) {
wardColor = wardColor08;
};
//layer.setStyle({color: zipCodesColor, weight: 2, opacity: 1, fillOpacity: 0.65, fillColor = '#fff'});
// outline zip code
//layer.setStyle({color: zipCodesColor, weight: 2, opacity: 1});
layer.setStyle({fillOpacity: .45, fillColor: wardColor, color: '#000', opacity: 1, weight: 1.45});
/**var phm2a = '#ababd9';
var phmColor;
// "ZONE": "7b: 5 to 10 F"
if (layer.feature.properties.ZONE == '2b: -45 to -40 F') {
phmColor = phm2b;
} else if (layer.feature.properties.ZONE == '3a: -40 to -35 F') {
phmColor = phm3a;
} else if (layer.feature.properties.ZONE == '3b: -35 to -30 F') {
phmColor = phm3b;
} else if (layer.feature.properties.ZONE == '4a: -30 to -25 F') {
phmColor = phm4a;
} else if (layer.feature.properties.ZONE == '4b: -25 to -20 F') {
phmColor = phm4b;
} else if (layer.feature.properties.ZONE == '5a: -20 to -15 F') {
phmColor = phm5a;
} else if (layer.feature.properties.ZONE == '5b: -15 to -10 F') {
phmColor = phm5b;
} else if (layer.feature.properties.ZONE == '6a: -10 to -5 F') {
phmColor = phm6a;
} else if (layer.feature.properties.ZONE == '6b: -5 to 0 F') {
phmColor = phm6b;
} else if (layer.feature.properties.ZONE == '7a: 0 to 5 F') {
phmColor = phm7a;
} else if (layer.feature.properties.ZONE == '7b: 5 to 10 F') {
phmColor = phm7b;
} else if (layer.feature.properties.ZONE == '8a: 10 to 15 F') {
phmColor = phm8a;
} else if (layer.feature.properties.ZONE == '8b: 15 to 20 F') {
phmColor = phm8b;
} else if (layer.feature.properties.ZONE == '9a: 20 to 25 F') {
phmColor = phm9a;
} else if (layer.feature.properties.ZONE == '9b: 25 to 30 F') {
phmColor = phm9b;
} else if (layer.feature.properties.ZONE == '10a: 30 to 35 F') {
phmColor = phm10a;
} else if (layer.feature.properties.ZONE == '10b: 35 to 40 F') {
phmColor = phm10b;
} else if (layer.feature.properties.ZONE == '11a: 40 to 45 F') {
phmColor = phm11a;
} else if (layer.feature.properties.ZONE == '11b: 45 to 50 F') {
phmColor = phm11b;
} else {
phmColor = "#fff";
}
**/
//layer.setStyle({color: phmColor, weight: 2, opacity: 1, fillOpacity: 0.65, fillColor: phmColor});
console.log("layer: " + layer.feature.properties.WARD);
}
}).addTo(map);
});
</script>
</body>
</html>
|
jalbertbowden/dcdatadump
|
leaflet/2017-04-05-done/wards/wards.html
|
HTML
|
mpl-2.0
| 7,707
|
"use strict";
module.exports = OTR
var path = require('path')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var smwPath = 'sm-webworker.js'
var Worker = global.Worker
if (!Worker) {
smwPath = path.join(__dirname, smwPath)
try {
// load optional dep. in node
Worker = require('webworker-threads').Worker
} catch (err) {}
}
var CryptoJS = require('../vendor/crypto.js')
var BigInt = require('../vendor/bigint.js')
var CONST = require('./const.js')
var HLP = require('./helpers.js')
var Parse = require('./parse.js')
var AKE = require('./ake.js')
var SM = require('./sm.js')
var DSA = require('./dsa.js')
// expose CONST for consistency with docs
OTR.CONST = CONST
// diffie-hellman modulus and generator
// see group 5, RFC 3526
var G = BigInt.str2bigInt(CONST.G, 10)
var N = BigInt.str2bigInt(CONST.N, 16)
// JavaScript integers
var MAX_INT = Math.pow(2, 53) - 1 // doubles
var MAX_UINT = Math.pow(2, 31) - 1 // bitwise operators
// OTR contructor
function OTR(options) {
if (!(this instanceof OTR)) return new OTR(options)
// options
options = options || {}
// private keys
if (!options.priv)
throw new Error('Requires long-lived DSA key.')
this.priv = options.priv ? options.priv : new DSA()
this.fragment_size = options.fragment_size || 0
if (this.fragment_size < 0)
throw new Error('Fragment size must be a positive integer.')
this.send_interval = options.send_interval || 0
if (this.send_interval < 0)
throw new Error('Send interval must be a positive integer.')
this.outgoing = []
// instance tag
this.our_instance_tag = options.instance_tag || OTR.makeInstanceTag()
// debug
this.debug = !!options.debug
// smp in webworker options
// this is still experimental and undocumented
this.smw = options.smw
// init vals
this.init()
// bind methods
var self = this
;['sendMsg', 'receiveMsg'].forEach(function (meth) {
self[meth] = self[meth].bind(self)
})
EventEmitter.call(this)
}
// inherit from EE
inherits(OTR, EventEmitter)
// add to prototype
OTR.prototype.init = function () {
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.authstate = CONST.AUTHSTATE_NONE
this.ALLOW_V2 = true
this.ALLOW_V3 = true
this.REQUIRE_ENCRYPTION = false
this.SEND_WHITESPACE_TAG = false
this.WHITESPACE_START_AKE = false
this.ERROR_START_AKE = false
Parse.initFragment(this)
// their keys
this.their_y = null
this.their_old_y = null
this.their_keyid = 0
this.their_priv_pk = null
this.their_instance_tag = '\x00\x00\x00\x00'
// our keys
this.our_dh = this.dh()
this.our_old_dh = this.dh()
this.our_keyid = 2
// session keys
this.sessKeys = [ new Array(2), new Array(2) ]
// saved
this.storedMgs = []
this.oldMacKeys = []
// smp
this.sm = null // initialized after AKE
// when ake is complete
// save their keys and the session
this._akeInit()
// receive plaintext message since switching to plaintext
// used to decide when to stop sending pt tags when SEND_WHITESPACE_TAG
this.receivedPlaintext = false
}
OTR.prototype._akeInit = function () {
this.ake = new AKE(this)
this.transmittedRS = false
this.ssid = null
}
// smp over webworker
OTR.prototype._SMW = function (otr, reqs) {
this.otr = otr
var opts = {
path: smwPath
, seed: BigInt.getSeed
}
if (typeof otr.smw === 'object')
Object.keys(otr.smw).forEach(function (k) {
opts[k] = otr.smw[k]
})
this.worker = new Worker(opts.path)
var self = this
this.worker.onmessage = function (e) {
var d = e.data
if (!d) return
self.emit.apply(self, [d.method].concat(d.args))
}
this.worker.postMessage({
type: 'seed'
, seed: opts.seed()
, imports: opts.imports
})
this.worker.postMessage({
type: 'init'
, reqs: reqs
})
}
// inherit from EE
inherits(OTR.prototype._SMW, EventEmitter)
// shim sm methods
;['handleSM', 'rcvSecret', 'abort'].forEach(function (m) {
OTR.prototype._SMW.prototype[m] = function () {
this.worker.postMessage({
type: 'method'
, method: m
, args: Array.prototype.slice.call(arguments, 0)
})
}
})
OTR.prototype._smInit = function () {
var reqs = {
ssid: this.ssid
, our_fp: this.priv.fingerprint()
, their_fp: this.their_priv_pk.fingerprint()
, debug: this.debug
}
if (this.smw) {
if (this.sm) this.sm.worker.terminate() // destroy prev webworker
this.sm = new this._SMW(this, reqs)
} else {
this.sm = new SM(reqs)
}
var self = this
;['trust', 'abort', 'question'].forEach(function (e) {
self.sm.on(e, function () {
self.emit.apply(self, ['smp', e].concat(Array.prototype.slice.call(arguments)))
})
})
this.sm.on('send', function (ssid, send) {
if (self.ssid === ssid) {
send = self.prepareMsg(send)
self.io(send)
}
})
}
OTR.prototype.io = function (msg, meta, cb) {
// buffer
var queue = ([].concat(msg)).map(function(m, i, arr) {
return { msg: m, meta: meta }
})
var last = queue[queue.length - 1]
last.cb = cb
this.outgoing = this.outgoing.concat(queue)
var self = this
;(function send(first) {
if (!first) {
if (!self.outgoing.length) return
var elem = self.outgoing.shift()
self.emit('io', elem.msg, elem.meta)
if (elem.cb) elem.cb()
}
setTimeout(send, first ? 0 : self.send_interval)
}(true))
}
OTR.prototype.dh = function dh() {
var keys = { privateKey: BigInt.randBigInt(320) }
keys.publicKey = BigInt.powMod(G, keys.privateKey, N)
return keys
}
// session constructor
OTR.prototype.DHSession = function DHSession(our_dh, their_y) {
if (!(this instanceof DHSession)) return new DHSession(our_dh, their_y)
// shared secret
var s = BigInt.powMod(their_y, our_dh.privateKey, N)
var secbytes = HLP.packMPI(s)
// session id
this.id = HLP.mask(HLP.h2('\x00', secbytes), 0, 64) // first 64-bits
// are we the high or low end of the connection?
var sq = BigInt.greater(our_dh.publicKey, their_y)
var sendbyte = sq ? '\x01' : '\x02'
var rcvbyte = sq ? '\x02' : '\x01'
// sending and receiving keys
this.sendenc = HLP.mask(HLP.h1(sendbyte, secbytes), 0, 128) // f16 bytes
this.sendmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.sendenc))
this.sendmac = this.sendmac.toString(CryptoJS.enc.Latin1)
this.rcvenc = HLP.mask(HLP.h1(rcvbyte, secbytes), 0, 128)
this.rcvmac = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(this.rcvenc))
this.rcvmac = this.rcvmac.toString(CryptoJS.enc.Latin1)
this.rcvmacused = false
// extra symmetric key
this.extra_symkey = HLP.h2('\xff', secbytes)
// counters
this.send_counter = 0
this.rcv_counter = 0
}
OTR.prototype.rotateOurKeys = function () {
// reveal old mac keys
var self = this
this.sessKeys[1].forEach(function (sk) {
if (sk && sk.rcvmacused) self.oldMacKeys.push(sk.rcvmac)
})
// rotate our keys
this.our_old_dh = this.our_dh
this.our_dh = this.dh()
this.our_keyid += 1
this.sessKeys[1][0] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[0][1]
this.sessKeys[0] = [
this.their_y ?
new this.DHSession(this.our_dh, this.their_y) : null
, this.their_old_y ?
new this.DHSession(this.our_dh, this.their_old_y) : null
]
}
OTR.prototype.rotateTheirKeys = function (their_y) {
// increment their keyid
this.their_keyid += 1
// reveal old mac keys
var self = this
this.sessKeys.forEach(function (sk) {
if (sk[1] && sk[1].rcvmacused) self.oldMacKeys.push(sk[1].rcvmac)
})
// rotate their keys / session
this.their_old_y = this.their_y
this.sessKeys[0][1] = this.sessKeys[0][0]
this.sessKeys[1][1] = this.sessKeys[1][0]
// new keys / sessions
this.their_y = their_y
this.sessKeys[0][0] = new this.DHSession(this.our_dh, this.their_y)
this.sessKeys[1][0] = new this.DHSession(this.our_old_dh, this.their_y)
}
OTR.prototype.prepareMsg = function (msg, esk) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || this.their_keyid === 0)
return this.notify('Not ready to encrypt.')
var sessKeys = this.sessKeys[1][0]
if (sessKeys.send_counter >= MAX_INT)
return this.notify('Should have rekeyed by now.')
sessKeys.send_counter += 1
var ctr = HLP.packCtr(sessKeys.send_counter)
var send = this.ake.otr_version + '\x03' // version and type
var v3 = (this.ake.otr_version === CONST.OTR_VERSION_3)
if (v3) {
send += this.our_instance_tag
send += this.their_instance_tag
}
send += '\x00' // flag
send += HLP.packINT(this.our_keyid - 1)
send += HLP.packINT(this.their_keyid)
send += HLP.packMPI(this.our_dh.publicKey)
send += ctr.substring(0, 8)
if (Math.ceil(msg.length / 8) >= MAX_UINT) // * 16 / 128
return this.notify('Message is too long.')
var aes = HLP.encryptAes(
CryptoJS.enc.Latin1.parse(msg)
, sessKeys.sendenc
, ctr
)
send += HLP.packData(aes)
send += HLP.make1Mac(send, sessKeys.sendmac)
send += HLP.packData(this.oldMacKeys.splice(0).join(''))
send = HLP.wrapMsg(
send
, this.fragment_size
, v3
, this.our_instance_tag
, this.their_instance_tag
)
if (send[0]) return this.notify(send[0])
// emit extra symmetric key
if (esk) this.emit('file', 'send', sessKeys.extra_symkey, esk)
return send[1]
}
OTR.prototype.handleDataMsg = function (msg) {
var vt = msg.version + msg.type
if (this.ake.otr_version === CONST.OTR_VERSION_3)
vt += msg.instance_tags
var types = ['BYTE', 'INT', 'INT', 'MPI', 'CTR', 'DATA', 'MAC', 'DATA']
msg = HLP.splitype(types, msg.msg)
// ignore flag
var ign = (msg[0] === '\x01')
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED || msg.length !== 8) {
if (!ign) this.error('Received an unreadable encrypted message.')
return
}
var our_keyid = this.our_keyid - HLP.readLen(msg[2])
var their_keyid = this.their_keyid - HLP.readLen(msg[1])
if (our_keyid < 0 || our_keyid > 1) {
if (!ign) this.error('Not of our latest keys.')
return
}
if (their_keyid < 0 || their_keyid > 1) {
if (!ign) this.error('Not of your latest keys.')
return
}
var their_y = their_keyid ? this.their_old_y : this.their_y
if (their_keyid === 1 && !their_y) {
if (!ign) this.error('Do not have that key.')
return
}
var sessKeys = this.sessKeys[our_keyid][their_keyid]
var ctr = HLP.unpackCtr(msg[4])
if (ctr <= sessKeys.rcv_counter) {
if (!ign) this.error('Counter in message is not larger.')
return
}
sessKeys.rcv_counter = ctr
// verify mac
vt += msg.slice(0, 6).join('')
var vmac = HLP.make1Mac(vt, sessKeys.rcvmac)
if (!HLP.compare(msg[6], vmac)) {
if (!ign) this.error('MACs do not match.')
return
}
sessKeys.rcvmacused = true
var out = HLP.decryptAes(
msg[5].substring(4)
, sessKeys.rcvenc
, HLP.padCtr(msg[4])
)
out = out.toString(CryptoJS.enc.Latin1)
if (!our_keyid) this.rotateOurKeys()
if (!their_keyid) this.rotateTheirKeys(HLP.readMPI(msg[3]))
// parse TLVs
var ind = out.indexOf('\x00')
if (~ind) {
this.handleTLVs(out.substring(ind + 1), sessKeys)
out = out.substring(0, ind)
}
out = CryptoJS.enc.Latin1.parse(out)
return out.toString(CryptoJS.enc.Utf8)
}
OTR.prototype.handleTLVs = function (tlvs, sessKeys) {
var type, len, msg
for (; tlvs.length; ) {
type = HLP.unpackSHORT(tlvs.substr(0, 2))
len = HLP.unpackSHORT(tlvs.substr(2, 2))
msg = tlvs.substr(4, len)
// TODO: handle pathological cases better
if (msg.length < len) break
switch (type) {
case 1:
// Disconnected
this.msgstate = CONST.MSGSTATE_FINISHED
this.emit('status', CONST.STATUS_END_OTR)
break
case 2: case 3: case 4:
case 5: case 6: case 7:
// SMP
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED) {
if (this.sm) this.sm.abort()
return
}
if (!this.sm) this._smInit()
this.sm.handleSM({ msg: msg, type: type })
break
case 8:
// utf8 filenames
msg = msg.substring(4) // remove 4-byte indication
msg = CryptoJS.enc.Latin1.parse(msg)
msg = msg.toString(CryptoJS.enc.Utf8)
// Extra Symkey
this.emit('file', 'receive', sessKeys.extra_symkey, msg)
break
}
tlvs = tlvs.substring(4 + len)
}
}
OTR.prototype.smpSecret = function (secret, question) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.notify('Must be encrypted for SMP.')
if (typeof secret !== 'string' || secret.length < 1)
return this.notify('Secret is required.')
if (!this.sm) this._smInit()
// utf8 inputs
secret = CryptoJS.enc.Utf8.parse(secret).toString(CryptoJS.enc.Latin1)
if (question)
question = CryptoJS.enc.Utf8.parse(question).toString(CryptoJS.enc.Latin1)
this.sm.rcvSecret(secret, question)
}
OTR.prototype.sendQueryMsg = function () {
var versions = {}
, msg = CONST.OTR_TAG
if (this.ALLOW_V2) versions['2'] = true
if (this.ALLOW_V3) versions['3'] = true
// but we don't allow v1
// if (versions['1']) msg += '?'
var vs = Object.keys(versions)
if (vs.length) {
msg += 'v'
vs.forEach(function (v) {
if (v !== '1') msg += v
})
msg += '?'
}
this.io(msg)
this.emit('status', CONST.STATUS_SEND_QUERY)
}
OTR.prototype.sendMsg = function (msg, meta, cb) {
if (!cb && typeof meta === 'function') {
cb = meta
meta = null
}
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) {
msg = CryptoJS.enc.Utf8.parse(msg)
msg = msg.toString(CryptoJS.enc.Latin1)
}
switch (this.msgstate) {
case CONST.MSGSTATE_PLAINTEXT:
if (this.REQUIRE_ENCRYPTION) {
this.storedMgs.push({ msg: msg, meta: meta, cb: cb })
this.sendQueryMsg()
return
}
if (this.SEND_WHITESPACE_TAG && !this.receivedPlaintext) {
msg += CONST.WHITESPACE_TAG // 16 byte tag
if (this.ALLOW_V3) msg += CONST.WHITESPACE_TAG_V3
if (this.ALLOW_V2) msg += CONST.WHITESPACE_TAG_V2
}
break
case CONST.MSGSTATE_FINISHED:
this.storedMgs.push({ msg: msg, meta: meta, cb: cb })
this.notify('Message cannot be sent at this time.', 'warn')
return
case CONST.MSGSTATE_ENCRYPTED:
msg = this.prepareMsg(msg)
break
default:
throw new Error('Unknown message state.')
}
if (msg) this.io(msg, meta, cb)
}
OTR.prototype.receiveMsg = function (msg, meta) {
// parse type
msg = Parse.parseMsg(this, msg)
if (!msg) return
switch (msg.cls) {
case 'error':
this.notify(msg.msg)
return
case 'ake':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) {
this.notify(
'Received a message intended for a different session.', 'warn')
return // ignore
}
this.ake.handleAKE(msg)
return
case 'data':
if ( msg.version === CONST.OTR_VERSION_3 &&
this.checkInstanceTags(msg.instance_tags)
) {
this.notify(
'Received a message intended for a different session.', 'warn')
return // ignore
}
msg.msg = this.handleDataMsg(msg)
msg.encrypted = true
break
case 'query':
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) this._akeInit()
this.doAKE(msg)
break
default:
// check for encrypted
if ( this.REQUIRE_ENCRYPTION ||
this.msgstate !== CONST.MSGSTATE_PLAINTEXT
) this.notify('Received an unencrypted message.', 'warn')
// received a plaintext message
// stop sending the whitespace tag
this.receivedPlaintext = true
// received a whitespace tag
if (this.WHITESPACE_START_AKE && msg.ver.length > 0)
this.doAKE(msg)
}
if (msg.msg) this.emit('ui', msg.msg, !!msg.encrypted, meta)
}
OTR.prototype.checkInstanceTags = function (it) {
var their_it = HLP.readLen(it.substr(0, 4))
var our_it = HLP.readLen(it.substr(4, 4))
if (our_it && our_it !== HLP.readLen(this.our_instance_tag))
return true
if (HLP.readLen(this.their_instance_tag)) {
if (HLP.readLen(this.their_instance_tag) !== their_it) return true
} else {
if (their_it < 100) return true
this.their_instance_tag = HLP.packINT(their_it)
}
}
OTR.prototype.doAKE = function (msg) {
if (this.ALLOW_V3 && ~msg.ver.indexOf(CONST.OTR_VERSION_3)) {
this.ake.initiateAKE(CONST.OTR_VERSION_3)
} else if (this.ALLOW_V2 && ~msg.ver.indexOf(CONST.OTR_VERSION_2)) {
this.ake.initiateAKE(CONST.OTR_VERSION_2)
} else {
this.notify('OTR conversation requested, ' +
'but no compatible protocol version found.', 'warn')
}
}
OTR.prototype.error = function (err) {
if (!this.debug) err = 'An OTR error has occurred.'
this.io('?OTR Error:' + err)
this.notify(err)
}
OTR.prototype.notify = function (err, severity) {
severity = severity || 'error'
// TODO: remove last argument
this.emit(severity, err, severity)
}
OTR.prototype.sendStored = function () {
var self = this
;(this.storedMgs.splice(0)).forEach(function (elem) {
var msg = self.prepareMsg(elem.msg)
self.io(msg, elem.meta, elem.cb)
})
}
OTR.prototype.sendFile = function (filename) {
if (this.msgstate !== CONST.MSGSTATE_ENCRYPTED)
return this.notify('Not ready to encrypt.')
if (this.ake.otr_version !== CONST.OTR_VERSION_3)
return this.notify('Protocol v3 required.')
if (!filename) return this.notify('Please specify a filename.')
// utf8 filenames
var l1name = CryptoJS.enc.Utf8.parse(filename)
l1name = l1name.toString(CryptoJS.enc.Latin1)
if (l1name.length >= 65532) return this.notify('Filename is too long.')
var msg = '\x00' // null byte
msg += '\x00\x08' // type 8 tlv
msg += HLP.packSHORT(4 + l1name.length) // length of value
msg += '\x00\x00\x00\x01' // four bytes indicating file
msg += l1name
msg = this.prepareMsg(msg, filename)
this.io(msg)
}
OTR.prototype.endOtr = function (cb) {
if (this.msgstate === CONST.MSGSTATE_ENCRYPTED) {
this.sendMsg('\x00\x00\x01\x00\x00', cb)
if (this.sm) {
if (this.smw) this.sm.worker.terminate() // destroy webworker
this.sm = null
}
} else if (typeof cb === 'function')
setTimeout(cb, 0)
this.msgstate = CONST.MSGSTATE_PLAINTEXT
this.receivedPlaintext = false
this.emit('status', CONST.STATUS_END_OTR)
}
// attach methods
OTR.makeInstanceTag = function () {
var num = BigInt.randBigInt(32)
if (BigInt.greater(BigInt.str2bigInt('100', 16), num))
return OTR.makeInstanceTag()
return HLP.packINT(parseInt(BigInt.bigInt2str(num, 10), 10))
}
|
mvayngrib/otr
|
lib/otr.js
|
JavaScript
|
mpl-2.0
| 18,767
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Computed types for text properties.
#[cfg(feature = "servo")]
use properties::StyleBuilder;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
use values::{CSSInteger, CSSFloat};
use values::computed::{NonNegativeLength, NonNegativeNumber};
use values::computed::length::{Length, LengthOrPercentage};
use values::generics::text::InitialLetter as GenericInitialLetter;
use values::generics::text::LineHeight as GenericLineHeight;
use values::generics::text::Spacing;
use values::specified::text::{TextOverflowSide, TextDecorationLine};
pub use values::specified::TextAlignKeyword as TextAlign;
/// A computed value for the `initial-letter` property.
pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>;
/// A computed value for the `letter-spacing` property.
pub type LetterSpacing = Spacing<Length>;
/// A computed value for the `word-spacing` property.
pub type WordSpacing = Spacing<LengthOrPercentage>;
/// A computed value for the `line-height` property.
pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
/// text-overflow.
/// When the specified value only has one side, that's the "second"
/// side, and the sides are logical, so "second" means "end". The
/// start side is Clip in that case.
///
/// When the specified value has two sides, those are our "first"
/// and "second" sides, and they are physical sides ("left" and
/// "right").
pub struct TextOverflow {
/// First side
pub first: TextOverflowSide,
/// Second side
pub second: TextOverflowSide,
/// True if the specified value only has one side.
pub sides_are_logical: bool,
}
impl TextOverflow {
/// Returns the initial `text-overflow` value
pub fn get_initial_value() -> TextOverflow {
TextOverflow {
first: TextOverflowSide::Clip,
second: TextOverflowSide::Clip,
sides_are_logical: true,
}
}
}
impl ToCss for TextOverflow {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.sides_are_logical {
debug_assert_eq!(self.first, TextOverflowSide::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToCss for TextDecorationLine {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
let mut has_any = false;
macro_rules! write_value {
($line:path => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(TextDecorationLine::UNDERLINE => "underline");
write_value!(TextDecorationLine::OVERLINE => "overline");
write_value!(TextDecorationLine::LINE_THROUGH => "line-through");
write_value!(TextDecorationLine::BLINK => "blink");
if !has_any {
dest.write_str("none")?;
}
Ok(())
}
}
/// A struct that represents the _used_ value of the text-decoration property.
///
/// FIXME(emilio): This is done at style resolution time, though probably should
/// be done at layout time, otherwise we need to account for display: contents
/// and similar stuff when we implement it.
///
/// FIXME(emilio): Also, should be just a bitfield instead of three bytes.
#[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)]
pub struct TextDecorationsInEffect {
/// Whether an underline is in effect.
pub underline: bool,
/// Whether an overline decoration is in effect.
pub overline: bool,
/// Whether a line-through style is in effect.
pub line_through: bool,
}
impl TextDecorationsInEffect {
/// Computes the text-decorations in effect for a given style.
#[cfg(feature = "servo")]
pub fn from_style(style: &StyleBuilder) -> Self {
use values::computed::Display;
// Start with no declarations if this is an atomic inline-level box;
// otherwise, start with the declarations in effect and add in the text
// decorations that this block specifies.
let mut result = match style.get_box().clone_display() {
Display::InlineBlock |
Display::InlineTable => Self::default(),
_ => style.get_parent_inheritedtext().text_decorations_in_effect.clone(),
};
let text_style = style.get_text();
result.underline |= text_style.has_underline();
result.overline |= text_style.has_overline();
result.line_through |= text_style.has_line_through();
result
}
}
|
fiji-flo/servo
|
components/style/values/computed/text.rs
|
Rust
|
mpl-2.0
| 5,100
|
<!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_45) on Fri Dec 27 12:52:54 CST 2013 -->
<title>Message.Dispatcher (apache-cassandra API)</title>
<meta name="date" content="2013-12-27">
<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="Message.Dispatcher (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Message.Dispatcher.html">Use</a></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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/transport/Message.Direction.html" title="enum in org.apache.cassandra.transport"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/transport/Message.ProtocolDecoder.html" title="class in org.apache.cassandra.transport"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/transport/Message.Dispatcher.html" target="_top">Frames</a></li>
<li><a href="Message.Dispatcher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.transport</div>
<h2 title="Class Message.Dispatcher" class="title">Class Message.Dispatcher</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.jboss.netty.channel.SimpleChannelUpstreamHandler</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.transport.Message.Dispatcher</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>org.jboss.netty.channel.ChannelHandler, org.jboss.netty.channel.ChannelUpstreamHandler</dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/cassandra/transport/Message.html" title="class in org.apache.cassandra.transport">Message</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="strong">Message.Dispatcher</span>
extends org.jboss.netty.channel.SimpleChannelUpstreamHandler</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_org.jboss.netty.channel.ChannelHandler">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from interface org.jboss.netty.channel.ChannelHandler</h3>
<code>org.jboss.netty.channel.ChannelHandler.Sharable</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/transport/Message.Dispatcher.html#Message.Dispatcher()">Message.Dispatcher</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/transport/Message.Dispatcher.html#exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent)">exceptionCaught</a></strong>(org.jboss.netty.channel.ChannelHandlerContext ctx,
org.jboss.netty.channel.ExceptionEvent e)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/transport/Message.Dispatcher.html#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)">messageReceived</a></strong>(org.jboss.netty.channel.ChannelHandlerContext ctx,
org.jboss.netty.channel.MessageEvent e)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.jboss.netty.channel.SimpleChannelUpstreamHandler">
<!-- -->
</a>
<h3>Methods inherited from class org.jboss.netty.channel.SimpleChannelUpstreamHandler</h3>
<code>channelBound, channelClosed, channelConnected, channelDisconnected, channelInterestChanged, channelOpen, channelUnbound, childChannelClosed, childChannelOpen, handleUpstream, writeComplete</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Message.Dispatcher()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Message.Dispatcher</h4>
<pre>public Message.Dispatcher()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>messageReceived</h4>
<pre>public void messageReceived(org.jboss.netty.channel.ChannelHandlerContext ctx,
org.jboss.netty.channel.MessageEvent e)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>messageReceived</code> in class <code>org.jboss.netty.channel.SimpleChannelUpstreamHandler</code></dd>
</dl>
</li>
</ul>
<a name="exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>exceptionCaught</h4>
<pre>public void exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext ctx,
org.jboss.netty.channel.ExceptionEvent e)
throws java.lang.Exception</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>exceptionCaught</code> in class <code>org.jboss.netty.channel.SimpleChannelUpstreamHandler</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Message.Dispatcher.html">Use</a></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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/transport/Message.Direction.html" title="enum in org.apache.cassandra.transport"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/transport/Message.ProtocolDecoder.html" title="class in org.apache.cassandra.transport"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/transport/Message.Dispatcher.html" target="_top">Frames</a></li>
<li><a href="Message.Dispatcher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013 The Apache Software Foundation</small></p>
</body>
</html>
|
bkcloud/bkplatform
|
cassandra-scripts/javadoc/org/apache/cassandra/transport/Message.Dispatcher.html
|
HTML
|
mpl-2.0
| 11,743
|
require 'rspec'
require 'rack'
require 'rack/test'
require_relative 'magick_generator'
include RSpec::Matchers
include MagickGenerator
# delete previous temp directory !!
FileUtils.rm_rf "#{File.dirname(__FILE__)}/../../tmp/spec" if File.directory? "#{File.dirname(__FILE__)}/../../tmp/spec"
require_relative '../../lib/moviemasher.rb'
MovieMasher.configure "#{File.dirname(__FILE__)}/config.yml"
def spec_file dir, id_or_hash
if id_or_hash
if id_or_hash.is_a? String
id = id_or_hash
path = "#{File.dirname(__FILE__)}/media/json/#{dir}/#{id_or_hash}.json"
if File.exists? path
#puts "ID: #{id} HASH: #{id_or_hash}"
id_or_hash = JSON.parse(File.read path)
#puts "ID: #{id} FILE: #{id_or_hash}"
else
bits = id.split '-'
id_or_hash = Hash.new
id_or_hash[:name] = id_or_hash[:type] = bits.shift
case id_or_hash[:type]
when 'image'
id_or_hash[:quality] = '1'
ratio = bits.shift
size = bits.shift
id_or_hash[:dimensions] = MagickGenerator.const_get "#{size.upcase}#{ratio}".to_sym
end
id_or_hash[:extension] = bits.shift
end
end
end
MovieMasher::Job.symbolize_hash! id_or_hash
id_or_hash
end
def spec_job_from_files(input_id = nil, output_id = nil, destination_id = nil)
job = Hash.new
job[:log_level] = 'debug'
job[:inputs] = Array.new
job[:callbacks] = Array.new
job[:outputs] = Array.new
job[:destination] = spec_file('destinations', destination_id)
job[:inputs] << spec_file('inputs', input_id) if input_id
job[:outputs] << spec_file('outputs', output_id) if output_id
job
end
ModularMedia = Hash.new
def spec_modular_media
if ModularMedia.empty?
js_dir = "#{File.dirname(__FILE__)}/../../../angular-moviemasher/app/module"
js_dirs = Dir["#{js_dir}/*/*.json"]
js_dirs += Dir["#{js_dir}/*/*/*.json"]
js_dirs.each do |json_file|
json_text = File.read json_file
json_text = "[#{json_text}]" unless json_text.start_with? '['
medias = JSON.parse(json_text)
medias.each do |media|
MovieMasher::Job.symbolize_hash! media
ModularMedia[media[:id]] = media
end
end
#puts ModularMedia
end
ModularMedia
end
def spec_callback_file job
callback = job.callbacks.first
(callback ? callback[:callback_file] : nil)
end
def spec_output job
dest_path = job[:destination][:file]
if not (dest_path and File.exists?(dest_path))
callback_file = spec_callback_file job
dest_path = callback_file if callback_file
end
if dest_path and File.directory?(dest_path) then
dest_path = Dir["#{dest_path}/*"].first
#puts "DIR: #{dest_path}"
end
dest_path
end
def spec_job_data job_data
unless job_data[:base_source]
job_data[:base_source] = spec_file('sources', 'base_source_file')
job_data[:base_source][:directory] = File.dirname(File.dirname(__FILE__))
end
input = job_data[:inputs].first
if input and input[:source] and not input[:source].is_a?(String)
input[:source][:directory] = File.dirname(__FILE__)
end
if job_data[:destination] and not job_data[:destination][:directory]
job_data[:destination][:directory] = File.dirname(File.dirname(File.dirname(__FILE__)))
end
end
def spec_job(input_id = nil, output = 'video_h264', destination = 'file_log')
job_data = spec_job_from_files input_id, output, destination
if job_data
spec_job_data job_data
unless job_data[:id]
input = job_data[:inputs].first
job_data[:id] = input[:id] if input
end
job_data = MovieMasher::Job.new job_data
else
puts "SKIPPED #{input_id} - put angular-moviemasher repo alongside moviemasher.rb repo to test modules"
end
job_data
end
def expect_colors_video colors, video_file
color_frames = MagickGenerator.color_frames video_file
puts "#{color_frames}\n#{colors}" unless color_frames.length == colors.length
expect(color_frames.length).to eq colors.length
color_frames.length.times do |i|
reported_range = color_frames[i]
expected_range = colors[i]
next if reported_range == expected_range
expected_range = expected_range.dup
c = expected_range[:color]
expected_range[:color] = MagickGenerator.output_color(c, 'jpg')
next if reported_range == expected_range
expected_range[:color] = MagickGenerator.output_color(c, 'png')
expect(reported_range).to eq expected_range
end
end
def spec_generate_rgb_video options = nil
options = Hash.new unless options
options[:red] = 2 unless options[:red]
options[:green] = 2 unless options[:green]
options[:blue] = 2 unless options[:blue]
red_file = MagickGenerator.image_file :back => RED, :width => SM16x9W, :height => SM16x9H
green_file = MagickGenerator.image_file :back => GREEN, :width => SM16x9W, :height => SM16x9H
blue_file = MagickGenerator.image_file :back => BLUE, :width => SM16x9W, :height => SM16x9H
job = spec_job
job[:inputs] << {:length => options[:red], :id => "red", :source => red_file, :type => 'image'}
job[:inputs] << {:length => options[:green], :id => "green", :source => green_file, :type => 'image'}
job[:inputs] << {:length => options[:blue], :id => "blue", :source => blue_file, :type => 'image'}
job[:id] = Digest::SHA2.new(256).hexdigest(options.inspect)
rendered_video_path = spec_process_job job
fps = job[:outputs].first.video_rate.to_i
colors = Array.new
frame = 0
frames = options[:red] * fps
colors << { :color => RED, :frames => [0, frames] }
frame += frames
frames = options[:green] * fps
colors << { :color => GREEN, :frames => [frame, frames] }
frame += frames
frames = options[:blue] * fps
colors << { :color => BLUE, :frames => [frame, frames] }
expect_colors_video(colors, rendered_video_path)
rendered_video_path
end
def expect_color_video color, video_file
video_duration = MovieMasher::Info.get(video_file, 'duration').to_f
video_rate = MovieMasher::Info.get(video_file, 'fps').to_f
expect_colors_video [{:color => color, :frames => [0, (video_rate * video_duration).to_i]}], video_file
end
def spec_process_job_files(input_id, output = 'video_h264', destination = 'file_log')
job = spec_job(input_id, output, destination)
(job ? spec_process_job(job) : nil)
end
def spec_magick job
mod_media = nil
magick_path = "magick/"
job[:inputs].each do |input|
if MovieMasher::Input::TypeMash == input[:type]
mash = input[:mash]
if MovieMasher::Mash.hash? mash
referenced = Hash.new
MovieMasher::Mash::Tracks.each do |track_type|
mash[track_type.to_sym].each do |track|
MovieMasher::Mash.media_count_for_clips(mash, track[:clips], referenced)
end
end
expect(referenced.empty?).to be_false
referenced.each do |media_id, reference|
if reference[:media]
# generate it
src = reference[:media][:source]
if src.start_with? magick_path
reference[:media][:source] = MagickGenerator.generate src[magick_path.length..-1]
end
else
mod_media = spec_modular_media unless mod_media
return nil unless mod_media[media_id]
mash[:media] << mod_media[media_id]
end
end
end
else
# generate it
src = input[:source]
if src.is_a?(String) and src.start_with? magick_path
input[:source] = MagickGenerator.generate src[magick_path.length..-1]
end
end
end
end
def spec_process_job job, expect_error = nil
spec_magick job
job = MovieMasher.process job
if job[:error] and not expect_error
puts job[:error]
puts job[:commands]
end
puts job[:error] if job[:error] and (! job[:error]) != (! expect_error)
expect(! job[:error]).to eq ! expect_error
destination_file = spec_output job
expect(destination_file).to_not be_nil
expect(File.exists?(destination_file)).to be_true
output = job.outputs.first
if output
case output[:type]
when MovieMasher::Output::TypeAudio, MovieMasher::Output::TypeVideo
expect_duration destination_file, job[:duration]
end
input = job.inputs.first
if input and MovieMasher::Input::TypeMash == input[:type]
expect_dimensions(destination_file, output[:dimensions])
end
expect_fps(destination_file, output[:video_rate]) if MovieMasher::Output::TypeVideo == output[:type]
end
destination_file
end
def expect_color_image color, path
ext = File.extname(path)
ext = ext[1..-1]
expect(MagickGenerator.color_of_file path).to eq MagickGenerator.output_color(color, ext)
end
def expect_duration destination_file, duration
expect(MovieMasher::Info.get(destination_file, 'duration').to_f).to be_within(0.1).of duration
end
def expect_fps destination_file, fps
expect(MovieMasher::Info.get(destination_file, 'fps').to_i).to eq fps.to_i
end
def expect_dimensions destination_file, dimensions
expect(MovieMasher::Info.get(destination_file, 'dimensions')).to eq dimensions
end
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.include Rack::Test::Methods
config.after(:suite) do
end
end
|
sanyaade-mediadev/moviemasher.rb
|
spec/helpers/spec_helper.rb
|
Ruby
|
mpl-2.0
| 8,795
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `F_GETPIPE_SZ` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, F_GETPIPE_SZ">
<title>libc::notbsd::F_GETPIPE_SZ - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='../index.html'>libc</a>::<wbr><a href='index.html'>notbsd</a></p><script>window.sidebarCurrent = {name: 'F_GETPIPE_SZ', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>libc</a>::<wbr><a href='index.html'>notbsd</a>::<wbr><a class='constant' href=''>F_GETPIPE_SZ</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-1293' class='srclink' href='../../src/libc/unix/notbsd/mod.rs.html#207' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const F_GETPIPE_SZ: <a class='type' href='../../libc/type.c_int.html' title='libc::c_int'>c_int</a><code> = </code><code>1032</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "libc";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
libc/notbsd/constant.F_GETPIPE_SZ.html
|
HTML
|
mpl-2.0
| 4,411
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `GLOB_ABORTED` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, GLOB_ABORTED">
<title>libc::unix::notbsd::linux::GLOB_ABORTED - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>unix</a>::<wbr><a href='../index.html'>notbsd</a>::<wbr><a href='index.html'>linux</a></p><script>window.sidebarCurrent = {name: 'GLOB_ABORTED', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>unix</a>::<wbr><a href='../index.html'>notbsd</a>::<wbr><a href='index.html'>linux</a>::<wbr><a class='constant' href=''>GLOB_ABORTED</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-2326' class='srclink' href='../../../../src/libc/unix/notbsd/linux/mod.rs.html#356' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const GLOB_ABORTED: <a class='type' href='../../../../libc/type.c_int.html' title='libc::c_int'>c_int</a><code> = </code><code>2</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../../";
window.currentCrate = "libc";
window.playgroundUrl = "";
</script>
<script src="../../../../jquery.js"></script>
<script src="../../../../main.js"></script>
<script defer src="../../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
libc/unix/notbsd/linux/constant.GLOB_ABORTED.html
|
HTML
|
mpl-2.0
| 4,657
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Owner: david@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
var PE = require('../physics/PhysicsEngine');
var Particle = require('../physics/bodies/Particle');
var Spring = require('../physics/forces/Spring');
var Vector = require('../math/Vector');
/**
* SpringTransition is a method of transitioning between two values (numbers,
* or arrays of numbers) with a bounce. The transition will overshoot the target
* state depending on the parameters of the transition.
*
* @class SpringTransition
* @constructor
*
* @param {Number|Array} [state=0] Initial state
*/
function SpringTransition(state) {
state = state || 0;
this.endState = new Vector(state);
this.initState = new Vector();
this._dimensions = undefined;
this._restTolerance = 1e-10;
this._absRestTolerance = this._restTolerance;
this._callback = undefined;
this.PE = new PE();
this.spring = new Spring({anchor : this.endState});
this.particle = new Particle();
this.PE.addBody(this.particle);
this.PE.attach(this.spring, this.particle);
}
SpringTransition.SUPPORTS_MULTIPLE = 3;
/**
* @property SpringTransition.DEFAULT_OPTIONS
* @type Object
* @protected
* @static
*/
SpringTransition.DEFAULT_OPTIONS = {
/**
* The amount of time in milliseconds taken for one complete oscillation
* when there is no damping
* Range : [0, Infinity]
*
* @attribute period
* @type Number
* @default 300
*/
period : 300,
/**
* The damping of the snap.
* Range : [0, 1]
* 0 = no damping, and the spring will oscillate forever
* 1 = critically damped (the spring will never oscillate)
*
* @attribute dampingRatio
* @type Number
* @default 0.5
*/
dampingRatio : 0.5,
/**
* The initial velocity of the transition.
*
* @attribute velocity
* @type Number|Array
* @default 0
*/
velocity : 0
};
function _getEnergy() {
return this.particle.getEnergy() + this.spring.getEnergy(this.particle);
}
function _setParticlePosition(p) {
this.particle.setPosition(p);
}
function _setParticleVelocity(v) {
this.particle.setVelocity(v);
}
function _getParticlePosition() {
return (this._dimensions === 0)
? this.particle.getPosition1D()
: this.particle.getPosition();
}
function _getParticleVelocity() {
return (this._dimensions === 0)
? this.particle.getVelocity1D()
: this.particle.getVelocity();
}
function _setCallback(callback) {
this._callback = callback;
}
function _wake() {
this.PE.wake();
}
function _sleep() {
this.PE.sleep();
}
function _update() {
if (this.PE.isSleeping()) {
if (this._callback) {
var cb = this._callback;
this._callback = undefined;
cb();
}
return;
}
if (_getEnergy.call(this) < this._absRestTolerance) {
_setParticlePosition.call(this, this.endState);
_setParticleVelocity.call(this, [0,0,0]);
_sleep.call(this);
}
}
function _setupDefinition(definition) {
var defaults = SpringTransition.DEFAULT_OPTIONS;
if (definition.period === undefined) definition.period = defaults.period;
if (definition.dampingRatio === undefined) definition.dampingRatio = defaults.dampingRatio;
if (definition.velocity === undefined) definition.velocity = defaults.velocity;
if (definition.period < 150) {
definition.period = 150;
console.warn('The period of a SpringTransition is capped at 150 ms. Use a SnapTransition for faster transitions');
}
//setup spring
this.spring.setOptions({
period : definition.period,
dampingRatio : definition.dampingRatio
});
//setup particle
_setParticleVelocity.call(this, definition.velocity);
}
function _setAbsoluteRestTolerance() {
var distance = this.endState.sub(this.initState).normSquared();
this._absRestTolerance = (distance === 0)
? this._restTolerance
: this._restTolerance * distance;
}
function _setTarget(target) {
this.endState.set(target);
_setAbsoluteRestTolerance.call(this);
}
/**
* Resets the position and velocity
*
* @method reset
*
* @param {Number|Array.Number} pos positional state
* @param {Number|Array} vel velocity
*/
SpringTransition.prototype.reset = function reset(pos, vel) {
this._dimensions = (pos instanceof Array)
? pos.length
: 0;
this.initState.set(pos);
_setParticlePosition.call(this, pos);
_setTarget.call(this, pos);
if (vel) _setParticleVelocity.call(this, vel);
_setCallback.call(this, undefined);
};
/**
* Getter for velocity
*
* @method getVelocity
*
* @return {Number|Array} velocity
*/
SpringTransition.prototype.getVelocity = function getVelocity() {
return _getParticleVelocity.call(this);
};
/**
* Setter for velocity
*
* @method setVelocity
*
* @return {Number|Array} velocity
*/
SpringTransition.prototype.setVelocity = function setVelocity(v) {
this.call(this, _setParticleVelocity(v));
};
/**
* Detects whether a transition is in progress
*
* @method isActive
*
* @return {Boolean}
*/
SpringTransition.prototype.isActive = function isActive() {
return !this.PE.isSleeping();
};
/**
* Halt the transition
*
* @method halt
*/
SpringTransition.prototype.halt = function halt() {
this.set(this.get());
};
/**
* Get the current position of the transition
*
* @method get
*
* @return {Number|Array} state
*/
SpringTransition.prototype.get = function get() {
_update.call(this);
return _getParticlePosition.call(this);
};
/**
* Set the end position and transition, with optional callback on completion.
*
* @method set
*
* @param {Number|Array} endState Final state
* @param {Object} definition Transition definition
* @param {Function} callback Callback
*/
SpringTransition.prototype.set = function set(endState, definition, callback) {
if (!definition) {
this.reset(endState);
if (callback) callback();
return;
}
this._dimensions = (endState instanceof Array)
? endState.length
: 0;
_wake.call(this);
_setupDefinition.call(this, definition);
_setTarget.call(this, endState);
_setCallback.call(this, callback);
};
module.exports = SpringTransition;
|
mizchi/famous-bundled
|
transitions/SpringTransition.js
|
JavaScript
|
mpl-2.0
| 6,656
|
/// <reference path="BaseBattleDiff.ts"/>
module TK.SpaceTac {
/**
* A ship takes damage (to hull or shield)
*
* This is only informative, and does not apply the damage on ship values (there are ShipValueDiff for this).
*/
export class ShipDamageDiff extends BaseBattleShipDiff {
// Damage to hull
hull: number
// Damage to shield
shield: number
// Evaded damage
evaded: number
// Theoretical damage value
theoretical: number
constructor(ship: Ship, hull: number, shield: number, evaded = 0, theoretical = hull + shield + evaded) {
super(ship);
this.hull = hull;
this.shield = shield;
this.evaded = evaded;
this.theoretical = theoretical;
}
}
}
|
thunderk/spacetac
|
src/core/diffs/ShipDamageDiff.ts
|
TypeScript
|
mpl-2.0
| 824
|
"""URL routes for the sample app."""
from django.conf.urls import include, url
from django.views.generic import TemplateView
from rest_framework.routers import DefaultRouter
from .viewsets import ChoiceViewSet, QuestionViewSet, UserViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'questions', QuestionViewSet)
router.register(r'choices', ChoiceViewSet)
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='sample_poll_app/home.html'), name='home'),
url(r'^api-auth/', include(
'rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include(router.urls))
]
|
jwhitlock/drf-cached-instances
|
sample_poll_app/urls.py
|
Python
|
mpl-2.0
| 652
|
const Cu = Components.utils;
const {devtools} = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const {require} = devtools;
const {installHosted, installPackaged} = require("devtools/app-actor-front");
Cu.import("resource://gre/modules/devtools/dbg-server.jsm");
Cu.import("resource://gre/modules/devtools/dbg-client.jsm");
let gClient, gActor;
let gAppId = "actor-test";
let onDone = function () {
installPackaged(gClient, gActor, "/data/local/app.zip", gAppId)
.then(function ({ appId }) {
gClient.close();
marionetteScriptFinished("finished");
}, function (e) {
gClient.close();
marionetteScriptFinished("Failed install uploaded packaged app: " + e.error + ": " + e.message);
});
};
let connect = function(onDone) {
// Initialize a loopback remote protocol connection
if (!DebuggerServer.initialized) {
DebuggerServer.init(function () { return true; });
// We need to register browser actors to have `listTabs` working
// and also have a root actor
DebuggerServer.addBrowserActors();
}
// Setup the debugger client
gClient = new DebuggerClient(DebuggerServer.connectPipe());
gClient.connect(function onConnect() {
gClient.listTabs(function onListTabs(aResponse) {
gActor = aResponse.webappsActor;
onDone();
});
});
};
connect(onDone);
|
malini/certtest
|
device_setup/app_install.js
|
JavaScript
|
mpl-2.0
| 1,344
|
/* ***** BEGIN LICENSE BLOCK *****
;;
;; Copyright (c) 2009 Shannon Weyrick <weyrick@mozek.us>
;;
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
***** END LICENSE BLOCK *****
*/
#include "corvus/pPassManager.h"
#include "corvus/pPass.h"
#include "corvus/pSourceModule.h"
namespace corvus {
pPassManager::~pPassManager(void) {
// free passes
for (queueType::iterator i = passQueue_.begin();
i != passQueue_.end();
++i) {
delete *i;
}
}
void pPassManager::run(pSourceModule* mod, int verbosity) {
for (queueType::iterator i = passQueue_.begin();
i != passQueue_.end();
++i) {
if (verbosity > 1) {
std::cerr << "running pass [" << (*i)->name().str() << "] on " << mod->fileName() << std::endl;
}
(*i)->do_pre_run(mod);
if ((*i)->aborted())
return;
(*i)->do_run(mod);
if ((*i)->aborted())
return;
(*i)->do_post_run(mod);
}
}
void pPassManager::addPass(AST::pPass* p) {
p->setModel(model_);
passQueue_.push_back(p);
}
} // namespace
|
weyrick/corvus
|
corvus/pPassManager.cpp
|
C++
|
mpl-2.0
| 1,268
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `LARGEST_PBUFFER` constant in crate `glutin`.">
<meta name="keywords" content="rust, rustlang, rust-lang, LARGEST_PBUFFER">
<title>glutin::api::x11::ffi::glx_extra::LARGEST_PBUFFER - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../../../../index.html'>glutin</a>::<wbr><a href='../../../index.html'>api</a>::<wbr><a href='../../index.html'>x11</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>glx_extra</a></p><script>window.sidebarCurrent = {name: 'LARGEST_PBUFFER', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../../../../index.html'>glutin</a>::<wbr><a href='../../../index.html'>api</a>::<wbr><a href='../../index.html'>x11</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>glx_extra</a>::<wbr><a class='constant' href=''>LARGEST_PBUFFER</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-17299' class='srclink' href='../../../../../src/glutin///home/servo/buildbot/slave/doc/build/target/debug/build/glutin-3a49bc866bd01bfd/out/glx_extra_bindings.rs.html#453' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const LARGEST_PBUFFER: <a class='type' href='../../../../../glutin/api/x11/ffi/glx_extra/types/type.GLenum.html' title='glutin::api::x11::ffi::glx_extra::types::GLenum'>GLenum</a><code> = </code><code>0x801C</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../../../../";
window.currentCrate = "glutin";
window.playgroundUrl = "";
</script>
<script src="../../../../../jquery.js"></script>
<script src="../../../../../main.js"></script>
<script async src="../../../../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
glutin/api/x11/ffi/glx_extra/constant.LARGEST_PBUFFER.html
|
HTML
|
mpl-2.0
| 4,495
|
/*
This file is part of the MinSG library.
Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "TransparencyRenderer.h"
#include "../Nodes/AbstractCameraNode.h"
#include "../Nodes/GroupNode.h"
#include "../FrameContext.h"
#include <Rendering/RenderingContext/RenderingParameters.h>
#include <Rendering/RenderingContext/RenderingContext.h>
#include <Util/Macros.h>
#include <functional>
namespace MinSG {
TransparencyRenderer::TransparencyRenderer() : NodeRendererState(FrameContext::TRANSPARENCY_CHANNEL), nodes(), usePremultipliedAlpha(true) {
}
TransparencyRenderer::TransparencyRenderer(const TransparencyRenderer & source) :
NodeRendererState(source), nodes(), usePremultipliedAlpha(source.usePremultipliedAlpha) {
}
TransparencyRenderer::~TransparencyRenderer() = default;
void TransparencyRenderer::addNode(Node * n) {
if(!nodes) {
WARN("State not enabled");
} else {
nodes->insert(n);
}
}
State::stateResult_t TransparencyRenderer::doEnableState(FrameContext & context, Node * node, const RenderParam & rp) {
nodes.reset(new DistanceSetB2F<Node>(context.getCamera()->getWorldOrigin()));
return NodeRendererState::doEnableState(context, node, rp);
}
void TransparencyRenderer::doDisableState(FrameContext & context, Node * node, const RenderParam & rp) {
NodeRendererState::doDisableState(context, node, rp);
// No need to disable depth writing here because we are rendering in the correct order from back to front.
Rendering::BlendingParameters blend;
blend.enable();
blend.setBlendColor( Util::Color4f(1.0,1.0,1.0,0.5) );
if(usePremultipliedAlpha)
blend.setBlendFunc(Rendering::BlendingParameters::ONE, Rendering::BlendingParameters::ONE_MINUS_SRC_ALPHA);
else
blend.setBlendFunc(Rendering::BlendingParameters::SRC_ALPHA, Rendering::BlendingParameters::ONE_MINUS_SRC_ALPHA);
context.getRenderingContext().pushAndSetBlending(blend);
RenderParam childParams(rp);
childParams.setFlag(USE_WORLD_MATRIX);
childParams.setChannel(FrameContext::TRANSPARENCY_CHANNEL);
std::unique_ptr<DistanceSetB2F<Node>> tempNodes;
tempNodes.swap(nodes);
for (auto & elem : *tempNodes) {
if(elem == node) {
WARN("TransparencyRenderer is attached to a node that it shall display.\n" \
" This may be caused by a BlendingState attached to the same node.\n" \
" TransparencyRenderer has been disabled.\n ");
deactivate();
break;
} else {
elem->display(context, childParams);
}
}
context.getRenderingContext().popBlending();
}
NodeRendererResult TransparencyRenderer::displayNode(FrameContext &, Node * node, const RenderParam &) {
nodes->insert(node);
return NodeRendererResult::NODE_HANDLED;
}
TransparencyRenderer * TransparencyRenderer::clone() const {
return new TransparencyRenderer(*this);
}
}
|
PADrend/MinSG
|
Core/States/TransparencyRenderer.cpp
|
C++
|
mpl-2.0
| 3,164
|
/*
* Copyright (c) 2014. The Trustees of Indiana University.
*
* This version of the code is licensed under the MPL 2.0 Open Source license with additional
* healthcare disclaimer. If the user is an entity intending to commercialize any application
* that uses this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.view.forms;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.muzima.MuzimaApplication;
import com.muzima.R;
import com.muzima.adapters.forms.RegistrationFormsAdapter;
import com.muzima.api.model.Patient;
import com.muzima.controller.FormController;
import com.muzima.model.AvailableForm;
import com.muzima.model.collections.AvailableForms;
import com.muzima.view.BaseActivity;
import java.util.UUID;
public class RegistrationFormsActivity extends BaseActivity {
private ListView list;
private RegistrationFormsAdapter registrationFormsAdapter;
private String TAG = "RegistrationFormsActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_form_list);
FormController formController = ((MuzimaApplication) getApplicationContext()).getFormController();
AvailableForms availableForms = getRegistrationForms(formController);
if (isOnlyOneRegistrationForm(availableForms)) {
startWebViewActivity(availableForms.get(0));
} else {
prepareRegistrationAdapter(formController, availableForms);
}
}
private void prepareRegistrationAdapter(FormController formController, AvailableForms availableForms) {
registrationFormsAdapter = new RegistrationFormsAdapter(getApplicationContext(), R.layout.item_forms_list,
formController, availableForms);
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(startRegistrationOnClick());
list.setAdapter(registrationFormsAdapter);
registrationFormsAdapter.reloadData();
}
private boolean isOnlyOneRegistrationForm(AvailableForms availableForms) {
return availableForms.size() == 1;
}
private AdapterView.OnItemClickListener startRegistrationOnClick() {
return new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AvailableForm form = registrationFormsAdapter.getItem(position);
startWebViewActivity(form);
}
};
}
private void startWebViewActivity(AvailableForm form) {
Patient patient = new Patient();
String uuid = String.valueOf(UUID.randomUUID());
patient.setUuid(uuid);
startActivity(new FormViewIntent(this, form, patient));
}
private AvailableForms getRegistrationForms(FormController formController) {
AvailableForms availableForms = null;
try {
availableForms = formController.getDownloadedRegistrationForms();
} catch (FormController.FormFetchException e) {
Log.e(TAG, "Error while retrieving registration forms from Lucene");
}
return availableForms;
}
}
|
vijayakumarn/muzima-android
|
src/main/java/com/muzima/view/forms/RegistrationFormsActivity.java
|
Java
|
mpl-2.0
| 3,354
|
/*
* echocat Marquardt Java SDK, Copyright (c) 2015 echocat
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.echocat.marquardt.example;
import org.echocat.marquardt.common.exceptions.AlreadyLoggedInException;
import org.echocat.marquardt.common.exceptions.ClientNotAuthorizedException;
import org.echocat.marquardt.common.exceptions.LoginFailedException;
import org.echocat.marquardt.common.exceptions.NoSessionFoundException;
import org.echocat.marquardt.common.exceptions.UserAlreadyExistsException;
import org.echocat.marquardt.example.domain.PersistentUser;
import org.junit.Test;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
import static org.echocat.marquardt.authority.domain.UserStatus.CONFIRMED;
import static org.echocat.marquardt.authority.domain.UserStatus.WITHOUT_CREDENTIALS;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class AuthenticationIntegrationTest extends AbstractSsoIntegrationTest {
@Test
public void shouldSignInWithCorrectCredentials() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
thenCertificateIsProvided();
}
@Test(expected = LoginFailedException.class)
public void shouldRejectLoginWithIncorrectCredentials() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenIncorrectCredentials();
whenSigningIn();
}
@Test
public void shouldRejectLoginWhenUserIsLoggedIn() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
try { // Do not use @Test(expected = ) as the 1st sign-in invocation might as well throw this exception!
whenSigningIn();
fail("Expected " + AlreadyLoggedInException.class + " was not thrown!");
} catch (final AlreadyLoggedInException ignored) {}
}
/**
* No client id at all is defined for the test
*/
@Test(expected = ClientNotAuthorizedException.class)
public void shouldNotSignInWithCorrectCredentialsWhenClientIdIsUnknown() throws IOException {
givenExistingUser(Collections.emptySet());
givenCorrectCredentials();
whenSigningIn();
}
@Test(expected = ClientNotAuthorizedException.class)
public void shouldNotSignInWithCorrectCredentialsWhenClientIdProhibited() throws IOException {
givenProhibitedClientId();
givenExistingUser(Collections.emptySet());
givenCorrectCredentials();
whenSigningIn();
}
@Test
public void shouldInitializeSignUp() throws IOException {
givenCorrectCredentials();
givenClientIdIsAllowed();
whenInitializingSignUp();
thenCertificateIsProvided();
thenUserWithoutCredentialsWasCreated();
}
@Test
public void shouldFinalizeSignUp() throws IOException {
givenAccountDataWithCredentials();
givenClientIdIsAllowed();
givenEmptyUserAndSession();
whenFinalizingSignUp();
thenCertificateIsProvided();
thenUserWasEnrichedByAccountData();
}
@Test(expected = UserAlreadyExistsException.class)
public void shouldNotFinalizeSignUpWhenCredentialsAreInUseByExistingUser() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenAccountDataWithCredentials();
givenEmptyUserAndSession();
whenFinalizingSignUp();
}
@Test(expected = ClientNotAuthorizedException.class)
public void shouldNotFinalizeSignUpWhenClientIdIsUnknown() throws IOException {
givenAccountDataWithCredentials();
givenEmptyUserAndSession();
// No client id is set at all
whenFinalizingSignUp();
}
@Test(expected = ClientNotAuthorizedException.class)
public void shouldNotFinalizeSignUpWhenClientIdProhibited() throws IOException {
givenAccountDataWithCredentials();
givenEmptyUserAndSession();
givenProhibitedClientId();
whenFinalizingSignUp();
}
@Test
public void shouldLogoutAnLoggedInUser() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
whenLoggingOut();
thenCertificateIsProvided();
}
@Test
public void shouldRefreshCertificateOfSignedInUsers() throws IOException {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
whenRefreshingCertificate();
thenCertificateIsProvided();
}
@Test(expected = NoSessionFoundException.class)
public void shouldNotRefreshCertificatesOfUsersThatAreSignedOut() throws Exception {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
whenLoggingOut();
whenRefreshingCertificate();
}
@Test
public void shouldNotRefreshWhenClientIdIsProhibited() throws Exception {
givenExistingUser(Collections.emptySet());
givenClientIdIsAllowed();
givenCorrectCredentials();
whenSigningIn();
givenProhibitedClientId();
try { // Do not use @Test(expected = ) as sign-in might as well throw this exception!
whenRefreshingCertificate();
fail("Expected " + ClientNotAuthorizedException.class + " was not thrown!");
} catch (final ClientNotAuthorizedException ignored) {}
}
private void whenRefreshingCertificate() throws IOException {
//noinspection unchecked
setCertificate(getClient().refresh(_certificate));
}
private void thenCertificateIsProvided() {
assertThat(getCertificate(), is(not(nullValue())));
}
private void thenUserWithoutCredentialsWasCreated() {
final UUID userId = getCertificate().getPayload().getUserId();
final PersistentUser user = getUserRepository().findByUserId(userId).orElseThrow(() -> new IllegalStateException("Could not find expected user with id '" + userId + "'."));
assertThat(user.getStatus(), is(WITHOUT_CREDENTIALS));
assertThat(user.getEmail(), nullValue());
assertThat(user.getEncodedPassword(), nullValue());
assertThat(user.getLastName(), nullValue());
assertThat(user.getFirstName(), nullValue());
}
private void thenUserWasEnrichedByAccountData() {
final UUID userId = getCertificate().getPayload().getUserId();
final PersistentUser user = getUserRepository().findByUserId(userId).orElseThrow(() -> new IllegalStateException("Could not find expected user with id '" + userId + "'."));
assertThat(user.getStatus(), is(CONFIRMED));
assertThat(user.getEmail(), is(_signUpAccountData.getCredentials().getIdentifier()));
assertThat(user.getEncodedPassword(), notNullValue());
assertThat(user.getFirstName(), is(_signUpAccountData.getFirstName()));
assertThat(user.getLastName(), is(_signUpAccountData.getLastName()));
}
}
|
echocat/marquardt-java-sdk
|
example/src/test/java/org/echocat/marquardt/example/AuthenticationIntegrationTest.java
|
Java
|
mpl-2.0
| 7,682
|
package opc
import (
"fmt"
"github.com/hashicorp/go-oracle-terraform/compute"
"github.com/r3labs/terraform/helper/schema"
)
func resourceOPCSecurityAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceOPCSecurityAssociationCreate,
Read: resourceOPCSecurityAssociationRead,
Delete: resourceOPCSecurityAssociationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"vcable": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"seclist": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceOPCSecurityAssociationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*compute.Client).SecurityAssociations()
name := d.Get("name").(string)
vcable := d.Get("vcable").(string)
seclist := d.Get("seclist").(string)
input := compute.CreateSecurityAssociationInput{
Name: name,
SecList: seclist,
VCable: vcable,
}
info, err := client.CreateSecurityAssociation(&input)
if err != nil {
return fmt.Errorf("Error creating security association between vcable %s and security list %s: %s", vcable, seclist, err)
}
d.SetId(info.Name)
return resourceOPCSecurityAssociationRead(d, meta)
}
func resourceOPCSecurityAssociationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*compute.Client).SecurityAssociations()
name := d.Id()
input := compute.GetSecurityAssociationInput{
Name: name,
}
result, err := client.GetSecurityAssociation(&input)
if err != nil {
// Security Association does not exist
if compute.WasNotFoundError(err) {
d.SetId("")
return nil
}
return fmt.Errorf("Error reading security association %s: %s", name, err)
}
d.Set("name", result.Name)
d.Set("seclist", result.SecList)
d.Set("vcable", result.VCable)
return nil
}
func resourceOPCSecurityAssociationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*compute.Client).SecurityAssociations()
name := d.Id()
input := compute.DeleteSecurityAssociationInput{
Name: name,
}
if err := client.DeleteSecurityAssociation(&input); err != nil {
return fmt.Errorf("Error deleting Security Association '%s': %v", name, err)
}
return nil
}
|
r3labs/terraform
|
vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_association.go
|
GO
|
mpl-2.0
| 2,430
|
package google
import (
"fmt"
"testing"
"strconv"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccContainerCluster_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_basic,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.primary"),
),
},
},
})
}
func TestAccContainerCluster_withAdditionalZones(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_withAdditionalZones,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.with_additional_zones"),
testAccCheckContainerClusterAdditionalZonesExist(
"google_container_cluster.with_additional_zones", 2),
),
},
},
})
}
func TestAccContainerCluster_withVersion(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_withVersion,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.with_version"),
),
},
},
})
}
func TestAccContainerCluster_withNodeConfig(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_withNodeConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.with_node_config"),
),
},
},
})
}
func TestAccContainerCluster_withNodeConfigScopeAlias(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_withNodeConfigScopeAlias,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.with_node_config_scope_alias"),
),
},
},
})
}
func TestAccContainerCluster_network(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_networkRef,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.with_net_ref_by_url"),
testAccCheckContainerClusterExists(
"google_container_cluster.with_net_ref_by_name"),
),
},
},
})
}
func TestAccContainerCluster_backend(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckContainerClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccContainerCluster_backendRef,
Check: resource.ComposeTestCheckFunc(
testAccCheckContainerClusterExists(
"google_container_cluster.primary"),
),
},
},
})
}
func testAccCheckContainerClusterDestroy(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
for _, rs := range s.RootModule().Resources {
if rs.Type != "google_container_cluster" {
continue
}
attributes := rs.Primary.Attributes
_, err := config.clientContainer.Projects.Zones.Clusters.Get(
config.Project, attributes["zone"], attributes["name"]).Do()
if err == nil {
return fmt.Errorf("Cluster still exists")
}
}
return nil
}
func testAccCheckContainerClusterExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
attributes := rs.Primary.Attributes
found, err := config.clientContainer.Projects.Zones.Clusters.Get(
config.Project, attributes["zone"], attributes["name"]).Do()
if err != nil {
return err
}
if found.Name != attributes["name"] {
return fmt.Errorf("Cluster not found")
}
return nil
}
}
func testAccCheckContainerClusterAdditionalZonesExist(n string, num int) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
additionalZonesSize, err := strconv.Atoi(rs.Primary.Attributes["additional_zones.#"])
if err != nil {
return err
}
if additionalZonesSize != num {
return fmt.Errorf("number of additional zones did not match %d, was %d", num, additionalZonesSize)
}
return nil
}
}
var testAccContainerCluster_basic = fmt.Sprintf(`
resource "google_container_cluster" "primary" {
name = "cluster-test-%s"
zone = "us-central1-a"
initial_node_count = 3
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
}`, acctest.RandString(10))
var testAccContainerCluster_withAdditionalZones = fmt.Sprintf(`
resource "google_container_cluster" "with_additional_zones" {
name = "cluster-test-%s"
zone = "us-central1-a"
initial_node_count = 1
additional_zones = [
"us-central1-b",
"us-central1-c"
]
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
}`, acctest.RandString(10))
var testAccContainerCluster_withVersion = fmt.Sprintf(`
resource "google_container_cluster" "with_version" {
name = "cluster-test-%s"
zone = "us-central1-a"
node_version = "1.5.2"
initial_node_count = 1
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
}`, acctest.RandString(10))
var testAccContainerCluster_withNodeConfig = fmt.Sprintf(`
resource "google_container_cluster" "with_node_config" {
name = "cluster-test-%s"
zone = "us-central1-f"
initial_node_count = 1
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
node_config {
machine_type = "g1-small"
disk_size_gb = 15
oauth_scopes = [
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring"
]
}
}`, acctest.RandString(10))
var testAccContainerCluster_withNodeConfigScopeAlias = fmt.Sprintf(`
resource "google_container_cluster" "with_node_config_scope_alias" {
name = "cluster-test-%s"
zone = "us-central1-f"
initial_node_count = 1
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
node_config {
machine_type = "g1-small"
disk_size_gb = 15
oauth_scopes = [ "compute-rw", "storage-ro", "logging-write", "monitoring" ]
}
}`, acctest.RandString(10))
var testAccContainerCluster_networkRef = fmt.Sprintf(`
resource "google_compute_network" "container_network" {
name = "container-net-%s"
auto_create_subnetworks = true
}
resource "google_container_cluster" "with_net_ref_by_url" {
name = "cluster-test-%s"
zone = "us-central1-a"
initial_node_count = 1
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
network = "${google_compute_network.container_network.self_link}"
}
resource "google_container_cluster" "with_net_ref_by_name" {
name = "cluster-test-%s"
zone = "us-central1-a"
initial_node_count = 1
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
network = "${google_compute_network.container_network.name}"
}`, acctest.RandString(10), acctest.RandString(10), acctest.RandString(10))
var testAccContainerCluster_backendRef = fmt.Sprintf(`
resource "google_compute_backend_service" "my-backend-service" {
name = "terraform-test-%s"
port_name = "http"
protocol = "HTTP"
backend {
group = "${element(google_container_cluster.primary.instance_group_urls, 1)}"
}
health_checks = ["${google_compute_http_health_check.default.self_link}"]
}
resource "google_compute_http_health_check" "default" {
name = "terraform-test-%s"
request_path = "/"
check_interval_sec = 1
timeout_sec = 1
}
resource "google_container_cluster" "primary" {
name = "terraform-test-%s"
zone = "us-central1-a"
initial_node_count = 3
additional_zones = [
"us-central1-b",
"us-central1-c",
]
master_auth {
username = "mr.yoda"
password = "adoy.rm"
}
node_config {
oauth_scopes = [
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring",
]
}
}
`, acctest.RandString(10), acctest.RandString(10), acctest.RandString(10))
|
mikesplain/terraform
|
builtin/providers/google/resource_container_cluster_test.go
|
GO
|
mpl-2.0
| 9,428
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Liberally derived from the [Firefox JS implementation]
//! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js).
//! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents.
//! Supports dynamic attaching and detaching which control notifications of navigation, etc.
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::actors::console::ConsoleActor;
use crate::protocol::JsonPacketStream;
use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications};
use serde_json::{Map, Value};
use std::net::TcpStream;
#[derive(Serialize)]
struct BrowsingContextTraits;
#[derive(Serialize)]
struct BrowsingContextAttachedReply {
from: String,
#[serde(rename = "type")]
type_: String,
threadActor: String,
cacheDisabled: bool,
javascriptEnabled: bool,
traits: BrowsingContextTraits,
}
#[derive(Serialize)]
struct BrowsingContextDetachedReply {
from: String,
#[serde(rename = "type")]
type_: String,
}
#[derive(Serialize)]
struct ReconfigureReply {
from: String,
}
#[derive(Serialize)]
struct ListFramesReply {
from: String,
frames: Vec<FrameMsg>,
}
#[derive(Serialize)]
struct FrameMsg {
id: u32,
url: String,
title: String,
parentID: u32,
}
#[derive(Serialize)]
struct ListWorkersReply {
from: String,
workers: Vec<WorkerMsg>,
}
#[derive(Serialize)]
struct WorkerMsg {
id: u32,
}
#[derive(Serialize)]
pub struct BrowsingContextActorMsg {
actor: String,
title: String,
url: String,
outerWindowID: u32,
consoleActor: String,
emulationActor: String,
inspectorActor: String,
timelineActor: String,
profilerActor: String,
performanceActor: String,
styleSheetsActor: String,
}
pub struct BrowsingContextActor {
pub name: String,
pub title: String,
pub url: String,
pub console: String,
pub emulation: String,
pub inspector: String,
pub timeline: String,
pub profiler: String,
pub performance: String,
pub styleSheets: String,
pub thread: String,
}
impl Actor for BrowsingContextActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(
&self,
registry: &ActorRegistry,
msg_type: &str,
msg: &Map<String, Value>,
stream: &mut TcpStream,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"reconfigure" => {
if let Some(options) = msg.get("options").and_then(|o| o.as_object()) {
if let Some(val) = options.get("performReload") {
if val.as_bool().unwrap_or(false) {
let console_actor = registry.find::<ConsoleActor>(&self.console);
let _ = console_actor
.script_chan
.send(DevtoolScriptControlMsg::Reload(console_actor.pipeline));
}
}
}
stream.write_json_packet(&ReconfigureReply { from: self.name() });
ActorMessageStatus::Processed
},
// https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs
// (see "To attach to a _targetActor_")
"attach" => {
let msg = BrowsingContextAttachedReply {
from: self.name(),
type_: "targetAttached".to_owned(),
threadActor: self.thread.clone(),
cacheDisabled: false,
javascriptEnabled: true,
traits: BrowsingContextTraits,
};
let console_actor = registry.find::<ConsoleActor>(&self.console);
console_actor
.streams
.borrow_mut()
.push(stream.try_clone().unwrap());
stream.write_json_packet(&msg);
console_actor
.script_chan
.send(WantsLiveNotifications(console_actor.pipeline, true))
.unwrap();
ActorMessageStatus::Processed
},
//FIXME: The current implementation won't work for multiple connections. Need to ensure 105
// that the correct stream is removed.
"detach" => {
let msg = BrowsingContextDetachedReply {
from: self.name(),
type_: "detached".to_owned(),
};
let console_actor = registry.find::<ConsoleActor>(&self.console);
console_actor.streams.borrow_mut().pop();
stream.write_json_packet(&msg);
console_actor
.script_chan
.send(WantsLiveNotifications(console_actor.pipeline, false))
.unwrap();
ActorMessageStatus::Processed
},
"listFrames" => {
let msg = ListFramesReply {
from: self.name(),
frames: vec![],
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"listWorkers" => {
let msg = ListWorkersReply {
from: self.name(),
workers: vec![],
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
impl BrowsingContextActor {
pub fn encodable(&self) -> BrowsingContextActorMsg {
BrowsingContextActorMsg {
actor: self.name(),
title: self.title.clone(),
url: self.url.clone(),
outerWindowID: 0, //FIXME: this should probably be the pipeline id
consoleActor: self.console.clone(),
emulationActor: self.emulation.clone(),
inspectorActor: self.inspector.clone(),
timelineActor: self.timeline.clone(),
profilerActor: self.profiler.clone(),
performanceActor: self.performance.clone(),
styleSheetsActor: self.styleSheets.clone(),
}
}
}
|
jimberlage/servo
|
components/devtools/actors/browsing_context.rs
|
Rust
|
mpl-2.0
| 6,555
|
/*
* Copyright (C) 2016 - 2019 DataSwift Ltd - All Rights Reserved
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Written by Augustinas Markevicius <augustinas.markevicius@dataswift.io> 2016
*/
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { ProfilesService } from './profiles.service';
import { AuthService } from '../core/services/auth.service';
import { HatApiService } from '../core/services/hat-api.service';
import { APP_CONFIG } from '../app.config';
import { of } from 'rxjs';
describe('ProfilesService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ProfilesService,
{ provide: HatApiService, useValue: {} },
{ provide: AuthService, useValue: {
auth$: of(false)
} },
{ provide: APP_CONFIG, useValue: {} }
]
});
});
it('should ...', inject([ProfilesService], (service: ProfilesService) => {
expect(service).toBeTruthy();
}));
});
|
Hub-of-all-Things/Rumpel
|
src/app/profiles/profiles.service.spec.ts
|
TypeScript
|
mpl-2.0
| 1,176
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html data-context="Build Apps" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>le_sls_List_t Struct Reference - Legato Docs</title>
<meta content="legato™ is an open source Linux-based embedded platform designed to simplify connected IoT application development" name="description"/>
<meta content="legato, iot" name="keywords"/>
<meta content="16.04.0-external-5-g7c8a4e3" name="legato-version"/>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>
<link href="resources/images/legato.ico" rel="shortcut icon"/>
<link href="resources/images/legato.ico" rel="icon" type="image/x-icon"/>
<link href="resources/images/legato.ico" rel="shortcut icon" type="image/x-icon"/>
<link href="resources/images/legato.ico" rel="apple-touch-icon" type="image/x-icon"/>
<link href="resources/css/style.css" media="screen" rel="stylesheet" type="text/css"/>
<link href="resources/css/jqtree.css" rel="stylesheet" type="text/css"/>
<link href="resources/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<!--[if IE]>
<script src="resources/js/html5shiv.js"></script>
<![endif]-->
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="resources/js/main.js"></script>
<script src="tocs/Build Apps API Guides.json"></script>
</head>
<body>
<noscript>
<input class="modal-closing-trick" id="modal-closing-trick" type="checkbox"/>
<div id="nojs">
<label for="modal-closing-trick">
<span>You seem to not have Javascript <a href="http://enable-javascript.com">enabled</a>, so site functionality like the search and navigation tree won't work.</span>
</label>
</div>
</noscript>
<div class="wrapper">
<div class="fa fa-bars documentation" id="menu-trigger"></div>
<div id="top">
<header>
<nav>
<a class="navlink" href="/index.html">Introduction</a><a class="navlink selected" href="buildAppsMain.html">Build Apps</a><a class="navlink" href="buildPlatformMain.html">Build Platform</a><a class="navlink" href="aboutMain.html">About</a>
</nav>
</header>
</div>
<div class="white" id="menudocumentation">
<header>
<a href="/"> <img alt="Back to Legato Homepage" id="logo" src="resources/images/legato_logo.png"/></a>
<h2>/ Build Apps</h2>
<nav class="secondary">
<a href="buildAppsConcepts.html">Concepts</a><a class="link-selected" href="apiGuidesMain.html">API Guides</a><a href="tools.html">Tools</a><a href="external_proj_mainpage.html">WiFi Plugin</a>
</nav>
<nav class="ui-front">
<i class="fa fa-search" id="search-icon"></i>
<input id="searchbox" placeholder="Search"/>
</nav>
</header>
</div>
<div id="resizable">
<div id="left">
<div id="tree1"></div>
</div>
</div>
<div class="content">
<div class="header">
<div class="summary">
<a href="#pub-attribs">Data Fields</a> </div>
<div class="headertitle">
<h1 class="title">le_sls_List_t Struct Reference</h1> </div>
</div><div class="contents">
<p><code>#include <<a class="el" href="le__singly_linked_list_8h_source.html">le_singlyLinkedList.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Data Fields</h2></td></tr>
<tr class="memitem:a696f83142673b69689c6dcf750a09e4a"><td align="right" class="memItemLeft" valign="top"><a class="anchor" id="a696f83142673b69689c6dcf750a09e4a"></a>
<a class="el" href="structle__sls___link__t.html">le_sls_Link_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="structle__sls___list__t.html#a696f83142673b69689c6dcf750a09e4a">tailLinkPtr</a></td></tr>
<tr class="memdesc:a696f83142673b69689c6dcf750a09e4a"><td class="mdescLeft"> </td><td class="mdescRight">Tail link pointer. <br/></td></tr>
<tr class="separator:a696f83142673b69689c6dcf750a09e4a"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a id="details" name="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>This is the list object. Create this list object and initialize it by assigning LE_SLS_LIST_INIT to it.</p>
<dl class="section warning"><dt>Warning</dt><dd>DON'T access the contents of this structure directly. </dd></dl>
</div><hr/>The documentation for this struct was generated from the following file:<ul>
<li><a class="el" href="le__singly_linked_list_8h_source.html">le_singlyLinkedList.h</a></li>
</ul>
</div>
<br clear="left"/>
</div>
</div>
<script src="resources/js/tree.jquery.js" type="text/javascript"></script>
<script src="resources/js/jquery.cookie.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="resources/css/perfect-scrollbar.min.css" rel="stylesheet"/>
<script src="resources/js/perfect-scrollbar.jquery.min.js"></script>
</body>
</html>
|
legatoproject/legato-docs
|
16_04/structle__sls___list__t.html
|
HTML
|
mpl-2.0
| 4,930
|
function (user, context, callback) {
// /!\ DO NOT EDIT THIS FILE /!\
// Please use http://github.com/mozilla-iam/auth0-rules instead
var WHITELIST = [
'moc-sso-monitoring@mozilla.com', // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903
'moc+servicenow@mozilla.com' // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903
];
if (!user.email_verified) {
console.log('duosecurity: user primary email NOT verified, refusing login for '+user.email);
return callback(null, user, global.postError('notingroup', context));
}
if (WHITELIST.indexOf(user.email) >= 0) {
console.log('duosecurity: whitelisted account '+user.email+', no 2FA check performed');
// Fake 2FA
context.multifactor = true;
return callback(null, user, context);
}
// Any user logging in with LDAP (ad) requires MFA authentication.
if (context.connectionStrategy === 'ad') {
context.multifactor = {
provider: 'duo',
ikey: configuration.duo_ikey_mozilla,
skey: configuration.duo_skey_mozilla,
host: configuration.duo_apihost_mozilla,
// optional:
// Force DuoSecurity everytime this rule runs. Defaults to false.
// If accepted by users the cookie lasts for 30 days - i.e. 30 days MFA session (this cannot be changed)
ignoreCookie: false,
username: user.email,
};
}
callback(null, user, context);
}
|
jdow/auth0-deploy
|
rules/duosecurity.js
|
JavaScript
|
mpl-2.0
| 1,403
|
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Sanford.Multimedia.Midi;
namespace PividMidi.Model
{
public abstract class Control : INotifyPropertyChanged
{
private int _value;
/// <summary>
/// Nom du contrôle
/// </summary>
public string Name { get; set; }
/// <summary>
/// Numéro de voie MIDI
/// </summary>
public int ChannelID { get; set; }
/// <summary>
/// Type de contrôle
/// </summary>
public ControlType Type { get; set; }
/// <summary>
/// valeur courante du contrôle
/// </summary>
public int Value
{
get { return _value; }
set
{
_value = value;
OnPropertyChanged();
if (Type == ControlType.BottomButton || Type == ControlType.MatrixButton || Type == ControlType.RightButton)
{
ApcMiniController.setLed(ChannelID, _value);
}
ApcMiniController.sendMidi(this);
}
}
/// <summary>
/// Représente en les note ON et OFF des messages midi
/// </summary>
public bool State { get; set; }
public APCMiniController ApcMiniController { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public enum ControlType
{
Fader,
MatrixButton,
BottomButton,
RightButton,
ShiftButton
}
}
|
Nexyll/PividMidi
|
PividMidi/PividMidi/Model/Control.cs
|
C#
|
mpl-2.0
| 1,797
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XKB_KEY_Ukranian_I` constant in crate `wayland_kbd`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_Ukranian_I">
<title>wayland_kbd::keysyms::XKB_KEY_Ukranian_I - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_Ukranian_I', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_Ukranian_I</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-2744' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#1154' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XKB_KEY_Ukranian_I: <a href='../../std/primitive.u32.html'>u32</a><code> = </code><code>0x06b6</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "wayland_kbd";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
wayland_kbd/keysyms/constant.XKB_KEY_Ukranian_I.html
|
HTML
|
mpl-2.0
| 4,002
|
/*
* Simple positive sanity test on watchdog chain.
*
* These tests do not ensure proper functioning of watchdog chain, just that a properly configured
* watchdog chain does not interfere with normal operation.
*
* Copyright (C) Sierra Wireless Inc.
*/
#include "legato.h"
#include "watchdogChain.h"
// Number of times to test kicking watchdog. Needs to be such that KICK_COUNT*SLEEP_TIME is
// greater than watchdog timeout (5s)
#define KICK_COUNT 5
// Amount of time between kicks (in seconds)
#define SLEEP_TIME 2
COMPONENT_INIT
{
int i;
// On failure program will exit, so all tests are LE_TEST_OK(true, ...)
LE_TEST_PLAN(1 + 2*KICK_COUNT);
le_wdogChain_Init(4);
LE_TEST_OK(true, "watchdog chain initialized");
for (i = 0; i < KICK_COUNT; ++i)
{
le_wdogChain_Kick((0 + i) % 4);
le_wdogChain_Kick((1 + i) % 4);
le_wdogChain_Kick((2 + i) % 4);
le_wdogChain_Kick((3 + i) % 4);
le_thread_Sleep(SLEEP_TIME);
LE_TEST_OK(true, "4/4 active watchdogs: program running after %d seconds", (i+1)*2);
}
le_wdogChain_Stop(0);
le_wdogChain_Stop(1);
le_wdogChain_Stop(2);
for (i = 0; i < KICK_COUNT; ++i)
{
le_wdogChain_Kick(3);
le_thread_Sleep(SLEEP_TIME);
LE_TEST_OK(true, "1/4 active watchdogs: program running after %d seconds", (i+1)*2);
}
LE_TEST_EXIT;
}
|
legatoproject/legato-af
|
components/test/watchdogChain/watchdogComponent/watchdogChain.c
|
C
|
mpl-2.0
| 1,393
|
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec referrer-policy/` -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'no-referrer-when-downgrade'</title>
<meta charset='utf-8'>
<meta name="description" content="Check that non a priori insecure subresource gets the full Referrer URL. A priori insecure subresource gets no referrer information.">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-no-referrer-when-downgrade">
<meta name="assert" content="Referrer Policy: Expects stripped-referrer for iframe-tag to cross-http origin and swap-origin redirection from http context.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="../../../../generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "stripped-referrer",
"origin": "cross-http",
"redirection": "swap-origin",
"source_context_list": [],
"source_scheme": "http",
"subresource": "iframe-tag",
"subresource_policy_deliveries": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
|
UK992/servo
|
tests/wpt/web-platform-tests/referrer-policy/gen/top.http-rp/no-referrer-when-downgrade/iframe-tag/cross-http.swap-origin.http.html
|
HTML
|
mpl-2.0
| 1,553
|
# coding: utf-8
class Project < ActiveRecord::Base
attribute :images, ArrayType.new
mount_uploaders :images, ImageUploader
serialize :images, JSON
validates :subject, presence: true
has_many :project_updates
belongs_to :user
has_and_belongs_to_many :users
has_and_belongs_to_many :skills
belongs_to :stage
belongs_to :project
has_many :projects
scope :recent, -> { order(last_commented_at: 'desc') }
scope :recruiting, -> { where.not(stage_id: 13) }
scope :match_skills, lambda { |skill_ids|
where.not(stage_id: 13)
.includes(:skills)
.where(skills: { id: skill_ids })
}
scope :original_order, lambda { |ids|
if Array(ids).empty?
where(id: [])
else
where(id: ids).order("field(id, #{ids.join(',')})")
end
}
def self.comment_ranking(before)
Project
.joins(:project_updates)
.where(
project_updates: {
created_at: Time.now.ago(30.years)...before
}
)
.group('project_updates.project_id')
.order('count_project_updates_project_id desc')
.count('project_updates.project_id')
end
# プロジェクトを編集可能なユーザーかどうか
# @param [Integer] user_id
# @return [Boolean]
def editable_user_id?(user_id)
if user_id == self.user_id
return true
else
return false
end
end
# 必要なスキルを更新
# @param [Array] skill_names スキル名の配列
# @return [Boolean]
def update_skill_ids_by_skill_names(skill_names)
@before_skill_ids = skills.map(&:id)
@after_skill_ids = []
skill_names.compact.uniq.reject(&:empty?).each do |skill_name|
skill = Skill.find_by(name: skill_name)
if skill.nil?
skill = Skill.create(name: skill_name)
end
@after_skill_ids.push(skill.id)
end
# 追加
(@after_skill_ids - @before_skill_ids).each do |skill_id|
skills << Skill.find(skill_id)
end
# 削除
(@before_skill_ids - @after_skill_ids).each do |skill_id|
skills.delete(skill_id)
end
end
# メールを送るユーザーを取得
def send_mail_users
send_users = users
me = user
# 自分がいない場合には含める
if send_users.select { |u| u['user_id'] == me['user_id'] }.empty?
send_users.push me
end
# すべてを受け取るユーザーを追加
User.where(receive_all: 1).pluck(:email).compact each do |u|
send_users.push u
end
send_users
end
def send_mail_addresses
send_targets = users.pluck(:email).compact
me = user.email
# 自分がいない場合には含める
if send_targets.include?(me)
send_targets.push me
end
# すべてを受け取るユーザーを追加
User.where(receive_all: 1).pluck(:email).compact.each do |u|
send_targets.push u
end
send_targets.uniq
end
def send_mail_skill_matched_users
Users.find
end
end
|
codeforkanazawa-org/ha4go
|
app/models/project.rb
|
Ruby
|
mpl-2.0
| 2,952
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebAPI.Controllers
{
public class TimeController : ApiController
{
[SHA3Auth]
public double Get()
{
return Math.Floor(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds);
}
}
}
|
ScottRFrost/WebAPI-SHA3-Authorization
|
WebAPI/Controllers/TimeController.cs
|
C#
|
mpl-2.0
| 388
|
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=597331
-->
<head>
<title>Test for Bug 597331</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=597331">Mozilla Bug 597331</a>
<p id="display"></p>
<div id="content">
<textarea>line1
line2
line3
</textarea>
</div>
<pre id="test">
<script type="application/javascript">
/** Test for Bug 597331 **/
SimpleTest.waitForExplicitFinish();
addLoadEvent(function() {
SimpleTest.executeSoon(function() {
var t = document.querySelector("textarea");
t.focus();
t.selectionStart = 4;
t.selectionEnd = 4;
SimpleTest.executeSoon(function() {
t.getBoundingClientRect(); // flush layout
var before = snapshotWindow(window, true);
t.selectionStart = 5;
t.selectionEnd = 5;
t.addEventListener("keydown", function() {
t.removeEventListener("keydown", arguments.callee);
SimpleTest.executeSoon(function() {
t.style.display = 'block';
document.body.offsetWidth;
t.style.display = '';
document.body.offsetWidth;
is(t.selectionStart, 4, "Cursor should be moved correctly");
is(t.selectionEnd, 4, "Cursor should be moved correctly");
var after = snapshotWindow(window, true);
var result = compareSnapshots(before, after, true);
var msg = "The caret should be displayed correctly after reframing";
if (!result[0]) {
msg += "\nRESULT:\n" + result[2];
msg += "\nREFERENCE:\n" + result[1];
}
ok(result[0], msg);
SimpleTest.finish();
});
});
synthesizeKey("VK_LEFT", {});
});
});
});
</script>
</pre>
</body>
</html>
|
Yukarumya/Yukarum-Redfoxes
|
editor/libeditor/tests/test_bug597331.html
|
HTML
|
mpl-2.0
| 2,092
|
{% extends 'base.html' %}
{% block title %}文章内容管理{% endblock %}
{% block content %}
<div class="aboutz">
{% include 'admin/left-sider.html' %}
<div class="aboutrig">
<div class="aboutrigdao">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="2%">
<img src="{{ url_for('static', filename='images/li2.jpg') }}" width="11" height="11" />
</td>
<td width="36%">
<font class="wen4">{{ category.cname }}</font>
</td>
<td width="62%" align="right">
<div align="right" class="wz004">
<img src="{{ url_for('static', filename='images/index_21.jpg') }}" /> 您的位置:<a href="{{ url_for('home.index') }}">首页</a>
<img src="{{ url_for('static', filename='images/jiao.gif') }}" /><a href="{{ url_for('admin.index') }}">管理中心</a>
<img src="{{ url_for('static', filename='images/jiao.gif') }}" />文章内容管理
</div>
</td>
</tr>
</table>
</div>
<div class="left"><img src="{{ url_for('static', filename='images/rigxian.jpg') }}" /></div>
<div class="aboutrignei">
<style>
.posts-table {
width: 100%;
border: 1px;
text-align: center;
}
</style>
<table class="posts-table">
<thead>
{#
<tr>
<td><label for="category">一级分类:</label></td>
<td>
<select name="category">
{% for category in categories %}
<option value="{{ category.name }}">{{ category.cname }}</option>
{% endfor %}
</select>
</td>
</tr>
#}
<tr>
<th class="post-check-td" width="10%"><input id="post-check-all" type="checkbox" /></th>
{% if category.labels %}
<th class="post-label-td" width="10%">二级分类</th>
<th class="post-title-td" width="55%">文章标题</th>
{% else %}
<th class="post-title-td" width="65%">文章标题</th>
{% endif %}
<th class="post-status-td" width="10%">状态</th>
<th class="post-operation-td" width="15%">操作</th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr id="{{ post.id }}">
<td class="post-check-td"><input class="post-check-input" type="checkbox" /></td>
{% if category.labels %}
<td class="post-label-td">{{ post.label.cname }}</td>
{% endif %}
<td class="post-title-td"><a href="{{ url_for('admin.edit_post', id=post.id) }}">{{ post.title|d('无标题', true) }}</a></td>
<td class="post-status-td">{{ post.status }}</td>
<td class="post-operation-td">
<a href="{{ url_for('post.detail', id=post.id) }}">预览</a>
<a href="{{ url_for('admin.delete_post', id=post.id) }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
{% if category.labels %}
<td></td>
{% endif %}
<td></td>
<td></td>
<td>
<a id="post-add" href="{{ url_for('admin.add_post', category=category.name) }}">添加</a> |
<a id="post-delete-checked" href="javascript:void(0)">批量删除</a>
</td>
</tr>
</tfoot>
</table>
<p align="center">
<style>
<!--
#dcms_pager .pages {border:none;text-transform:uppercase;font-size:12px;margin:10px 0 10px 0;padding:0;height:20px;clear:both;text-align:center;}
#dcms_pager .pages a {border:1px solid #ccc;text-decoration:none;margin:0 5px 0 0;padding:0 3px 0 3px;font-size:12px;height:16px;line-height:16px;}
#dcms_pager .pages a:hover {border:1px solid #aeaeae;}
#dcms_pager .pages .pgempty {border:1px solid #eee;color:#eee;}
#dcms_pager .pages .pgcurrent {border:1px solid #aeaeae;color:#000;font-weight:bold;background-color:#eee;}
-->
</style>
{% if pagination.pages < 2 %}
{% else %}
<div id="dcms_pager" align="center">
<div class="pages">
<a class="pgnext"{%- if pagination.has_prev %} href="{{ url_for('admin.post', category=category.name) }}"{% endif -%}>首页</a>
<a class="pgnext"{%- if pagination.has_prev %} href="{{ url_for('admin.post', category=category.name, page=pagination.page-1) }}"{% endif -%}>上一页</a>
{% for page in pagination.iter_pages(2, 2, 2, 2) %}
{% if page %}
<a{%- if page == pagination.page %} class="page-number pgcurrent"{% else %} href="{{ url_for('admin.post', category=category.name, page=page) }}"{%- endif %}>{{ page }}</a>
{% else %}
...
{% endif %}
{% endfor %}
<a class="pgnext"{%- if pagination.has_next %} href="{{ url_for('admin.post', category=category.name, page=pagination.page+1) }}"{% endif -%}>下一页</a>
<a class="pgnext"{%- if pagination.has_next %} href="{{ url_for('admin.post', category=category.name, page=pagination.pages) }}"{% endif -%}>尾页</a>
</div>
</div>
{% endif %}
</p>
{#
{% for post in posts %}
<table width="100%" border="0" cellspacing="0" cellpadding="10">
<tr>
<td width="15%">
<a href="news_show.aspx?NewsId=130">
<img src="/Upload/股票页面-09482678882.jpg" width="135" height="88" style=" padding:2px;border:1px #dfdfdf solid;">
</a>
</td>
<td width="85%" valign="top">
<p style="font-weight:bold; "> 标题:<a href="{{ url_for('post.detail', id=post.id) }}" style="color:#666666;">{{ post.title }}</a></p>
<p style="height:50px;"> 2015年5月7日,深圳市德卡科技股份有限公司成功在全国中小企业股份转让系统(新三板)挂牌上市,证券简称“德卡科技”,股票代码为832423。德卡科技作为国内智能卡读写机具的领军企业,一直引领着国内智能身份识别终端和电子支付终端应用…</p>
<p style="float:right; margin-right:5px;"><a href="{{ url_for('post.detail', id=post.id) }}" style="color:#f47900;">[查看详情]</a></p>
</td>
</tr>
</table>
<p style="border-top:1px solid #dfdfdf; margin-top:15px; margin-bottom:15px;"></p>
{% endfor %}
<p align="center">
<style>
<!--
#dcms_pager .pages {border:none;text-transform:uppercase;font-size:12px;margin:10px 0 10px 0;padding:0;height:20px;clear:both;text-align:center;}
#dcms_pager .pages a {border:1px solid #ccc;text-decoration:none;margin:0 5px 0 0;padding:0 3px 0 3px;font-size:12px;height:16px;line-height:16px;}
#dcms_pager .pages a:hover {border:1px solid #aeaeae;}
#dcms_pager .pages .pgempty {border:1px solid #eee;color:#eee;}
#dcms_pager .pages .pgcurrent {border:1px solid #aeaeae;color:#000;font-weight:bold;background-color:#eee;}
-->
</style>
{% if pagination.pages < 2 %}
{% else %}
<div id="dcms_pager" align="center">
<div class=pages>
<a class=pgnext href="{{ url_for('post.index', category=active, label=label_active) }}">首页</a>
<a class="pgnext"{%- if pagination.has_prev %} href="{{ url_for('post.index', category=active, label=label_active, page=pagination.page-1) }}"{% endif -%}>上一页</a>
{% for page in pagination.iter_pages(2, 2, 2, 2) %}
{% if page %}
<a{%- if page == pagination.page %} class="page-number pgcurrent"{%- endif %} href="{{ url_for('post.index', category=active, label=label_active, page=page) }}" >{{ page }}</a>
{% else %}
...
{% endif %}
{% endfor %}
<a class=pgnext{%- if pagination.has_next %} href="{{ url_for('post.index', category=active, label=label_active, page=pagination.page+1) }}"{% endif -%}>下一页</a>
<a class=pgnext href="{{ url_for('post.index', category=active, label=label_active, page=pagination.pages) }}">尾页</a>
</div>
</div>
{% endif %}
</p>
#}
</div>
</div>
<div class="both"></div>
</div>
{% endblock %}
{% block script %}
<script>
$(document).ready(function() {
$("#post-check-all").click(function() {
// alert($(this).attr("checked"));
if ($(this).attr("checked") == true) {
$(".post-check-input").each(function() {
$(this).attr("checked", true);
});
} else {
$(".post-check-input").each(function() {
$(this).attr("checked", false);
});
}
});
$("#post-delete-checked").click(function() {
if (confirm("确认删除选中?")) {
// alert($(".link-check-input:checked"));
var ids = [];
$(".post-check-input:checked").each(function() {
ids.push($(this).parents("tr:first").attr("id"));
// var delete_url = $(this).parents("tr:first").find(".link-delete").attr("href");
// alert(delete_url);
});
// alert(ids);
$.get("{{ url_for('admin.batch_delete_post') }}", {ids: ids}, function() {
location.reload();
});
}
});
});
</script>
{% endblock %}
|
whypro/IBATI
|
ibati/templates/admin/posts.html
|
HTML
|
mpl-2.0
| 12,467
|
use std::{
collections::HashMap,
fmt::{Debug, Display},
fs::File,
hash::Hash,
io::Write,
result::Result as StdResult,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use dashmap::DashMap;
use libp2p::{identity, kad::QueryId, PeerId};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tokio::sync::mpsc::{error::TrySendError, Receiver, Sender};
use uuid::Uuid;
use crate::{
agent::{AgentId, AgentPolicy},
config::GlobalExecutor,
group::GroupSettings,
group::{Group, GroupPermits},
network::NetworkError,
rpc::{self, Resource, ResourceIdentifier},
Error, Result,
};
/// A handle to a running network connection.
pub struct NetworkHandle<M>
where
M: Serialize + DeserializeOwned,
{
pub stats: NetworkStats,
sender: Sender<HandleCmd<M>>,
local_key: identity::ed25519::Keypair,
pending: Arc<DashMap<OpId, PendingCmd<M>>>,
next_msg_id: usize,
/// a flag attribute to indicate in the background network is alive or not
network_is_dead: bool,
msg_buf: Arc<DashMap<PeerId, Vec<M>>>,
}
impl<M> NetworkHandle<M>
where
M: Serialize + DeserializeOwned + Debug + Send + Sync + 'static,
{
/// Only should be instanced throught the network builder.
pub(crate) fn new(
sender: Sender<HandleCmd<M>>,
rcv: Receiver<StdResult<HandleAnsw<M>, NetworkError>>,
local_key: identity::ed25519::Keypair,
) -> Self {
let pending = Arc::new(DashMap::new());
let msg_buf = Arc::new(DashMap::new());
let net_stats = Arc::new(Mutex::new(Vec::new()));
GlobalExecutor::spawn(Self::process_answer_buffer(
rcv,
pending.clone(),
msg_buf.clone(),
net_stats.clone(),
));
NetworkHandle {
sender,
local_key,
pending,
next_msg_id: 1, // 0 value is reserved
network_is_dead: false,
stats: NetworkStats::new(net_stats),
msg_buf,
}
}
/// Returns whether an asynchrnous operation executed succesfully or not.
/// If the operation still is running it will return a `waiting` error type.
/// Returns the resource identifier in case the operation returns one:
/// - create_group
/// - join_group
/// - register_agent
/// - find_agent.
pub fn op_result(&mut self, op_id: OpId) -> Result<Option<ResourceIdentifier>> {
let answ = match self.pending.get_mut(&op_id) {
None => Err(HandleError::OpNotFound(op_id).into()),
Some(mut pend_cmd) => match pend_cmd.value_mut().answ.as_mut() {
None => return Err(HandleError::AwaitingResponse(op_id).into()),
Some(HandleAnsw::ReqJoinGroupAccepted { group_id, .. }) => {
Ok(Some(ResourceIdentifier::group(&group_id)))
}
Some(HandleAnsw::ReqJoinGroupDenied {
group_id, reason, ..
}) => Err(Error::GroupError {
group_id: *group_id,
reason: reason.clone(),
}),
Some(HandleAnsw::AgentRegistered { rss_key, .. }) => Ok(Some(*rss_key)),
Some(HandleAnsw::AgentFound { rss_key, .. }) => {
log::info!("Found agent {}", rss_key);
Ok(Some(*rss_key))
}
Some(HandleAnsw::HasShutdown { .. })
| Some(HandleAnsw::PropagateGroupChange { .. }) => Ok(None),
Some(HandleAnsw::AwaitingRegistration { .. }) => Ok(None),
Some(HandleAnsw::RcvMsg { .. }) => unreachable!(),
},
};
self.pending.remove(&op_id);
answ
}
/// Blocks the current thread until a resource key is returned from a previous operation.
/// Returns error in case time out is reached (if provided) or the result of the op
/// is an error.
///
/// # Panic
/// Panics if the provided operation does not return a resource key.
pub fn get_resource_key(
&mut self,
op_id: OpId,
time_out: Option<Duration>,
) -> Result<ResourceIdentifier> {
let start_time = Instant::now();
loop {
match time_out {
Some(time_out) => {
let diff = Instant::now() - start_time;
if diff > time_out {
break Err(HandleError::TimeOut(op_id).into());
}
}
None => {}
}
match self.op_result(op_id) {
Err(Error::OpError(HandleError::AwaitingResponse(_))) => {}
Ok(Some(key)) => return Ok(key),
Err(err) => return Err(err),
Ok(None) => panic!("Wrong OpId provided"),
}
}
}
/// Get all the received messages from a given peer.
pub fn received_messages(&mut self, peer: PeerId) -> Vec<M> {
let mut new_msgs = vec![];
if let Some(mut msgs) = self.msg_buf.get_mut(&peer) {
std::mem::swap(&mut *msgs, &mut new_msgs);
}
new_msgs
}
/// Register an agent with this node. From this point on the node will act as the owner of this
/// agent and handle any communication from/to this agent. Operation is asynchronous.
///
/// This will block the handle until the agent has been correctly registered or an error happens.
pub fn register_agent(&mut self, agent: &simag_core::Agent, config: AgentPolicy) -> OpId {
// TODO: An agent can only be registered with a single node. If you try to register the same agent in
// the same network more than once it will be an error.
let agent_id = AgentId::from(agent.id());
let id = self.next_id();
let msg = HandleCmd::RegisterAgent {
op_id: id,
agent_id,
config,
};
let sender = self.sender.clone();
self.pending.insert(
id,
PendingCmd {
cmd: SentCmd::RegisterAgent,
answ: None,
},
);
GlobalExecutor::spawn(async move {
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
id
}
/// Find an agent in the network and try to open a connection with it. Operation is asynchronous.
pub fn find_agent<ID: Into<AgentId>>(&mut self, agent_id: ID) -> OpId {
let op_id = self.next_id();
let agent_id = agent_id.into();
self.pending.insert(
op_id,
PendingCmd {
cmd: SentCmd::FindAgent,
answ: None,
},
);
let sender = self.sender.clone();
GlobalExecutor::spawn(async move {
let msg = HandleCmd::ConnectToAgent { agent_id, op_id };
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
op_id
}
pub fn send_message_to_agent<ID: Into<AgentId>>(&mut self, agent_id: ID, value: M) -> OpId {
let op_id = self.next_id();
let agent_id = agent_id.into();
self.pending.insert(
op_id,
PendingCmd {
cmd: SentCmd::SentMsg,
answ: None,
},
);
let sender = self.sender.clone();
GlobalExecutor::spawn(async move {
let msg = HandleCmd::<M>::SendMessageToAg {
op_id,
value,
agent_id,
};
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
op_id
}
/// Create a resource of the group kind that belongs to the given agent, which will then be the original
/// owner of the group. Operation is asynchronous.
///
/// Returns the network identifier (key) to the group in case the group has not already been
/// registered by an other agent/peer or error otherwise.
pub fn create_group<C, ID>(
&mut self,
group_id: &str,
owners: impl IntoIterator<Item = ID> + Clone,
permits: Option<GroupPermits>,
settings: C,
) -> OpId
where
ID: AsRef<str>,
C: GroupSettings,
{
let op_id = self.next_id();
let (key, mut group) = Resource::group(owners.clone(), group_id, settings);
if let Some(mut permits) = permits {
// ensure that owners are added as readers/writers
owners.into_iter().for_each(|owner| {
permits.write(owner.as_ref());
permits.read(owner.as_ref());
});
group.with_permits(permits);
}
let sender = self.sender.clone();
// FIXME: register op as pending
GlobalExecutor::spawn(async move {
let msg = HandleCmd::RegisterGroup {
op_id,
group_key: key,
group,
};
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
op_id
}
/// Request joining to a given group, will return the network identifier of the group in case
/// this agent is allowed to join the group. Operation is asynchronous.
///
/// The petitioner must pass the settings used to evaluate if joining is possible when comparing
/// with the settings set by the owners of the group.
///
/// Optionally request a set of group permits, otherwise read permits will be requested.
/// The agent only will be allowed to join if the permits are legal for this agent.
///
/// ## Arguments
/// - agent_id: identifier of the agent making the request.
pub fn join_group<C, AID>(
&mut self,
group_id: &str,
agent_id: AID,
permits: Option<GroupPermits>,
settings: C,
) -> OpId
where
C: GroupSettings,
AID: Into<AgentId>,
{
let op_id = self.next_id();
let agent_id = agent_id.into();
// unknown owners, this information is to be completed after fecthing the initial info
let (group_key, mut group) = Resource::group(Vec::<String>::new(), group_id, settings);
if let Some(permits) = permits {
group.with_permits(permits);
}
let sender = self.sender.clone();
// FIXME: register op as pending
GlobalExecutor::spawn(async move {
let msg = HandleCmd::ReqJoinGroup {
op_id,
group_key,
agent_id,
group,
};
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
op_id
}
/// Operation is asynchronous.
pub fn leave_group(&mut self, group_id: &str, agent_id: &str) -> OpId {
todo!()
}
/// Send a message to the given peer directly. Operation is asynchronous.
pub fn send_message(&mut self, value: M, peer: PeerId) -> OpId {
let op_id = self.next_id();
self.pending.insert(
op_id,
PendingCmd {
cmd: SentCmd::SentMsg,
answ: None,
},
);
let sender = self.sender.clone();
GlobalExecutor::spawn(async move {
let msg = HandleCmd::<M>::SendMessage { op_id, value, peer };
sender.send(msg).await.map_err(|_| ())?;
Ok::<_, ()>(())
});
op_id
}
/// Get this peer id encoded as a Base58 string.
pub fn get_peer_id(&self) -> String {
Self::peer_id_from_ed25519(self.local_key.public()).to_base58()
}
/// Saves this peer secret key to a file in bytes. This file should be kept in a secure location.
pub fn save_secret_key<T: AsRef<std::path::Path>>(&self, path: T) -> Result<()> {
let enconded_key = self.local_key.encode().to_vec();
let mut file = File::create(path.as_ref())
.map_err(|err| crate::Error::from(HandleError::FailedSaving(err)))?;
file.write_all(enconded_key.as_slice())
.map_err(|err| HandleError::FailedSaving(err).into())
}
/// Returns whether the network connection is running or has shutdown.
pub fn running(&mut self) -> bool {
if self.network_is_dead {
return false;
}
self.sender
.try_send(HandleCmd::IsRunning)
.map(|_| true)
.unwrap_or_else(|err| match err {
TrySendError::Full(_) => true,
TrySendError::Closed(_) => {
self.network_is_dead = true;
false
}
})
}
/// Commands the network to shutdown, returns inmediately if the network has shutdown
/// or if it already had disconnected for any reason or blocking otherwise.
///
/// The network may not shutdown inmediately if still is processing any commands.
pub fn shutdown(&mut self) -> Result<bool> {
if self.network_is_dead {
// was previously marked as dead
return Err(HandleError::Disconnected.into());
}
if self.has_shutdown() {
return Ok(true);
}
let msg_id = self.next_id();
let msg = HandleCmd::Shutdown(msg_id);
match self.sender.blocking_send(msg) {
Ok(()) => {}
Err(_err) => {
self.network_is_dead = true;
return Err(HandleError::Disconnected.into());
}
}
Ok(self.has_shutdown())
}
fn has_shutdown(&mut self) -> bool {
let shutdown_cmds: Vec<_> = self
.pending
.iter()
.filter_map(|p| {
if (*p).shutdown() {
Some(*p.key())
} else {
None
}
})
.collect();
let mut has_shutdown = false;
for k in shutdown_cmds {
if let Some((
_,
PendingCmd {
cmd: SentCmd::ShutDown,
answ: Some(HandleAnsw::HasShutdown { answ, .. }),
},
)) = self.pending.remove(&k)
{
if answ {
// one of all the sent shutdown commands was successful, not the conn is dead
self.network_is_dead = true;
has_shutdown = true;
}
}
}
has_shutdown
}
async fn process_answer_buffer(
mut rcv: Receiver<StdResult<HandleAnsw<M>, NetworkError>>,
pending: Arc<DashMap<OpId, PendingCmd<M>>>,
msg_buf: Arc<DashMap<PeerId, Vec<M>>>,
net_stats: Arc<Mutex<Vec<(PeerId, usize)>>>,
) -> Result<()> {
while let Some(answ_res) = rcv.recv().await {
let msg = answ_res?;
match msg {
HandleAnsw::HasShutdown { op_id: id, answ } => {
pending.entry(id).and_modify(|e| {
e.answ = Some(HandleAnsw::HasShutdown { op_id: id, answ });
});
}
HandleAnsw::RcvMsg { peer, msg } => {
log::debug!("Received streaming msg from {}: {:?}", peer, msg);
msg_buf.entry(peer).or_default().push(msg);
let stats = &mut *net_stats.lock().unwrap();
if let Ok(idx) = stats.binary_search_by_key(&peer, |&(p, _)| p) {
stats[idx].1 += 1;
} else {
stats.push((peer, 1));
stats.sort_by_key(|e| e.0);
}
}
HandleAnsw::AgentRegistered { op_id, rss_key } => {
log::info!("Registered {} with {:?}", rss_key, op_id);
pending.entry(op_id).and_modify(|e| {
e.answ = Some(HandleAnsw::AgentRegistered { op_id, rss_key });
});
}
HandleAnsw::PropagateGroupChange { op_id, group_id } => todo!(),
HandleAnsw::ReqJoinGroupAccepted { op_id, group_id } => {
pending.entry(op_id).and_modify(|e| {
e.answ = Some(HandleAnsw::ReqJoinGroupAccepted { op_id, group_id });
});
}
HandleAnsw::ReqJoinGroupDenied {
op_id,
group_id,
reason,
} => {
pending.entry(op_id).and_modify(|e| {
e.answ = Some(HandleAnsw::ReqJoinGroupDenied {
op_id,
group_id,
reason,
});
});
}
HandleAnsw::AgentFound {
op_id,
rss_key: key,
} => {
pending.alter(&op_id, |_, mut e| {
e.answ = Some(HandleAnsw::AgentFound {
op_id,
rss_key: key,
});
e
});
}
HandleAnsw::AwaitingRegistration { .. } => {}
}
}
// all sending halves were closed, meaning that the network connection has been dropped
// communicate back to the main thread
pending.insert(
OpId(usize::MAX),
PendingCmd {
cmd: SentCmd::ShutDown,
answ: Some(HandleAnsw::HasShutdown {
op_id: OpId(usize::MAX),
answ: true,
}),
},
);
Err(HandleError::Disconnected.into())
}
fn next_id(&mut self) -> OpId {
let msg_id = self.next_msg_id;
self.next_msg_id += 1;
OpId(msg_id)
}
fn peer_id_from_ed25519(key: identity::ed25519::PublicKey) -> PeerId {
PeerId::from_public_key(identity::PublicKey::Ed25519(key))
}
}
pub struct NetworkStats {
key_stats: HashMap<ResourceIdentifier, KeyStats>,
msg_stats: Arc<Mutex<Vec<(PeerId, usize)>>>,
}
impl NetworkStats {
fn new(msg_stats: Arc<Mutex<Vec<(PeerId, usize)>>>) -> Self {
NetworkStats {
key_stats: HashMap::new(),
msg_stats,
}
}
pub fn for_key(&self, key: &ResourceIdentifier) -> Option<&KeyStats> {
self.key_stats.get(key)
}
pub fn received_messages(&self) -> Vec<(PeerId, usize)> {
let stats = self.msg_stats.lock().unwrap();
stats.clone()
}
}
#[derive(Default)]
pub struct KeyStats {
pub times_served: usize,
pub times_received: usize,
}
struct PendingCmd<M>
where
M: DeserializeOwned,
{
cmd: SentCmd,
answ: Option<HandleAnsw<M>>,
}
impl<M: DeserializeOwned> PendingCmd<M> {
fn shutdown(&self) -> bool {
match self.cmd {
SentCmd::ShutDown => true,
_ => false,
}
}
}
enum SentCmd {
AddedKey(Vec<u8>),
PullContent(Vec<u8>),
ShutDown,
SentMsg,
RegisterAgent,
FindAgent,
}
#[derive(Debug)]
pub(crate) enum HandleCmd<M> {
/// query the network about current status
IsRunning,
/// put a resource in this node
RegisterGroup {
op_id: OpId,
group_key: ResourceIdentifier,
group: Group,
},
/// issue a shutdown command
Shutdown(OpId),
/// send a serialized message
/// M should be heap allocated ideally to avoid large enum sizes
SendMessage { op_id: OpId, value: M, peer: PeerId },
/// register a peer as the manager of an agent
RegisterAgent {
op_id: OpId,
agent_id: AgentId,
config: AgentPolicy,
},
/// try to open a channel to the specified agent
ConnectToAgent { agent_id: AgentId, op_id: OpId },
/// enroute a message to a given agent
SendMessageToAg {
agent_id: AgentId,
value: M,
op_id: OpId,
},
/// instruct the network handler to send a request
/// for an agent joining a group
ReqJoinGroup {
op_id: OpId,
group_key: ResourceIdentifier,
agent_id: AgentId,
group: Group,
// state: RequestState,
},
/// No manager was found in the local cache. Awaiting peer information for managers
/// so a connection attempt can be initialized.
FindGroupManager {
op_id: OpId,
group_key: ResourceIdentifier,
agent_id: AgentId,
group: Group,
},
/// Awaiting publish confirmation by the kad DHT of a rss.
AwaitingRegistration {
op_id: OpId,
rss_key: ResourceIdentifier,
resource: Resource,
},
}
impl<M: DeserializeOwned> HandleCmd<M> {
fn get_op_id(&self) -> OpId {
use self::HandleCmd::*;
match self {
IsRunning => OpId::IS_RUNNING,
RegisterGroup { op_id, .. } => *op_id,
Shutdown(op_id) => *op_id,
SendMessage { op_id, .. } => *op_id,
RegisterAgent { op_id, .. } => *op_id,
ConnectToAgent { op_id, .. } => *op_id,
SendMessageToAg { op_id, .. } => *op_id,
ReqJoinGroup { op_id, .. } => *op_id,
FindGroupManager { op_id, .. } => *op_id,
AwaitingRegistration { op_id, .. } => *op_id,
}
}
}
impl<M: DeserializeOwned> PartialEq for HandleCmd<M> {
fn eq(&self, other: &Self) -> bool {
self.get_op_id() == other.get_op_id()
}
}
impl<M: DeserializeOwned> Eq for HandleCmd<M> {}
impl<M: DeserializeOwned> PartialOrd for HandleCmd<M> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.get_op_id().partial_cmp(&other.get_op_id())
}
}
impl<M: DeserializeOwned> Ord for HandleCmd<M> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.get_op_id().cmp(&other.get_op_id())
}
}
/// The answer of an operation.
#[derive(Clone, Debug)]
pub(crate) enum HandleAnsw<M>
where
M: DeserializeOwned,
{
AgentRegistered {
op_id: OpId,
rss_key: ResourceIdentifier,
},
HasShutdown {
op_id: OpId,
answ: bool,
},
/// Propagate a change in the configuration or composition of a group.
PropagateGroupChange {
op_id: OpId,
group_id: Uuid,
},
ReqJoinGroupAccepted {
op_id: OpId,
group_id: Uuid,
},
ReqJoinGroupDenied {
op_id: OpId,
group_id: Uuid,
reason: crate::group::GroupError,
},
/// The operation id of received messages is always considered OpId::RCV_MSG.
RcvMsg {
peer: PeerId,
msg: M,
},
AgentFound {
op_id: OpId,
rss_key: ResourceIdentifier,
},
AwaitingRegistration {
op_id: OpId,
qid: QueryId,
},
}
impl<M: DeserializeOwned> HandleAnsw<M> {
fn get_op_id(&self) -> OpId {
use self::HandleAnsw::*;
match self {
AgentRegistered { op_id, .. } => *op_id,
HasShutdown { op_id, .. } => *op_id,
PropagateGroupChange { op_id, .. } => *op_id,
ReqJoinGroupAccepted { op_id, .. } => *op_id,
ReqJoinGroupDenied { op_id, .. } => *op_id,
RcvMsg { .. } => OpId::RCV_MSG,
AgentFound { op_id, .. } => *op_id,
AwaitingRegistration { op_id, .. } => *op_id,
}
}
}
impl<M: DeserializeOwned> PartialEq for HandleAnsw<M> {
fn eq(&self, other: &Self) -> bool {
self.get_op_id() == other.get_op_id()
}
}
impl<M: DeserializeOwned> Eq for HandleAnsw<M> {}
impl<M: DeserializeOwned> PartialOrd for HandleAnsw<M> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.get_op_id().partial_cmp(&other.get_op_id())
}
}
impl<M: DeserializeOwned> Ord for HandleAnsw<M> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.get_op_id().cmp(&other.get_op_id())
}
}
#[derive(thiserror::Error, Debug)]
pub enum HandleError {
#[error("awaiting a response for op `{0}`")]
AwaitingResponse(OpId),
#[error("unexpected disconnect")]
Disconnected,
#[error("failed saving secret key")]
FailedSaving(#[from] std::io::Error),
#[error("handle not available")]
HandleNotResponding,
#[error("irrecoverable error in the network")]
IrrecoverableError,
#[error("network op execution failed")]
OpFailed,
#[error("operation `{0}` not found")]
OpNotFound(OpId),
#[error("manager not found for op `{0}`")]
ManagerNotFound(OpId),
#[error("unexpected response")]
UnexpectedResponse(OpId),
#[error("op `{0}` timed out")]
TimeOut(OpId),
}
/// An identifier for an operation executed asynchronously. Used to fetch the results
/// of such operation in an asynchronous fashion.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OpId(usize);
impl OpId {
const RCV_MSG: OpId = OpId(0);
const IS_RUNNING: OpId = OpId(0);
}
impl Display for OpId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)?;
Ok(())
}
}
|
iduartgomez/simag
|
simag_networking/src/handle.rs
|
Rust
|
mpl-2.0
| 25,345
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `delete_shader` fn in crate `servo`.">
<meta name="keywords" content="rust, rustlang, rust-lang, delete_shader">
<title>servo::gl::delete_shader - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a></p><script>window.sidebarCurrent = {name: 'delete_shader', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a>::<wbr><a class='fn' href=''>delete_shader</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-1770' class='srclink' href='../../export/gleam/gl/fn.delete_shader.html?gotosrc=1770' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn delete_shader(shader: <a href='../../std/primitive.u32.html'>u32</a>)</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "servo";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
servo/gl/fn.delete_shader.html
|
HTML
|
mpl-2.0
| 3,889
|
% AURSEC(7) aursec user manuals
% Lukas Krismer and Bennett Piater
% November 21, 2016
# NAME
aursec - verify AUR package sources against hashes stored in a blockchain
# PROGRAMS
The following is just an overview, see the respective documentation for details.
aursec(1)
: Hash source folders and verify them against the blockchain.
aursec-chain(1)
: API for the blockchain.
aursec-hash(1)
: Ouput an ID and a hash for source folders.
aursec-parse-srcinfo(1)
: Extract helpful information from a *.SRCINFO*.
aursec-verify-hashes(1):
: Take IDs and hashes and compare them against the ones on the blockchain.
aursec-aursync-wrapper
: Use this instead of **aursync**(1) to integrate **aursec** with **aurutils**(7)
# PURPOSE
The open and insecure nature of the AUR makes a variety of attacks very easy to pull off. Aursec reduces the risks by creating a secure, distributed repository of hashes with package name, version and release as key.
Comparing the build files (*PKGBUILD*, *.SRCINFO*, *\*.patch*, *\*.install*) against those of other users makes targeted attacks much less feasible.
We also hash VCS sources, which is a huge security improvement since vcs packages don't have hashes in the *PKGBUILD*.
# NOTES
Most features of this toolkit require the blockchain to be running and periodical mining to be enabled. Please start and enable
aursec-blockchain.service
aursec-blockchain-mine.timer
before using them.
The first time, there will be a synchronisation before the blockchain can be used, which will take a few minutes.
To use **aursec-aursync-wrapper** instead of **aursync**(1), add
alias -g aursync="$(which aursec-aursync-wrapper)"
To your *.bashrc*, or *.zshrc*.
# BUGS
# SEE ALSO
**aursec**(1), **aursec-hash**(1), **aursec-chain**(1).
# COPYRIGHT
This is free software licensed under the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file,
You can obtain one at http://mozilla.org/MPL/2.0/
|
clawoflight/aursec
|
aursec/man/aursec.7.md
|
Markdown
|
mpl-2.0
| 1,977
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `MultiTexCoordP3ui` static in crate `gleam`.">
<meta name="keywords" content="rust, rustlang, rust-lang, MultiTexCoordP3ui">
<title>gleam::ffi::storage::MultiTexCoordP3ui - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>storage</a></p><script>window.sidebarCurrent = {name: 'MultiTexCoordP3ui', ty: 'static', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content static">
<h1 class='fqn'><span class='in-band'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>storage</a>::<wbr><a class='static' href=''>MultiTexCoordP3ui</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-4390' class='srclink' href='../../../src/gleam/home/servo/buildbot/slave/doc/build/target/debug/build/gleam-8cc6d4d4d5b87928/out/gl_bindings.rs.html#2927-2930' title='goto source code'>[src]</a></span></h1>
<pre class='rust static'>pub static mut MultiTexCoordP3ui: <a class='struct' href='../../../gleam/gl/struct.FnPtr.html' title='gleam::gl::FnPtr'>FnPtr</a><code> = </code><code>FnPtr{f: super::missing_fn_panic as *const raw::c_void, is_loaded: false,}</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "gleam";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
gleam/ffi/storage/static.MultiTexCoordP3ui.html
|
HTML
|
mpl-2.0
| 4,524
|
<?php
$lang['required'] = "Le champ %s est requis.";
$lang['isset'] = "Le champ %s doit avoir une valeur.";
$lang['valid_email'] = "Le champ %s doit contenir une véritable adresse e-mail.";
$lang['valid_emails'] = "Le champ %s doit contenir de véritables adresses e-mail.";
$lang['valid_url'] = "The %s field must contain a valid URL.";
$lang['valid_ip'] = "The %s field must contain a valid IP.";
$lang['min_length'] = "Le champ %s doit contenir au moins %s caractères.";
$lang['max_length'] = "Le champ %s ne peut pas contenir %s caractères.";
$lang['exact_length'] = "Le champ %s doit contenir exactement %s caractères.";
$lang['alpha'] = "Le champ %s ne peux contenir que des caractères alphabétiques.";
$lang['alpha_numeric'] = "Le champ %s ne peux contenir que des caractères alpha-numériques.";
$lang['alpha_dash'] = "The %s field may only contain alpha-numeric characters, underscores, and dashes.";
$lang['numeric'] = "Le champ %s ne doit contenir que des nombres.";
$lang['is_numeric'] = "Le champ %s doit contenir uniquement des caractères numériques.";
$lang['integer'] = "The %s field must contain an integer.";
$lang['regex_match'] = "The %s field is not in the correct format.";
$lang['matches'] = "The %s field does not match the %s field.";
$lang['is_unique'] = "The %s field must contain a unique value.";
$lang['is_natural'] = "The %s field must contain only positive numbers.";
$lang['is_natural_no_zero'] = "The %s field must contain a number greater than zero.";
$lang['decimal'] = "The %s field must contain a decimal number.";
$lang['less_than'] = "The %s field must contain a number less than %s.";
$lang['greater_than'] = "The %s field must contain a number greater than %s.";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */
|
indydedeken/markus
|
system/language/english/form_validation_lang.php
|
PHP
|
mpl-2.0
| 1,895
|
package org.helioviewer.jhv.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import org.helioviewer.jhv.JHVGlobals;
import org.helioviewer.jhv.camera.Interaction;
import org.helioviewer.jhv.display.Display;
import org.helioviewer.jhv.gui.actions.ExitProgramAction;
import org.helioviewer.jhv.gui.components.MainContentPanel;
import org.helioviewer.jhv.gui.components.MenuBar;
import org.helioviewer.jhv.gui.components.MoviePanel;
import org.helioviewer.jhv.gui.components.SideContentPane;
import org.helioviewer.jhv.gui.components.StatusPanel;
import org.helioviewer.jhv.gui.components.ToolBar;
import org.helioviewer.jhv.gui.components.statusplugin.CarringtonStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugin.FramerateStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugin.PositionStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugin.ZoomStatusPanel;
import org.helioviewer.jhv.input.InputController;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.layers.Movie;
import org.helioviewer.jhv.layers.selector.LayersPanel;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLListener;
import com.jogamp.opengl.awt.GLCanvas;
public class JHVFrame {
private static JFrame mainFrame;
private static JScrollPane leftScrollPane;
private static SideContentPane leftPane;
private static GLCanvas glCanvas;
private static GLListener glListener;
private static InputController inputController;
private static Interaction interaction;
private static MainContentPanel mainContentPanel;
private static ZoomStatusPanel zoomStatus;
private static CarringtonStatusPanel carringtonStatus;
private static LayersPanel layersPanel;
private static Layers layers;
private static ToolBar toolBar;
private static MenuBar menuBar;
public static JFrame prepare() {
mainFrame = createFrame();
menuBar = new MenuBar();
mainFrame.setJMenuBar(menuBar);
glCanvas = GLHelper.createGLCanvas(); // before camera
glCanvas.setMinimumSize(new Dimension(1, 1)); // allow resize
glListener = new GLListener(glCanvas);
glCanvas.addGLEventListener(glListener);
layers = Layers.getInstance();
layersPanel = new LayersPanel(layers);
leftPane = new SideContentPane();
leftPane.add("Image Layers", MoviePanel.getInstance(), true);
MoviePanel.setAdvanced(false);
leftScrollPane = new JScrollPane(leftPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
leftScrollPane.setFocusable(false);
leftScrollPane.setBorder(null);
leftScrollPane.getVerticalScrollBar().setUnitIncrement(layersPanel.getGridRowHeight());
interaction = new Interaction(Display.getCamera());
inputController = new InputController(interaction);
glCanvas.addMouseListener(inputController);
glCanvas.addMouseMotionListener(inputController);
glCanvas.addMouseWheelListener(inputController);
glCanvas.addKeyListener(inputController);
mainContentPanel = new MainContentPanel(glCanvas);
JSplitPane midSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
midSplitPane.setDividerSize(2);
midSplitPane.setBorder(null);
midSplitPane.setLeftComponent(leftScrollPane);
midSplitPane.setRightComponent(mainContentPanel);
zoomStatus = new ZoomStatusPanel();
carringtonStatus = new CarringtonStatusPanel();
FramerateStatusPanel framerateStatus = new FramerateStatusPanel();
PositionStatusPanel positionStatus = new PositionStatusPanel();
inputController.addPlugin(positionStatus);
StatusPanel statusPanel = new StatusPanel(5, 5);
statusPanel.addPlugin(framerateStatus, StatusPanel.Alignment.LEFT);
statusPanel.addPlugin(positionStatus, StatusPanel.Alignment.RIGHT);
statusPanel.addPlugin(zoomStatus, StatusPanel.Alignment.RIGHT);
statusPanel.addPlugin(carringtonStatus, StatusPanel.Alignment.RIGHT);
toolBar = new ToolBar();
mainFrame.add(toolBar, BorderLayout.PAGE_START);
mainFrame.add(midSplitPane, BorderLayout.CENTER);
mainFrame.add(statusPanel, BorderLayout.PAGE_END);
Movie.setMaster(Layers.getActiveImageLayer()); //! for nullImageLayer
return mainFrame;
}
private static JFrame createFrame() {
JFrame frame = new JFrame(JHVGlobals.programName);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setTransferHandler(new DropHandler());
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
ExitProgramAction exitAction = new ExitProgramAction();
exitAction.actionPerformed(new ActionEvent(this, 0, ""));
}
});
Dimension maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getSize();
Dimension minSize = new Dimension(800, 600);
minSize.width = Math.min(minSize.width, maxSize.width);
minSize.height = Math.min(minSize.height, maxSize.height);
frame.setMinimumSize(minSize);
frame.setPreferredSize(new Dimension(maxSize.width - 100, maxSize.height - 100));
frame.setIconImage(IconBank.getIcon(IconBank.JHVIcon.HVLOGO_SMALL).getImage());
return frame;
}
public static JFrame getFrame() {
return mainFrame;
}
public static SideContentPane getLeftContentPane() {
return leftPane;
}
public static JScrollPane getLeftScrollPane() {
return leftScrollPane;
}
public static GLCanvas getGLCanvas() {
return glCanvas;
}
public static GLListener getGLListener() {
return glListener;
}
public static MainContentPanel getMainContentPanel() {
return mainContentPanel;
}
public static InputController getInputController() {
return inputController;
}
public static ZoomStatusPanel getZoomStatusPanel() {
return zoomStatus;
}
public static CarringtonStatusPanel getCarringtonStatusPanel() {
return carringtonStatus;
}
public static Layers getLayers() {
return layers;
}
public static LayersPanel getLayersPanel() {
return layersPanel;
}
public static Interaction getInteraction() {
return interaction;
}
public static ToolBar getToolBar() {
return toolBar;
}
public static MenuBar getMenuBar() {
return menuBar;
}
}
|
Helioviewer-Project/JHelioviewer-SWHV
|
src/org/helioviewer/jhv/gui/JHVFrame.java
|
Java
|
mpl-2.0
| 6,953
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XcursorGetTheme` fn in crate `x11`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XcursorGetTheme">
<title>x11::xcursor::XcursorGetTheme - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xcursor</a></p><script>window.sidebarCurrent = {name: 'XcursorGetTheme', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xcursor</a>::<wbr><a class='fn' href=''>XcursorGetTheme</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-1482' class='srclink' href='../../src/x11/link.rs.html#14' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe extern fn XcursorGetTheme(_1: <a class='primitive' href='../../std/primitive.pointer.html'>*mut </a><a class='type' href='../../x11/xlib/type.Display.html' title='x11::xlib::Display'>Display</a>) -> <a class='primitive' href='../../std/primitive.pointer.html'>*mut </a><a class='type' href='../../std/os/raw/type.c_char.html' title='std::os::raw::c_char'>c_char</a></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "x11";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
x11/xcursor/fn.XcursorGetTheme.html
|
HTML
|
mpl-2.0
| 4,425
|
<?php
require_once dirname(__FILE__).'/../config/config.php';
$context = (isset($_GET['c']) ? trim($_GET['c']) : null);
if (!$context) {
header('Location: ../staff/');
exit(0);
}
$ctx_lc = strtolower($context);
$ctx_uc = strtoupper($context);
$ctx_info = (
isset($cm_config['application_types'][$ctx_uc]) ?
$cm_config['application_types'][$ctx_uc] : null
);
if (!$ctx_info) {
header('Location: ../staff/');
exit(0);
}
$ctx_name = $ctx_info['nav_prefix'];
$ctx_name_lc = strtolower($ctx_name);
session_name('PHPSESSID_CMAPPLYAPP_' . $ctx_uc);
session_start();
require_once dirname(__FILE__).'/../lib/database/database.php';
require_once dirname(__FILE__).'/../lib/database/application.php';
require_once dirname(__FILE__).'/../lib/database/forms.php';
require_once dirname(__FILE__).'/../lib/database/mail.php';
require_once dirname(__FILE__).'/../lib/util/res.php';
require_once dirname(__FILE__).'/../lib/util/util.php';
$event_name = $cm_config['event']['name'];
$db = new cm_db();
$apdb = new cm_application_db($db, $context);
$name_map = $apdb->get_badge_type_name_map();
$fdb = new cm_forms_db($db, 'application-' . $ctx_lc);
$questions = $fdb->list_questions();
$mdb = new cm_mail_db($db);
$contact_address = $mdb->get_contact_address('application-submitted-' . $ctx_lc);
function cm_app_cart_set_state($state, $cart = null) {
if ($cart) $_SESSION['cart'] = $cart;
if (!isset($_SESSION['cart'])) $_SESSION['cart'] = array();
$_SESSION['cart_hash'] = md5(serialize($_SESSION['cart']));
$_SESSION['cart_state'] = $state;
}
function cm_app_cart_check_state($expected_state) {
if (!isset($_SESSION['cart'])) return false;
if (!isset($_SESSION['cart_hash'])) return false;
if (!isset($_SESSION['cart_state'])) return false;
$expected_hash = md5(serialize($_SESSION['cart']));
if ($_SESSION['cart_hash'] != $expected_hash) return false;
if ($_SESSION['cart_state'] != $expected_state) return false;
return true;
}
function cm_app_cart_destroy() {
unset($_SESSION['cart']);
unset($_SESSION['cart_hash']);
unset($_SESSION['cart_state']);
session_destroy();
}
function cm_app_head($title) {
echo '<!DOCTYPE HTML>';
echo '<html>';
echo '<head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
echo '<title>' . htmlspecialchars($title) . '</title>';
echo '<link rel="shortcut icon" href="' . htmlspecialchars(theme_file_url('favicon.ico', false)) . '">';
echo '<link rel="stylesheet" href="' . htmlspecialchars(resource_file_url('cm.css', false)) . '">';
echo '<link rel="stylesheet" href="' . htmlspecialchars(theme_file_url('theme.css', false)) . '">';
echo '<script type="text/javascript" src="' . htmlspecialchars(resource_file_url('jquery.js', false)) . '"></script>';
echo '<script type="text/javascript" src="' . htmlspecialchars(resource_file_url('cmui.js', false)) . '"></script>';
}
function cm_app_body($title) {
echo '</head>';
echo '<body class="cm-reg">';
echo '<header>';
echo '<div class="pagename">' . htmlspecialchars($title) . '</div>';
echo '</header>';
}
function cm_app_tail() {
echo '</body>';
echo '</html>';
}
function cm_app_closed() {
global $ctx_name, $event_name, $contact_address;
cm_app_head($ctx_name . ' Applications Closed');
cm_app_body($ctx_name . ' Applications Closed');
echo '<article>';
echo '<div class="card">';
echo '<div class="card-content">';
echo '<p>';
echo htmlspecialchars($ctx_name);
echo ' applications for <b>';
echo htmlspecialchars($event_name);
echo '</b> are currently closed.';
if ($contact_address) {
echo ' Please <b><a href="mailto:';
echo htmlspecialchars($contact_address);
echo '">contact us</a></b> if you have any questions.';
}
echo '</p>';
echo '</div>';
echo '</div>';
echo '</article>';
cm_app_tail();
exit(0);
}
function cm_app_message($title, $custom_text_name, $default_text, $fields = null) {
global $ctx_lc, $ctx_name, $ctx_name_lc, $event_name, $fdb, $contact_address;
cm_app_head($title);
cm_app_body($title);
echo '<article>';
echo '<div class="card">';
echo '<div class="card-title">';
echo htmlspecialchars($title);
echo '</div>';
echo '<div class="card-content">';
$text = $fdb->get_custom_text($custom_text_name);
if (!$text) $text = $default_text;
$text = safe_html_string($text, true);
$merge_fields = array(
'ctx-name' => $ctx_name,
'ctx_name' => $ctx_name,
'ctx-name-lc' => $ctx_name_lc,
'ctx_name_lc' => $ctx_name_lc,
'event-name' => $event_name,
'event_name' => $event_name,
'contact-address' => $contact_address,
'contact_address' => $contact_address
);
if ($fields) {
foreach ($fields as $k => $v) {
$merge_fields[strtolower(str_replace('_', '-', $k))] = $v;
$merge_fields[strtolower(str_replace('-', '_', $k))] = $v;
}
}
echo mail_merge_html($text, $merge_fields);
echo '</div>';
echo '<div class="card-buttons">';
echo '<a href="index.php?c=' . $ctx_lc . '" role="button" class="button register-button">';
echo 'Start a New Application';
echo '</a>';
echo '</div>';
echo '</div>';
echo '</article>';
cm_app_tail();
exit(0);
}
|
harmonious-elements/concrescent
|
cm2/apply/apply.php
|
PHP
|
mpl-2.0
| 5,073
|
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Agebull.EntityModel.RobotCoder.CodeTemplate
{
/// <summary>
/// ±íʾһ¸ö»ù´¡µ¥´Ê
/// </summary>
public class WordUnit : AnalyzeUnitBase
{
#region ·½·¨
/// <summary>
/// ¹¹Ôì
/// </summary>
internal WordUnit()
{
Line = -1;
Column = -1;
Start = -1;
End = -1;
}
/// <summary>
/// ¹¹Ôì
/// </summary>
internal WordUnit(char ch)
{
Line = -1;
Column = -1;
Start = -1;
End = -1;
Append(-1, ch);
}
/// <summary>
/// ×·¼Ó×Ö·û
/// </summary>
/// <param name="idx">ÎļþλÖÃ</param>
/// <param name="ch">×Ö·û</param>
public void Append(int idx, char ch)
{
if (Start < 0)
Start = idx;
if (idx >= 0)
End = idx;
Chars.Add(ch);
if (ItemType == CodeItemType.String)
{
return;
}
if (UnitType == TemplateUnitType.Content)
{
if (ch == '\n')
IsLine = true;
return;
}
if (UnitType < TemplateUnitType.Content )
{
return;
}
IsPunctuate = !(ch >= 128
|| ch >= '0' && ch <= '9' //Êý×Ö
|| ch == '_'
|| ch >= 'A' && ch <= 'Z' //×Öĸ
|| ch >= 'a' && ch <= 'z');
if (!IsPunctuate)
return;
switch (ch)
{
case '\n':
IsLine = true;
IsSpace = true;
SetRace(CodeItemRace.Assist, CodeItemFamily.Space, CodeItemType.Line);
break;
case '\r':
case '\t':
case ' ':
case '\u2028':
case '\u2029':
case '\u000B':
case '\u000C':
IsSpace = true;
SetRace(CodeItemRace.Assist, CodeItemFamily.Space, CodeItemType.Space);
break;
// //case ';':
// // IsLine = true;
// // IsSpace = true;
// // SetRace(CodeItemRace.Assist, CodeItemFamily.Space, CodeItemType.Line);
// // break;
}
}
/// <summary>
/// ×·¼Ó×Ö·û
/// </summary>
/// <param name="unit">×Ö·û</param>
public void Append(WordUnit unit)
{
if (unit == null)
return;
Chars.AddRange(unit.Chars);
if (unit.End >= 0)
End = unit.End;
}
public void Clear()
{
Chars.Clear();
Start = -1;
End = -1;
_cusWord = null;
}
public override bool IsEmpty => Start < 0 || End < 0 || _cusWord == null && Chars.Count == 0;
#endregion
#region ÄÚÈÝ
/// <summary>
/// ÊÇ·ñ»ù´¡µ¥Ôª
/// </summary>
public override bool IsUnit => true;
/// <summary>
/// ΪÖ÷¿Ø·ûµÄµÈ¼¶
/// </summary>
[DataMember]
public int PrimaryLevel { get; set; } = 32;
/// <summary>
/// Êý×ÖÀàÐÍ,0²»ÊÇ,1ÕûÊý,2СÊý
/// </summary>
public int NumberType { get; set; }
/// <summary>
/// ¹Ø¼ü×Ö
/// </summary>
public bool IsKeyWord { get; set; }
/// <summary>
/// ÊÇ·ñ±êµã
/// </summary>
public bool IsPunctuate { get; private set; }
/// <summary>
/// ÊÇ·ñ¿Õ°×
/// </summary>
public bool IsSpace { get; private set; }
/// <summary>
/// ÊÇ·ñ»»ÐÐ
/// </summary>
public bool IsLine { get; private set; }
/// <summary>
/// ×Ö·ûÄÚÈÝ
/// </summary>
public List<char> Chars { get; } = new List<char>();
private string _cusWord;
/// <summary>
/// ÊÇ·ñ¿ÉÒÔµ±³Éµ¥´Ê
/// </summary>
[DataMember]
public override bool IsWord => true;
/// <summary>
/// µ±Ç°µÄµ¥´Ê
/// </summary>
public sealed override string Word
{
get => _cusWord ?? (Chars.Count == 0 ? string.Empty : string.Concat(Chars));
set => _cusWord = value;
}
/// <summary>
/// µ±Ç°µÄµ¥´Ê
/// </summary>
public char Char => Chars.Count == 1 ? Chars[0] : '\0';
/// <summary>
/// µ±Ç°µÄµ¥´Ê
/// </summary>
public char FirstChar => Chars.Count == 0 ? '\0' : Chars[0];
#endregion
/// <summary>
/// ¿ªÊ¼½áÊø¸÷Óм¸¸öÎÞÓÃ×Ö·û
/// </summary>
[DataMember]
public int EmptyChar { get; set; }
/// <summary>
/// µ½Îı¾
/// </summary>
/// <returns></returns>
public override string ToCode()
{
return Word;
}
/// <summary>
/// µ½Îı¾
/// </summary>
/// <returns></returns>
public override void ToContent(StringBuilder builder)
{
if (_cusWord != null)
{
foreach (var ch in _cusWord)
{
switch (ch)
{
default:
builder.Append(ch);
break;
case '\'':
builder.Append(@"\'");
break;
case '\n':
builder.Append(@"\n");
break;
case '\r':
builder.Append(@"\r");
break;
case '\t':
builder.Append(@"\t");
break;
case '\\':
builder.Append(@"\\");
break;
}
}
}
else
{
foreach (var ch in Chars)
{
switch (ch)
{
default:
builder.Append(ch);
break;
case '\'':
builder.Append(@"\'");
break;
case '\n':
builder.Append(@"\n");
break;
case '\r':
builder.Append(@"\r");
break;
case '\t':
builder.Append(@"\t");
break;
case '\\':
builder.Append(@"\\");
break;
}
}
}
}
}
}
|
agebullhu/AgebullDesigner
|
src/CodeTemplate/Base/WordUnit.cs
|
C#
|
mpl-2.0
| 7,447
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `forward` fn in crate `encoding_index_japanese`.">
<meta name="keywords" content="rust, rustlang, rust-lang, forward">
<title>encoding_index_japanese::jis0208::forward - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>encoding_index_japanese</a>::<wbr><a href='index.html'>jis0208</a></p><script>window.sidebarCurrent = {name: 'forward', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>encoding_index_japanese</a>::<wbr><a href='index.html'>jis0208</a>::<wbr><a class='fn' href=''>forward</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-6' class='srclink' href='../../src/encoding_index_japanese/jis0208.rs.html#1121-1128' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn forward(code: <a class='primitive' href='../../std/primitive.u16.html'>u16</a>) -> <a class='primitive' href='../../std/primitive.u32.html'>u32</a></pre><div class='docblock'><p>Returns the index code point for pointer <code>code</code> in this index.</p>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "encoding_index_japanese";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
encoding_index_japanese/jis0208/fn.forward.html
|
HTML
|
mpl-2.0
| 4,408
|
<html>
<head>
<title>A Leaflet map!</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
#map{ height: 100% }
</style>
</head>
<body>
<div id="map"></div>
<script>
// initialize the map
var map = L.map('map').setView([38.911206,-77.028961], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> Imagery © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 17,
minZoom: 9
}).addTo(map);
// load a tile layer
// load GeoJSON from an external file
$.getJSON("ward-2012.geojson",function(data){
// add GeoJSON layer to the map once the file is loaded
L.geoJson(data).addTo(map);
});
</script>
</body>
</html>
|
jalbertbowden/dcdatadump
|
leaflet/done/data/ward-2012.html
|
HTML
|
mpl-2.0
| 979
|
object Versions extends WebJarsVersions with ScalaJSVersions with SharedVersions
{
val scala = "2.12.3"
val akkaHttp = "10.0.10"
val bcrypt = "3.1"
val ammonite = "1.0.0"
val apacheCodec = "1.10"
val akkaHttpExtensions = "0.0.16"
val controls = "0.0.27"
}
trait ScalaJSVersions {
val jqueryFacade = "1.0"
val semanticUIFacade = "0.0.1"
val dom = "0.9.2"
val codemirrorFacade = "5.22.0-0.8"
}
//versions for libs that are shared between client and server
trait SharedVersions
{
val scalaRx = "0.3.2"
val scalaTags = "0.6.2"
val scalaCSS = "0.5.3"
val scalaTest = "3.0.4"
val macroParadise = "2.1.0"
}
trait WebJarsVersions{
val jquery = "3.2.1"
val semanticUI = "2.2.10"
val codemirror = "5.24.2"
}
|
denigma/akka-http-extensions
|
project/Versions.scala
|
Scala
|
mpl-2.0
| 743
|
---
layout: "guides"
page_title: "Clustering"
sidebar_current: "guides-operations-cluster"
description: |-
Learn how to cluster Nomad.
---
# Clustering
Nomad models infrastructure into regions and datacenters. Servers reside at the
regional layer and manage all state and scheduling decisions for that region.
Regions contain multiple datacenters, and clients are registered to a single
datacenter (and thus a region that contains that datacenter). For more details on
the architecture of Nomad and how it models infrastructure see the [architecture
page](/docs/internals/architecture.html).
There are multiple strategies available for creating a multi-node Nomad cluster:
1. <a href="/guides/operations/cluster/manual.html">Manual Clustering</a>
1. <a href="/guides/operations/cluster/automatic.html">Automatic Clustering with Consul</a>
1. <a href="/guides/operations/cluster/cloud_auto_join.html">Cloud Auto-join</a>
Please refer to the specific documentation links above or in the sidebar for
more detailed information about each strategy.
|
nak3/nomad
|
website/source/guides/operations/cluster/bootstrapping.html.md
|
Markdown
|
mpl-2.0
| 1,052
|
/**
* Copyright 2011 Paul Lewis. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
html, body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
}
#library {
display: none;
}
canvas {
-webkit-transform: translateZ(0);
}
|
heliogabalo/The-side-of-the-source
|
Codigo/Games/Efects/Fireworks/Css/main.css
|
CSS
|
mpl-2.0
| 823
|
using System.Collections.Generic;
using Alex.Blocks.State;
using Alex.Common.Utils.Vectors;
using Alex.Worlds.Chunks;
namespace Alex.Worlds.Abstraction
{
public interface IBlockAccess
{
ChunkColumn GetChunk(BlockCoordinates coordinates, bool cacheOnly = false);
ChunkColumn GetChunk(ChunkCoordinates coordinates, bool cacheOnly = false);
void SetSkyLight(BlockCoordinates coordinates, byte skyLight);
byte GetSkyLight(BlockCoordinates coordinates);
byte GetBlockLight(BlockCoordinates coordinates);
void SetBlockLight(BlockCoordinates coordinates, byte blockLight);
bool TryGetBlockLight(BlockCoordinates coordinates, out byte blockLight);
void GetLight(BlockCoordinates coordinates, out byte blockLight, out byte skyLight);
int GetHeight(BlockCoordinates coordinates);
IEnumerable<ChunkSection.BlockEntry> GetBlockStates(int positionX, int positionY, int positionZ);
BlockState GetBlockState(BlockCoordinates position);
void SetBlockState(int x,
int y,
int z,
BlockState block,
int storage,
BlockUpdatePriority priority = BlockUpdatePriority.High | BlockUpdatePriority.Neighbors);
Biome GetBiome(BlockCoordinates coordinates);
BlockState GetBlockState(int x, int y, int z) => GetBlockState(new BlockCoordinates(x, y, z));
}
}
|
kennyvv/Alex
|
src/Alex/Worlds/Abstraction/IBlockAccess.cs
|
C#
|
mpl-2.0
| 1,417
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XKB_KEY_Georgian_ban` constant in crate `wayland_kbd`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_Georgian_ban">
<title>wayland_kbd::keysyms::XKB_KEY_Georgian_ban - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_Georgian_ban', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_Georgian_ban</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-4700' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#1885' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XKB_KEY_Georgian_ban: <a href='../../std/primitive.u32.html'>u32</a><code> = </code><code>0x10010d1</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "wayland_kbd";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
wayland_kbd/keysyms/constant.XKB_KEY_Georgian_ban.html
|
HTML
|
mpl-2.0
| 4,017
|
/*
* Copyright © 2017-2018 Cloudveil Technology Inc.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.Sqlite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using NLog;
using System.Diagnostics;
using CloudVeil.Core.Windows.Util;
using Filter.Platform.Common.Util;
namespace FilterProvider.Common.Data.Filtering
{
/// <summary>
/// The BagOfTextTriggers class serves the sole purpose of storing bits of text in a database,
/// and then reponding to queries with answers about whether this class has stored the text in
/// question.
/// </summary>
/// <remarks>
/// This class is a super special snowflake that will unpredictably get triggered.
/// </remarks>
public class BagOfTextTriggers : IDisposable
{
/// <summary>
/// Our Sqlite connection.
/// </summary>
private SqliteConnection m_connection;
/// <summary>
/// Holds whether or not this instance has any triggers loaded.
/// </summary>
private volatile bool m_hasTriggers = false;
/// <summary>
/// Get whether or not this instance has any triggers loaded.
/// </summary>
public bool HasTriggers
{
get
{
return m_hasTriggers;
}
}
/// <summary>
/// A bloom filter to help determine if a trigger is in the SQL database.
/// </summary>
public BloomFilter<string> TriggerFilter { get; set; }
/// <summary>
/// A bloom filter to prefetch results for first words, so we don't have to do a SQL call.
/// </summary>
public BloomFilter<string> FirstWordFilter { get; set; }
private Logger m_logger;
/// <summary>
/// Constructs a new BagOfTextTriggers.
/// </summary>
/// <param name="dbAbsolutePath">
/// The absolute path where the database exists or should be created.
/// </param>
/// <param name="overwrite">
/// If true, and a file exists at the supplied absolute db path, it will be deleted first.
/// Default is true.
/// </param>
/// <param name="useMemory">
/// If true, the database will be created as a purely in-memory database.
/// </param>
public BagOfTextTriggers(string dbAbsolutePath, bool overwrite = true, bool useMemory = false, Logger logger = null)
{
m_logger = logger;
if(!useMemory && overwrite && File.Exists(dbAbsolutePath))
{
File.Delete(dbAbsolutePath);
}
bool isNew = !File.Exists(dbAbsolutePath);
if(useMemory)
{
var version = typeof(BagOfTextTriggers).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
var rnd = new Random();
var rndNum = rnd.Next();
var generatedDbName = string.Format("{0} {1} - {2}", nameof(BagOfTextTriggers), version, rndNum);
// "Data Source = :memory:; Cache = shared;"
var cb = new SqliteConnectionStringBuilder();
cb.Mode = SqliteOpenMode.Memory;
cb.Cache = SqliteCacheMode.Shared;
cb.DataSource = generatedDbName;
m_connection = new SqliteConnection(cb.ToString());
//m_connection = new SqliteConnection("FullUri=file::memory:?cache=shared;Version=3;");
}
else
{
var cb = new SqliteConnectionStringBuilder();
cb.Mode = SqliteOpenMode.ReadWriteCreate;
cb.Cache = SqliteCacheMode.Shared;
cb.DataSource = dbAbsolutePath;
m_connection = new SqliteConnection(cb.ToString());
//m_connection = new SqliteConnection(string.Format("Data Source={0};Version=3;", dbAbsolutePath));
}
//m_connection.Flags = SQLiteConnectionFlags.UseConnectionPool | SQLiteConnectionFlags.NoConvertSettings | SQLiteConnectionFlags.NoVerifyTypeAffinity;
m_connection.Open();
ConfigureDatabase();
CreateTables();
}
/// <summary>
/// Configures the database page size, cache size for optimal performance according to our
/// needs.
/// </summary>
private async void ConfigureDatabase()
{
using(var cmd = m_connection.CreateCommand())
{
cmd.CommandText = "PRAGMA page_size=65536;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA cache_size=-65536;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA soft_heap_limit=131072;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA synchronous=OFF;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA journal_mode=MEMORY;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA locking_mode=NORMAL;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA temp_store=2;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA ignore_check_constraints=TRUE;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA cell_size_check=FALSE;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA cache_spill=FALSE;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA automatic_index=FALSE;";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = "PRAGMA busy_timeout=20000;";
await cmd.ExecuteNonQueryAsync();
}
}
/// <summary>
/// Creates needed tables on the source database if they do not exist.
/// </summary>
private async void CreateTables()
{
using(var tsx = m_connection.BeginTransaction())
using(var command = m_connection.CreateCommand())
{
command.CommandText = "CREATE TABLE IF NOT EXISTS TriggerIndex (TriggerText VARCHAR(255), CategoryId INT16)";
await command.ExecuteNonQueryAsync();
command.CommandText = "CREATE TABLE IF NOT EXISTS FirstWordIndex (FirstWordText VARCHAR(255), IsWholeTrigger INT16, CategoryId INT16)";
await command.ExecuteNonQueryAsync();
tsx.Commit();
}
}
/// <summary>
/// Creates needed indexes on the database if they do not exist.
/// </summary>
private void CreatedIndexes()
{
using(var command = m_connection.CreateCommand())
{
command.CommandText = "CREATE INDEX IF NOT EXISTS trigger_index ON TriggerIndex (TriggerText)";
command.ExecuteNonQuery();
command.CommandText = "CREATE INDEX IF NOT EXISTS first_word_index ON FirstWordIndex (FirstWordText)";
command.ExecuteNonQuery();
}
}
/// <summary>
/// Finalize the database for read only access. This presently builds indexes if they do not
/// exist, and is meant to be called AFTER all bulk insertions are complete. Note that
/// calling this command does not rebuild the Sqlite connection to enforce read-only mode.
/// Write access is still possible after calling.
/// </summary>
public void FinalizeForRead()
{
CreatedIndexes();
}
public void InitializeBloomFilters()
{
int firstWordCount;
using (var countCmd = m_connection.CreateCommand())
{
countCmd.CommandText = "SELECT COUNT(1) FROM FirstWordIndex;";
using (var reader = countCmd.ExecuteReader())
{
reader.Read();
firstWordCount = reader.GetInt32(0);
}
}
FirstWordFilter = new BloomFilter<string>(firstWordCount == 0 ? 100 : firstWordCount);
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = "SELECT FirstWordText FROM FirstWordIndex;";
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
string firstWord = reader.GetString(0);
FirstWordFilter.Add(firstWord);
}
}
}
int triggerCount;
using (var countCmd = m_connection.CreateCommand())
{
countCmd.CommandText = "SELECT COUNT(1) FROM TriggerIndex;";
using (var reader = countCmd.ExecuteReader())
{
reader.Read();
triggerCount = reader.GetInt32(0);
}
}
TriggerFilter = new BloomFilter<string>(triggerCount == 0 ? 100 : triggerCount);
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = "SELECT TriggerText FROM TriggerIndex;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string triggerWord = reader.GetString(0);
TriggerFilter.Add(triggerWord);
}
}
}
m_logger.Info($"trigger count = {triggerCount}, first word count = {firstWordCount}");
}
private class StoreCommands : IDisposable
{
SqliteConnection connection;
SqliteCommand firstWordCommand;
SqliteCommand triggerCommand;
public StoreCommands(SqliteConnection connection)
{
this.connection = connection;
firstWordCommand = connection.CreateCommand();
triggerCommand = connection.CreateCommand();
firstWordCommand.CommandText = "INSERT INTO FirstWordIndex VALUES ($firstWord, $isWholeTrigger, $categoryId)";
triggerCommand.CommandText = "INSERT INTO TriggerIndex VALUES ($trigger, $categoryId)";
var domainParam = new SqliteParameter("$trigger", DbType.String);
var categoryIdParam = new SqliteParameter("$categoryId", DbType.Int16);
triggerCommand.Parameters.Add(domainParam);
triggerCommand.Parameters.Add(categoryIdParam);
var firstWordParam = new SqliteParameter("$firstWord", DbType.String);
var isWholeTriggerParam = new SqliteParameter("$isWholeTrigger", DbType.Int16);
var firstWordCategoryIdParam = new SqliteParameter("$categoryId", DbType.Int16);
firstWordCommand.Parameters.Add(firstWordParam);
firstWordCommand.Parameters.Add(isWholeTriggerParam);
firstWordCommand.Parameters.Add(firstWordCategoryIdParam);
}
public async Task<bool> StoreTrigger(string line, short categoryId)
{
string trimmedLine = line.Trim();
if (trimmedLine.Length > 0)
{
List<string> trimmedLineParts = Split(trimmedLine);
triggerCommand.Parameters[0].Value = trimmedLine;
triggerCommand.Parameters[1].Value = categoryId;
firstWordCommand.Parameters[0].Value = trimmedLineParts.First();
firstWordCommand.Parameters[1].Value = trimmedLineParts.Count == 1;
firstWordCommand.Parameters[2].Value = categoryId;
await triggerCommand.ExecuteNonQueryAsync();
await firstWordCommand.ExecuteNonQueryAsync();
return true;
}
else
{
return false;
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
firstWordCommand.Dispose();
triggerCommand.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~StoreCommands() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
public async Task<int> LoadStoreFromList(IEnumerable<string> inputList, short categoryId)
{
int loaded = 0;
using (var transaction = m_connection.BeginTransaction())
{
using (var storeCommands = new StoreCommands(m_connection))
{
foreach(string line in inputList)
{
if (line == null) continue;
if (await storeCommands.StoreTrigger(line, categoryId)) ++loaded;
}
}
transaction.Commit();
}
m_hasTriggers = loaded > 0;
return loaded;
}
/// <summary>
/// Loads each line read from the supplied stream as a new trigger and stores it.
/// </summary>
/// <param name="inputStream">
/// The source input stream where each line represents a unique trigger.
/// </param>
/// <param name="categoryId">
/// The category ID that all loaded triggers are to be assigned.
/// </param>
/// <returns>
/// The total number of triggers loaded from the supplied input stream.
/// </returns>
public async Task<int> LoadStoreFromStream(Stream inputStream, short categoryId)
{
int loaded = 0;
using(var transaction = m_connection.BeginTransaction())
{
using (var storeCommands = new StoreCommands(m_connection))
{
string line = null;
using (var sw = new StreamReader(inputStream))
{
while ((line = await sw.ReadLineAsync()) != null)
{
if (await storeCommands.StoreTrigger(line, categoryId)) ++loaded;
}
}
}
transaction.Commit();
}
m_hasTriggers = loaded > 0;
return loaded;
}
/// <summary>
/// Checks to see if the string supplied exactly matches a known trigger.
/// </summary>
/// <param name="input">
/// </param>
/// <param name="firstMatchCategory">
/// </param>
/// <returns>
/// </returns>
public bool IsTrigger(string input, out short firstMatchCategory, Func<short, bool> categoryAppliesCb)
{
using(var cmd = m_connection.CreateCommand())
{
cmd.CommandText = @"SELECT * from TriggerIndex where TriggerText = $trigger";
var domainSumParam = new SqliteParameter("$trigger", System.Data.DbType.String);
domainSumParam.Value = input.ToLower();
cmd.Parameters.Add(domainSumParam);
using(var reader = cmd.ExecuteReader())
{
if(!reader.HasRows)
{
firstMatchCategory = -1;
return false;
}
while(reader.Read())
{
var thisCat = reader.GetInt16(1);
if(categoryAppliesCb(thisCat))
{
firstMatchCategory = thisCat;
return true;
}
}
}
}
firstMatchCategory = -1;
return false;
}
/// <summary>
/// Checks to see if the string supplied contains at least one substring that is a trigger.
/// The supplied string will be broken apart by a static internal logic to perform this
/// check.
/// </summary>
/// <param name="input">
/// The input string to search for triggers.
/// </param>
/// <param name="firstMatchCategory">
/// The category of the first discovered trigger. Will be -1 on failure.
/// </param>
/// <param name="rebuildAndTestFragments">
/// If no match is found from a single substring fragment, and this parameter is set to true,
/// the function will begin reconstructing new ordered sentences dynamically from all
/// extracted fragments to see if a combination of substrings forms a trigger.
/// </param>
/// <param name="maxRebuildLen">
/// If the rebuildAndTestFragments parameter is set to true, this can be set to the maximum
/// number of substrings to combine in search for a match. By leaving the parameter at its
/// default value, -1, every possible combination in every length will be tried. For example,
/// if you're only wanting to match 3 works like "I dont care", you would set this parameter
/// to a value of 3.
///
/// Note that there are contraints on how long these combinations can be, so regardless of
/// what the value is here, strings created from joins internally will be skipped when they
/// exceed internal database column limits.
/// </param>
/// <returns>
/// True if the supplied text contained one or more substrings that were indentified as a
/// trigger.
/// </returns>
public bool ContainsTrigger(string input, out short firstMatchCategory, out string matchedTrigger, Func<short, bool> categoryAppliesCb, bool rebuildAndTestFragments = false, int maxRebuildLen = -1)
{
firstMatchCategory = -1;
matchedTrigger = null;
if(!m_hasTriggers)
{
return false;
}
// LoggerUtil.GetAppWideLogger().Info("Triggers for input: " + input);
var split = Split(input);
/*using (FileStream debugStream = new FileStream(@"C:\ProgramData\CloudVeil\textTriggerDebug.txt", FileMode.Append))
using (StreamWriter writer = new StreamWriter(debugStream))*/
using (var myConn = new SqliteConnection(m_connection.ConnectionString))
{
myConn.Open();
int itr = 0;
SqliteCommand triggerCommand = null;
using (var tsx = myConn.BeginTransaction())
using (var cmd = myConn.CreateCommand())
{
cmd.CommandText = @"SELECT * from FirstWordIndex where FirstWordText = $trigger";
var domainSumParam = new SqliteParameter("$trigger", System.Data.DbType.String);
cmd.Parameters.Add(domainSumParam);
bool skippingTags = false;
bool skippingScript = false;
bool quoteReached = false;
bool collectingImportantAttributes = false;
bool isClosingTag = false;
List<string> newSplit = new List<string>();
List<List<string>> wordLists = new List<List<string>>();
List<List<string>> listsToRemove = new List<List<string>>(maxRebuildLen);
foreach (var s in split)
{
// Completely skip closing tags.
if (s.Length > 2 && s[0] == '<' && s[1] == '/' && s[s.Length - 1] == '>')
{
isClosingTag = true;
}
// We require some more complex determinations for opening tags as they may have important
// text inside them.
if (s.Length >= 2 && s[0] == '<' && s[1] != '/' && s.Length > 1 && s.Length < 10)
{
skippingTags = true;
}
switch (s.ToLower())
{
case "<script":
case "<style":
skippingScript = true;
break;
case "</script>":
case "</style>":
skippingScript = false;
break;
case ">":
skippingTags = false;
break;
case "alt":
case "title":
case "href":
collectingImportantAttributes = true;
break;
case "\"":
case "\'":
quoteReached = !quoteReached;
if (!quoteReached)
{
collectingImportantAttributes = false;
}
break;
}
if (isClosingTag)
{
isClosingTag = false;
continue;
}
if (collectingImportantAttributes)
{
newSplit.Add(s);
itr++;
}
else if (!skippingTags && !skippingScript && s != ">")
{
newSplit.Add(s);
itr++;
}
if (skippingTags && !collectingImportantAttributes)
{
continue;
}
listsToRemove.Clear();
// Check word lists.
foreach (var list in wordLists)
{
if (list.Count >= maxRebuildLen)
{
listsToRemove.Add(list);
}
else
{
list.Add(s);
}
}
foreach (var l in listsToRemove)
{
wordLists.Remove(l);
}
// Check word lists.
foreach (var list in wordLists)
{
string triggerCandidate = string.Join(" ", list);
if (!TriggerFilter.Contains(triggerCandidate))
{
continue;
}
if (triggerCommand == null)
{
triggerCommand = myConn.CreateCommand();
triggerCommand.CommandText = "SELECT * FROM TriggerIndex WHERE TriggerText = $trigger";
var wholeTriggerDomainSumParam = new SqliteParameter("$trigger", System.Data.DbType.String);
wholeTriggerDomainSumParam.Value = input.ToLower();
triggerCommand.Parameters.Add(wholeTriggerDomainSumParam);
}
triggerCommand.Parameters[0].Value = triggerCandidate;
using (var triggerReader = triggerCommand.ExecuteReader())
{
while (triggerReader.Read())
{
var thisCat = triggerReader.GetInt16(1);
if (categoryAppliesCb(thisCat))
{
firstMatchCategory = thisCat;
matchedTrigger = string.Join(" ", list);
return true;
}
}
}
}
// TODO: Apply bloom filters to this problem.
// We need a bloom filter for first words and a bloom filter for triggers for maximum effect.
if (!FirstWordFilter.Contains(s))
{
continue;
}
cmd.Parameters[0].Value = s;
using (var reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
continue;
}
while (reader.Read())
{
var isWholeTrigger = reader.GetInt16(1);
if (isWholeTrigger > 0)
{
var thisCat = reader.GetInt16(2);
if (categoryAppliesCb(thisCat))
{
firstMatchCategory = thisCat;
matchedTrigger = s;
return true;
}
}
else
{
var newList = new List<string>(maxRebuildLen);
newList.Add(s);
wordLists.Add(newList);
break;
}
}
}
}
tsx.Commit();
}
}
return false;
}
private static List<string> Split(string input)
{
var sb = new StringBuilder();
var res = new List<string>();
var len = input.Length;
for(var i = 0; i < len; ++i)
{
switch(input[i])
{
case '<':
if(sb.Length > 0)
{
res.Add(sb.ToString());
sb.Clear();
}
sb.Append('<');
if(i < len-1 && input[i + 1] == '/')
{
while(input[i] != '>')
{
i++;
if(i >= len) {
break;
}
sb.Append(input[i]);
}
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case '-':
case '.':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
{
sb.Append(char.ToLower(input[i]));
}
break;
case '>':
res.Add(sb.ToString());
sb.Clear();
res.Add(">");
break;
case '"':
case '\'':
res.Add(sb.ToString());
sb.Clear();
res.Add(new string(input[i], 1));
break;
default:
{
if(sb.Length > 0)
{
res.Add(sb.ToString());
sb.Clear();
}
}
break;
}
}
if(sb.Length > 0)
{
res.Add(sb.ToString());
sb.Clear();
}
return res;
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if(!disposedValue)
{
if(disposing)
{
if(m_connection != null)
{
m_connection.Close();
m_connection = null;
}
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free
// unmanaged resources. ~BagOfTextTriggers() { // Do not change this code. Put cleanup
// code in Dispose(bool disposing) above. Dispose(false); }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
}
|
cloudveiltech/Citadel-Windows
|
FilterProvider.Common/Data/Filtering/BagOfTextTriggers.cs
|
C#
|
mpl-2.0
| 33,415
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XKB_KEY_braille_dots_13478` constant in crate `wayland_kbd`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_braille_dots_13478">
<title>wayland_kbd::keysyms::XKB_KEY_braille_dots_13478 - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_braille_dots_13478', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_braille_dots_13478</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-1980' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#2311' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XKB_KEY_braille_dots_13478: <a class='primitive' href='../../std/primitive.u32.html'>u32</a><code> = </code><code>16787661</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "wayland_kbd";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
wayland_kbd/keysyms/constant.XKB_KEY_braille_dots_13478.html
|
HTML
|
mpl-2.0
| 4,324
|
<!DOCTYPE html>
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>CSS Test: CSS display:contents</title>
<link rel="author" title="Mats Palmgren" href="https://bugzilla.mozilla.org/show_bug.cgi?id=907396">
<link rel="help" href="http://dev.w3.org/csswg/css-display">
<style type="text/css">
html,body {
color:black; background-color:white; font-size:16px; padding:0; margin:0;
}
.table { display:table; border-collapse:collapse; border: blue solid 1pt;}
.itable { display:inline-table; }
.caption { display:table-caption; }
.cell { display:table-cell; border:inherit; }
.row { display:table-row; border: green dashed 1pt; }
.rowg { display:table-row-group; }
.head { display:table-header-group; }
.foot { display:table-footer-group; }
.col { display:table-column; }
.colg { display:table-column-group; }
.flex { display:flex; }
.iflex { display:inline-flex; }
.li { display:list-item; }
.ib { display:inline-block; }
.inline { display:inline; }
.columns { -moz-columns:2; columns:2; height:4em; }
.contents { display:contents; align-items:inherit; justify-items:inherit; }
.c1 { color:lime; }
.c2 { background:blue; color:pink; }
.c3 { color:teal; }
.c4 { color:green; }
.c5 { color:silver; }
.c6 { color:cyan; }
.c7 { color:magenta; }
.c8 { color:yellow; }
.c9 { color:grey; }
.c10{ color:black; }
.b { background:inherit; }
</style>
</head>
<body style="color:red">
<div class="contents c1"><div class="contents c2"><div class="caption">1<span class="b">1</span></div></div></div>
<div class="contents c2"><div class="row">2a<div class="cell">2<div class="contents c2">b<span class="b">b</span></div></div></div></div>
<div class="contents c3"><div class="cell">3</div></div>
<div class="contents c4"><div class="rowg">4</div></div>
<div class="contents c5"><div class="cell">5a</div></div>
<div class="cell c5">5b</div>
<div class="contents c6"><div class="head">6</div></div>
<div class="contents c7"><div class="cell"><div class="contents c2">7<span class="b">a</span></div></div></div>
<div class="contents c8"><div class="cell">7b</div></div>
<div class="contents c9"><div class="foot">8</div></div>
<div class="contents c9"><div class="foot">9<div class="contents c2">a<span class="b">b</span>c</div></div></div>
<div class="contents c10"><div class="cell">10</div></div>
<div class="table" style="float:right">
<div class="contents c1"><div class="contents c2"><div class="caption">1<span class="b">1</span></div></div></div>
<div class="contents c2"><div class="row">2a<div class="cell">2<div class="contents c2">b<span class="b">b</span></div></div></div></div>
<div class="contents c3"><div class="cell">3</div></div>
<div class="contents c4"><div class="rowg">4</div></div>
<div class="contents c5"><div class="cell">5a</div></div>
<div class="cell c5">5b</div>
<div class="contents c6"><div class="head">6</div></div>
<div class="contents c7"><div class="cell"><div class="contents c2">7<span class="b">a</span></div></div></div>
<div class="contents c8"><div class="cell">7b</div></div>
<div class="contents c9"><div class="foot">8</div></div>
<div class="contents c9"><div class="foot">9<div class="contents c2">a<span class="b">b</span>c</div></div></div>
<div class="contents c10"><div class="cell">10</div></div>
</div>
<div class="flex c1">
0
<div class="contents c1">x</div>
<div class="contents c1"><div class="contents c2">y</div></div>
<div class="contents c1"><div class="contents c2"><div class="">1<span class="b">1</span></div></div></div>
<div class="contents c2"><div class="inline">2a<div class="">2<div class="contents c2">b<span class="b">b</span></div></div></div></div>
<div class="contents c3"><div class="inline">3</div></div>
<div class="inline"><div class="contents c4">4</div></div>
<div class=""><div class="contents c5">5a</div></div>
<div class=" c5">5b</div>
<div class="contents c6"><div class="">6</div></div>
<div class="ib"><div class="contents c7"><div class="contents c2">7<span class="b">a</span></div></div></div>
<div class="contents c9"><div class="">8</div></div>
<div class="contents c9"><div class="contents">9<div class="contents c2">a<span class="b">b</span>c</div></div></div>
<div class="contents c10"><div class="">10</div></div>
</div>
<div class="flex"><div class="contents c2">
0
<div class="contents c1">x</div>
<div class="contents c1"><div class="contents c2">y</div></div>
<div class="contents c1"><div class="contents c2"><div class="">1<span class="b">1</span></div></div></div>
<div class="contents c2"><div class="inline">2a<div class="">2<div class="contents c2">b<span class="b">b</span></div></div></div></div>
<div class="contents c3"><div class="inline">3</div></div>
<div class=""><div class="contents c4">4</div></div>
<div class=""><div class="contents c5">5a</div></div>
<div class=" c5">5b</div>
<div class="contents c6"><div class="">6</div></div>
<div class="ib"><div class="contents c7"><div class="contents c2">7<span class="b">a</span></div></div></div>
<div class="contents c9"><div class="">8</div></div>
<div class="contents c9"><div class="contents">9<div class="contents c2">a<span class="b">b</span>c</div></div></div>
<div class="contents c10"><div class="">10</div></div>
</div></div>
<div class="iflex"><div class="contents c2">
0
</div></div>
<div class="iflex"><div class="contents c2">
0
<div class="contents c1">1</div>
2
</div></div>
<div class="iflex"><div class="contents c2">
0
<div class="c1">1</div>
2
</div></div>
<div class="iflex c3">
0
<div class="contents c2"><div class="c1">1</div></div>
2
</div>
<div class="iflex c3">
<div class="contents c2">0</div>
<div class="contents c2"><div class="c1">1</div></div>
<div class="contents c2">2</div>
</div>
<div class="iflex c3">
<div class="inline">0</div>
<div class="contents"><div class="inline c1">1</div></div>
<div class="inline">2</div>
</div>
<ul><li class="c1"><div class="contents c2">
0
<div class="contents c1">x</div>
<div class="contents c1"><div class="contents c2">y</div></div>
<div class="contents c1"><div class="contents c2"><div class="">1<span class="b">1</span></div></div></div>
<div class="contents c2"><div class="inline">2a<div class="">2<div class="contents c2">b<span class="b">b</span></div></div></div></div>
<div class="contents c3"><div class="inline">3</div></div>
<div class="inline"><div class="contents c4">4</div></div>
<div class=""><div class="contents c5">5a</div></div>
<div class=" c5">5b</div>
<div class="contents c6"><div class="">6</div></div>
<div class="ib"><div class="contents c7"><div class="contents c2">7<span class="b">a</span></div></div></div>
<div class="contents c9"><div class="">8</div></div>
<div class="contents c9"><div class="contents">9<div class="contents c2">a<span class="b">b</span>c</div></div></div>
<div class="contents c10"><div class="">10</div></div>
</div></li>
</ul>
<div class="columns">
<div class="contents c1"><div class="contents c2"><div>1<span class="b">1</span></div></div></div>
<div class="contents c2"><div>2</div></div>
<div class="contents c3"><div>3</div></div>
</div>
<div class="columns">
<div class="columns contents">
<div class="contents c1"><div class="contents c2"><div>1<span class="b">1</span></div></div></div>
<div class="contents c2"><div>2</div></div>
<div class="contents c3"><div>3</div></div>
</div>
</div>
<div class="contents c3"><!-- comment node --></div>
<div class="contents c3"><?PI ?></div>
<span class="c2"><legend class="contents c1">Legend</legend><legend class="contents c1">Legend</legend></span>
<br clear="all">
<span class="c3">x<div class="contents c1" style="float:left">float:left</div></span>
<span class="c3">y<div class="contents c1" style="position:absolute">position:absolute</div></span>
<!-- Stuff below should simply ignore having display:contents -->
<fieldset class="contents c1"><legend class="contents">Legend</legend>fieldset</fieldset>
<button class="contents c1">but<span>ton</span></button>
<select class="contents c1"><option>select</select>
</body>
</html>
|
Yukarumya/Yukarum-Redfoxes
|
layout/reftests/css-display/display-contents-acid.html
|
HTML
|
mpl-2.0
| 8,185
|
# CursorBindBehaviour
- **класс** `CursorBindBehaviour` (`behaviour\custom\CursorBindBehaviour`) **унаследован от** [`AbstractBehaviour`](https://github.com/jphp-compiler/develnext/blob/master/dn-app-framework/api-docs/classes/php/gui/framework/behaviour/custom/AbstractBehaviour.ru.md)
- **пакет** `framework`
- **исходники** `behaviour/custom/CursorBindBehaviour.php`
**Описание**
Class CursorBindBehaviour
---
#### Свойства
- `->`[`hideOrigin`](#prop-hideorigin) : `bool`
- `->`[`offsetX`](#prop-offsetx) : `int`
- `->`[`offsetY`](#prop-offsety) : `int`
- `->`[`centered`](#prop-centered) : `bool`
- `->`[`cursorX`](#prop-cursorx) : `int`
- `->`[`cursorY`](#prop-cursory) : `int`
- `->`[`_timer`](#prop-_timer) : `UXAnimationTimer`
- *См. также в родительском классе* [AbstractBehaviour](https://github.com/jphp-compiler/develnext/blob/master/dn-app-framework/api-docs/classes/php/gui/framework/behaviour/custom/AbstractBehaviour.ru.md).
---
#### Методы
- `->`[`applyImpl()`](#method-applyimpl)
- `->`[`getCode()`](#method-getcode)
- `->`[`free()`](#method-free)
- См. также в родительском классе [AbstractBehaviour](https://github.com/jphp-compiler/develnext/blob/master/dn-app-framework/api-docs/classes/php/gui/framework/behaviour/custom/AbstractBehaviour.ru.md)
---
# Методы
<a name="method-applyimpl"></a>
### applyImpl()
```php
applyImpl(mixed $target): void
```
---
<a name="method-getcode"></a>
### getCode()
```php
getCode(): void
```
---
<a name="method-free"></a>
### free()
```php
free(): void
```
|
jphp-compiler/develnext
|
dn-app-framework/api-docs/classes/behaviour/custom/CursorBindBehaviour.ru.md
|
Markdown
|
mpl-2.0
| 1,642
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `DefineDOMInterface` fn in crate `script`.">
<meta name="keywords" content="rust, rustlang, rust-lang, DefineDOMInterface">
<title>script::dom::bindings::codegen::Bindings::TouchBinding::DefineDOMInterface - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../../../../index.html'>script</a>::<wbr><a href='../../../../index.html'>dom</a>::<wbr><a href='../../../index.html'>bindings</a>::<wbr><a href='../../index.html'>codegen</a>::<wbr><a href='../index.html'>Bindings</a>::<wbr><a href='index.html'>TouchBinding</a></p><script>window.sidebarCurrent = {name: 'DefineDOMInterface', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../../../../../index.html'>script</a>::<wbr><a href='../../../../index.html'>dom</a>::<wbr><a href='../../../index.html'>bindings</a>::<wbr><a href='../../index.html'>codegen</a>::<wbr><a href='../index.html'>Bindings</a>::<wbr><a href='index.html'>TouchBinding</a>::<wbr><a class='fn' href=''>DefineDOMInterface</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-81083' class='srclink' href='../../../../../../src/script/home/servo/buildbot/slave/doc/build/target/debug/build/script-4d3bb93218cab884/out/Bindings/TouchBinding.rs.html#479-489' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe fn DefineDOMInterface(cx: <a class='primitive' href='../../../../../../std/primitive.pointer.html'>*mut </a><a class='enum' href='../../../../../../js/jsapi/enum.JSContext.html' title='js::jsapi::JSContext'>JSContext</a>, global: <a class='type' href='../../../../../../js/jsapi/type.HandleObject.html' title='js::jsapi::HandleObject'>HandleObject</a>)</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../../../../";
window.currentCrate = "script";
window.playgroundUrl = "";
</script>
<script src="../../../../../../jquery.js"></script>
<script src="../../../../../../main.js"></script>
<script defer src="../../../../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
script/dom/bindings/codegen/Bindings/TouchBinding/fn.DefineDOMInterface.html
|
HTML
|
mpl-2.0
| 5,082
|
import os
from outlawg import Outlawg
from fftool import (
DIR_CONFIGS,
local
)
from ini_handler import IniHandler
Log = Outlawg()
env = IniHandler()
env.load_os_config(DIR_CONFIGS)
def launch_firefox(profile_path, channel, logging, nspr_log_modules=''):
"""relies on the other functions (download, install, profile)
having completed.
"""
FIREFOX_APP_BIN = env.get(channel, 'PATH_FIREFOX_BIN_ENV')
Log.header('LAUNCH FIREFOX')
print("Launching Firefox {0} with profile: {1}".format(
channel,
profile_path)
)
cmd = '"{0}" -profile "{1}"'.format(FIREFOX_APP_BIN, profile_path)
print('CMD: ' + cmd)
# NSPR_LOG_MODULES
if nspr_log_modules:
Log.header('FIREFOX NSPR_LOG_MODULES LOGGING')
os.environ['NSPR_LOG_MODULES'] = nspr_log_modules
local(cmd, logging)
|
rpappalax/ff-tool
|
fftool/firefox_run.py
|
Python
|
mpl-2.0
| 849
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDiffMat.sum(axis=1)
distances = pow(sqDistances,0.5)
sortedDistIndicies = distances.argsort()
classCount = {}
for i in range(k):
voteIlabel = labels[ sortedDistIndicies[i] ]
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
#sort by the apperance number
sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)
return sortedClassCount[0][0]
def mat_to_vect(filename):
vect = []
data = open(filename)
for i in range(32):
temp = data.readline()
for j in range(32):
try:
vect.append(int(temp[j]))
except(ValueError):
print temp[j],'error',ValueError
return vect
def load_train_data():
train_lables = []
size = 100
train_data = np.zeros((size*10,1024))
for i in range(10):
for j in range(size):
train_lables.append(i)
train_data[i*100+j,:] = mat_to_vect('train/%s/%s.txt' %( i,j ))
return train_lables,train_data
def classnumCut(fileName):
return int(fileName[0])
|
leonidas141/HIT-ML-2016-report
|
load.py
|
Python
|
mpl-2.0
| 1,459
|
package simulator.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import simulator.Simulator;
/**
* VariableDistribution.java
*
* Class representing a variable distribution which produces sequences of random
* numbers with a given mean and SD.
*
* Created on 01-Dec-2011 City University BSc Computing with Artificial
* Intelligence Project title: Building a TD Simulator for Real-Time Classical
* Conditioning
*
* @supervisor Dr. Eduardo Alonso
* @author Jonathan Gray
*
*/
public class VariableDistribution implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4932520581988365938L;
/** Lazily initialized random seed for variable distributions. **/
private static long randomSeed = 0;
public static void newRandomSeed() {
randomSeed = System.currentTimeMillis();
}
/**
*
* @return the seed for the random number generator.
*/
public static long randomSeed() {
if (randomSeed == 0) {
randomSeed = System.currentTimeMillis();
}
return randomSeed;
}
/** Mean for this distribution. **/
private double mean;
/** Standard deviation for this distribution. **/
private float sd;
/** List of onsets. **/
private List<Double> onsets;
/** Random generator for variable onsets. **/
protected Random random;
/** Random seed. **/
private long seed;
/** Trial index. **/
private int index;
/** Flag set to indicate this distribution must be rebuilt. **/
private boolean isChanged;
/** True if we are using geometric mean. **/
private boolean meanType;
/** Total number of trials. **/
private int trials;
/** Collection of shuffled onsets. **/
private List<List<Double>> shuffledOnsets;
private transient ListIterator<List<Double>> onsetsIt;
/**
* Creates a new variable distribution with the specified mean and standard
* deviation and a default random seed.
*
* @param mean
* The mean for the distribution
* @param sd
* The standard deviation for the distribution
*/
public VariableDistribution(final double mean, final float sd, int trials) {
this.setSd(sd);
this.mean = mean;
seed = randomSeed();
random = new Random(randomSeed());
index = 0;
this.trials = trials;
meanType = false;
onsets = new ArrayList<Double>();
isChanged = false;
shuffledOnsets = new ArrayList<List<Double>>();
onsetsIt = shuffledOnsets.listIterator();
}
/**
* Creates a new variable distribution with a specified random seed,
* supplying the same sd, mean and seed as a previous VariableDistribution
* will give an idential distribution.
*
* @param mean2
* @param sd
* @param seed
* The seed to be used for the random number generator.
*/
public VariableDistribution(final double mean2, final float sd, long seed,
int trials, boolean meanType) {
this(mean2, sd, trials);
random.setSeed(seed);
this.meanType = meanType;
}
/**
* Advance to the next shuffle of onsets.
*/
public void advance() {
onsets = onsetsIt.next();
}
/**
* @param onsets2
* a list of integers.
* @return the arithmetic mean of the list of numbers given.
*/
private double arithmeticMean(List<Double> onsets2) {
double actualMean = 0;
for (double onset : onsets2) {
actualMean += onset;
}
actualMean /= onsets2.size();
return actualMean;
}
/**
* Build the standardized list of onsets.
*/
public void build() {
index = 0;
if (isChanged) {
onsets.clear();
shuffledOnsets.clear();
onsetsIt = shuffledOnsets.listIterator();
random = new Random(randomSeed());
for (int i = 0; i < trials; i++) {
onsets.add(nextRandom());
}
onsets = standardize();
isChanged = false;
}
}
/**
*
* @param onsets2
* a list of integers.
* @return the geometric mean of the list of numbers
*/
private double geometricMean(List<Double> onsets2) {
double actualMean = 1;
for (double onset : onsets2) {
actualMean *= onset;
}
actualMean = Math.pow(actualMean, 1d / onsets2.size());
return actualMean;
}
/**
*
* @return the mean for the distribution.
*/
public double getMean() {
return mean;
}
/**
* Get the onset for the specified trial number.
*
* @param trial
* the trial number to get the onset for.
* @return an integer indicating the timestep that onset occurs at.
*/
public double getOnset(final int trial) {
return onsets.get(trial);
}
/**
*
* @return the standard deviation for the distribution.
*/
public float getSd() {
return sd;
}
public long getSeed() {
return seed;
}
/**
* @return the shuffle of onsets.
*/
public List<List<Double>> getShuffle() {
return shuffledOnsets;
}
/**
* @return false if this distribution is using the arithmetic mean, true if
* geometric.
*/
public boolean isArithmetic() {
return meanType;
}
public double next() {
double next = onsets.get(index);
index++;
return next;
}
/**
* Get the next onset in this variable distribution. Onsets are selected
* from an exponential distribution with the given mean. Variable
* distributions configured with the same mean will give the same sequence
* of onsets.
*
* @return a double indicating the next duration.
*/
protected double nextRandom() {
double next = -1 * mean * Math.log(random.nextDouble());
if (next == 0) return 0;
return Math.max(next, Simulator.getController().getModel()
.getTimestepSize());
}
/**
* Reshuffle the onsets list.
*/
public void regenerate() {
if(Simulator.getController().getView().isSetCompound()) {
Collections.shuffle(onsets, random);
} else {
Collections.shuffle(onsets, random);
}
onsetsIt.add(new ArrayList<Double>(onsets));
onsetsIt.previous();
}
/**
* Go back to the start of the shuffle of onsets.
*/
public void restartOnsets() {
onsetsIt = shuffledOnsets.listIterator();
}
public void setIndex(int num) {
index = num;
}
/**
*
* @param meanVar
* the new mean for the distribution.
*/
public void setMean(double meanVar) {
this.mean = meanVar;
}
/**
* @param meanType
* set to false to use arithmetic, true for geometric.
*/
public void setMeanType(boolean meanType) {
this.meanType = meanType;
isChanged = true;
}
/**
*
* @param sd
* new standard deviation.
*/
public void setSd(float sd) {
this.sd = sd;
}
/**
* @param shuffle
* the shuffle of onsets to use.
*/
public void setShuffle(List<List<Double>> shuffle) {
shuffledOnsets.addAll(shuffle);
restartOnsets();
}
public void setTrials(int numTrials) {
trials = numTrials;
isChanged = true;
}
/**
* Transform a list of random numbers into one standardized about an exact
* mean.
*
* @return a standardized list of numbers.
*/
private List<Double> standardize() {
List<Double> standardized = new ArrayList<Double>();
double actualMean = meanType ? geometricMean(onsets)
: arithmeticMean(onsets);
for (double onset : onsets) {
double shifted = onset - actualMean;
shifted += mean;
if (shifted != 0) {
shifted = Math.max(shifted, Simulator.getController().getModel()
.getTimestepSize()); // Make lower bound 1 timestep
}
standardized.add(shifted);
}
return standardized;
}
}
|
cal-r/sscctd
|
src/simulator/util/VariableDistribution.java
|
Java
|
mpl-2.0
| 7,556
|
{% extends 'base.html' %}
{% block content %}
<div class="page-header">
<h1>{% if object.pk %}Edit{% else %}Create{% endif %} graphite check</h1>
</div>
{% include 'include/submit_delete_form.html' with delete_view='graphite_delete_check' %}
{% endblock %}
|
Stupeflix/japper
|
japper/monitoring_backends/graphite/templates/graphite/check_form.html
|
HTML
|
mpl-2.0
| 262
|
<!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_131) on Sat May 06 22:14:41 CDT 2017 -->
<title>Uses of Class com.hyleria.common.account.Account</title>
<meta name="date" content="2017-05-06">
<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 com.hyleria.common.account.Account";
}
}
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="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/hyleria/common/account/class-use/Account.html" target="_top">Frames</a></li>
<li><a href="Account.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 com.hyleria.common.account.Account" class="title">Uses of Class<br>com.hyleria.common.account.Account</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.hyleria.command.api.data">com.hyleria.command.api.data</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.hyleria.common.account">com.hyleria.common.account</a></td>
<td class="colLast">
<div class="block">Data holders pertaining to the
backend account of players.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.hyleria.common.mongo">com.hyleria.common.mongo</a></td>
<td class="colLast">
<div class="block">Backbone tools pertaining to our usage of MongoDB.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.hyleria.network">com.hyleria.network</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.hyleria.command.api.data">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> in <a href="../../../../../com/hyleria/command/api/data/package-summary.html">com.hyleria.command.api.data</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/command/api/data/package-summary.html">com.hyleria.command.api.data</a> that return <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">OnlineOfflinePlayer.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/command/api/data/OnlineOfflinePlayer.html#offline--">offline</a></span>()</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/hyleria/command/api/data/package-summary.html">com.hyleria.command.api.data</a> with parameters of type <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/hyleria/command/api/data/OnlineOfflinePlayer.html#OnlineOfflinePlayer-org.bukkit.entity.Player-com.hyleria.common.account.Account-">OnlineOfflinePlayer</a></span>(org.bukkit.entity.Player onlinePlayer,
<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> account)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hyleria.common.account">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> in <a href="../../../../../com/hyleria/common/account/package-summary.html">com.hyleria.common.account</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/common/account/package-summary.html">com.hyleria.common.account</a> that return <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Account.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/account/Account.html#addVal-java.lang.String-java.lang.Object-">addVal</a></span>(java.lang.String key,
java.lang.Object val)</code>
<div class="block">Add a custom value into our account document</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Account.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/account/Account.html#fromLoginData-java.util.UUID-java.lang.String-java.lang.String-">fromLoginData</a></span>(java.util.UUID uuid,
java.lang.String name,
java.lang.String ip)</code>
<div class="block">Turns the provided data, retrieved
from a client when they login, into
a basic player <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account"><code>Account</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Account.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/account/Account.html#populateFromDocument-org.bson.Document-">populateFromDocument</a></span>(org.bson.Document document)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Account.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/account/Account.html#role-com.hyleria.common.reference.Role-com.hyleria.common.mongo.Database-">role</a></span>(<a href="../../../../../com/hyleria/common/reference/Role.html" title="enum in com.hyleria.common.reference">Role</a> newRole,
<a href="../../../../../com/hyleria/common/mongo/Database.html" title="class in com.hyleria.common.mongo">Database</a> database)</code>
<div class="block">Update this player's role in the database</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hyleria.common.mongo">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> in <a href="../../../../../com/hyleria/common/mongo/package-summary.html">com.hyleria.common.mongo</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/common/mongo/package-summary.html">com.hyleria.common.mongo</a> that return <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#cacheCommit-com.hyleria.common.account.Account-">cacheCommit</a></span>(<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> account)</code>
<div class="block">Inserts an account into our cache</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/common/mongo/package-summary.html">com.hyleria.common.mongo</a> that return types with arguments of type <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>com.google.common.cache.Cache<java.util.UUID,<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#cache--">cache</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#cacheFetch-java.lang.String-">cacheFetch</a></span>(java.lang.String username)</code>
<div class="block">Grabs an account from our cache wrapped
in an <code>Optional</code>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#cacheFetch-java.util.UUID-">cacheFetch</a></span>(java.util.UUID uuid)</code>
<div class="block">Grabs an account from out cache based
on a player's UUID.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.concurrent.Future<java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#fetchAccount-java.lang.String-">fetchAccount</a></span>(java.lang.String username)</code>
<div class="block">Grab an account from our account via
a username.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.concurrent.Future<java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#fetchAccount-java.util.UUID-java.util.function.Consumer-">fetchAccount</a></span>(java.util.UUID uuid,
java.util.function.Consumer<java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>>> callback)</code>
<div class="block">Grab an account from our account via
the UUID provided.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#fetchAccountSync-java.util.UUID-">fetchAccountSync</a></span>(java.util.UUID uuid)</code>
<div class="block">Grab an account from our account
synchronously.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/common/mongo/package-summary.html">com.hyleria.common.mongo</a> with parameters of type <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#cacheCommit-com.hyleria.common.account.Account-">cacheCommit</a></span>(<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> account)</code>
<div class="block">Inserts an account into our cache</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../com/hyleria/common/mongo/package-summary.html">com.hyleria.common.mongo</a> with type arguments of type <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>java.util.concurrent.Future<java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>>></code></td>
<td class="colLast"><span class="typeNameLabel">Database.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/common/mongo/Database.html#fetchAccount-java.util.UUID-java.util.function.Consumer-">fetchAccount</a></span>(java.util.UUID uuid,
java.util.function.Consumer<java.util.Optional<<a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a>>> callback)</code>
<div class="block">Grab an account from our account via
the UUID provided.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hyleria.network">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a> in <a href="../../../../../com/hyleria/network/package-summary.html">com.hyleria.network</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/hyleria/network/package-summary.html">com.hyleria.network</a> that return <a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">AccountManager.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/network/AccountManager.html#grab-org.bukkit.entity.Player-">grab</a></span>(org.bukkit.entity.Player player)</code>
<div class="block">Attempts to grab an account by
a Bukkit <code>Player</code>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">AccountManager.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/network/AccountManager.html#grab-java.lang.String-">grab</a></span>(java.lang.String name)</code>
<div class="block">Attempts to find the account of
a player via a username</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Account</a></code></td>
<td class="colLast"><span class="typeNameLabel">AccountManager.</span><code><span class="memberNameLink"><a href="../../../../../com/hyleria/network/AccountManager.html#grab-java.util.UUID-">grab</a></span>(java.util.UUID uuid)</code>
<div class="block">Attempts to grab the account
for the provided player.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</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="../../../../../com/hyleria/common/account/Account.html" title="class in com.hyleria.common.account">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/hyleria/common/account/class-use/Account.html" target="_top">Frames</a></li>
<li><a href="Account.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>
|
OutdatedVersion/hyleria
|
docs/com/hyleria/common/account/class-use/Account.html
|
HTML
|
mpl-2.0
| 22,435
|
<?php
/*
* Copyright 2006 - 2018 TubePress LLC (http://tubepress.com)
*
* This file is part of TubePress (http://tubepress.com)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Adds some core variables to the search input template.
*/
class tubepress_search_impl_listeners_SearchInputTemplateListener
{
/**
* @var tubepress_api_url_UrlFactoryInterface
*/
private $_urlFactory;
/**
* @var tubepress_api_options_ContextInterface
*/
private $_context;
/**
* @var tubepress_api_http_RequestParametersInterface
*/
private $_requestParams;
public function __construct(tubepress_api_options_ContextInterface $context,
tubepress_api_url_UrlFactoryInterface $urlFactory,
tubepress_api_http_RequestParametersInterface $requestParams)
{
$this->_context = $context;
$this->_urlFactory = $urlFactory;
$this->_requestParams = $requestParams;
}
public function onSearchInputTemplatePreRender(tubepress_api_event_EventInterface $event)
{
/*
* @var array
*/
$existingTemplateVars = $event->getSubject();
$resultsUrl = $this->_context->get(tubepress_api_options_Names::SEARCH_RESULTS_URL);
$url = '';
try {
$url = $this->_urlFactory->fromString($resultsUrl);
} catch (Exception $e) {
//this is not a real problem, as the user might simply not supply a custom URL
}
/* if the user didn't request a certain page, just send the search results right back here */
if ($url == '') {
$url = $this->_urlFactory->fromCurrent();
}
/* clean up the search terms a bit */
$searchTerms = $this->_requestParams->getParamValue('tubepress_search');
$searchTerms = urldecode($searchTerms);
/*
* read http://stackoverflow.com/questions/1116019/submitting-a-get-form-with-query-string-params-and-hidden-params-disappear
* if you're curious as to what's going on here
*/
$params = $url->getQuery();
$params->remove('tubepress_page');
$params->remove('tubepress_search');
/* apply the template variables */
$newVars = array(
tubepress_api_template_VariableNames::SEARCH_HANDLER_URL => $url->toString(),
tubepress_api_template_VariableNames::SEARCH_HIDDEN_INPUTS => $params->toArray(),
tubepress_api_template_VariableNames::SEARCH_TERMS => $searchTerms,
);
$existingTemplateVars = array_merge($existingTemplateVars, $newVars);
$event->setSubject($existingTemplateVars);
}
}
|
tubepress/tubepress
|
src/add-ons/search/classes/tubepress/search/impl/listeners/SearchInputTemplateListener.php
|
PHP
|
mpl-2.0
| 2,941
|
using System.Collections.Generic;
using L2dotNET.GameService.Model.Items;
namespace L2dotNET.GameService.Managers
{
class RqItemManager
{
private static readonly RqItemManager M = new RqItemManager();
public static RqItemManager GetInstance()
{
return M;
}
public SortedList<int, L2Item> Items = new SortedList<int, L2Item>();
public void PostItem(L2Item item)
{
if (Items.ContainsKey(item.ObjId))
{
lock (Items)
Items.Remove(item.ObjId);
}
Items.Add(item.ObjId, item);
}
public L2Item GetItem(int objectId)
{
return Items.ContainsKey(objectId) ? Items[objectId] : null;
}
}
}
|
MartLegion/L2dotNET
|
src/L2dotNET.GameService/managers/RqItemManager.cs
|
C#
|
mpl-2.0
| 793
|
import mock
from crashstats.base.tests.testbase import TestCase
from crashstats.api.cleaner import Cleaner, SmartWhitelistMatcher
from crashstats import scrubber
class TestCleaner(TestCase):
def test_simplest_case(self):
whitelist = {'hits': ('foo', 'bar')}
data = {
'hits': [
{'foo': 1,
'bar': 2,
'baz': 3},
{'foo': 4,
'bar': 5,
'baz': 6},
]
}
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = {
'hits': [
{'foo': 1,
'bar': 2},
{'foo': 4,
'bar': 5},
]
}
assert data == expect
@mock.patch('warnings.warn')
def test_simplest_case_with_warning(self, p_warn):
whitelist = {'hits': ('foo', 'bar')}
data = {
'hits': [
{'foo': 1,
'bar': 2,
'baz': 3},
{'foo': 4,
'bar': 5,
'baz': 6},
]
}
cleaner = Cleaner(whitelist, debug=True)
cleaner.start(data)
p_warn.assert_called_with("Skipping 'baz'")
def test_all_dict_data(self):
whitelist = {Cleaner.ANY: ('foo', 'bar')}
data = {
'WaterWolf': {
'foo': 1,
'bar': 2,
'baz': 3,
},
'NightTrain': {
'foo': 7,
'bar': 8,
'baz': 9,
},
}
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = {
'WaterWolf': {
'foo': 1,
'bar': 2,
},
'NightTrain': {
'foo': 7,
'bar': 8,
},
}
assert data == expect
def test_simple_list(self):
whitelist = ('foo', 'bar')
data = [
{
'foo': 1,
'bar': 2,
'baz': 3,
},
{
'foo': 7,
'bar': 8,
'baz': 9,
},
]
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = [
{
'foo': 1,
'bar': 2,
},
{
'foo': 7,
'bar': 8,
},
]
assert data == expect
def test_plain_dict(self):
whitelist = ('foo', 'bar')
data = {
'foo': 1,
'bar': 2,
'baz': 3,
}
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = {
'foo': 1,
'bar': 2,
}
assert data == expect
def test_dict_data_with_lists(self):
whitelist = {
'hits': {
Cleaner.ANY: ('foo', 'bar')
}
}
data = {
'hits': {
'WaterWolf': [
{'foo': 1, 'bar': 2, 'baz': 3},
{'foo': 4, 'bar': 5, 'baz': 6}
],
'NightTrain': [
{'foo': 7, 'bar': 8, 'baz': 9},
{'foo': 10, 'bar': 11, 'baz': 12}
]
}
}
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = {
'hits': {
'WaterWolf': [
{'foo': 1, 'bar': 2},
{'foo': 4, 'bar': 5}
],
'NightTrain': [
{'foo': 7, 'bar': 8},
{'foo': 10, 'bar': 11}
]
}
}
assert data == expect
def test_all_dict_data_deeper(self):
whitelist = {Cleaner.ANY: {Cleaner.ANY: ('foo', 'bar')}}
data = {
'WaterWolf': {
'2012': {
'foo': 1,
'bar': 2,
'baz': 3,
},
'2013': {
'foo': 4,
'bar': 5,
'baz': 6,
}
},
'NightTrain': {
'2012': {
'foo': 7,
'bar': 8,
'baz': 9,
},
'2013': {
'foo': 10,
'bar': 11,
'baz': 12,
}
},
}
cleaner = Cleaner(whitelist)
cleaner.start(data)
expect = {
'WaterWolf': {
'2012': {
'foo': 1,
'bar': 2,
},
'2013': {
'foo': 4,
'bar': 5,
}
},
'NightTrain': {
'2012': {
'foo': 7,
'bar': 8,
},
'2013': {
'foo': 10,
'bar': 11,
}
},
}
assert data == expect
def test_with_scrubber_cleaning(self):
whitelist = {'hits': ('foo', 'bar', 'baz')}
data = {
'hits': [
{'foo': "Bla bla",
'bar': "contact me on big@penis.com",
'baz': "when I visited http://www.p0rn.com"},
{'foo': "Ble ble unconfiged@email.com",
'bar': "other things on https://google.com here",
'baz': "talk to bill@gates.com"},
]
}
cleaner = Cleaner(
whitelist,
clean_scrub=(
('bar', scrubber.EMAIL),
('bar', scrubber.URL),
('baz', scrubber.URL),
)
)
cleaner.start(data)
expect = {
'hits': [
{'foo': "Bla bla",
'bar': "contact me on ",
'baz': "when I visited "},
{'foo': "Ble ble unconfiged@email.com",
'bar': "other things on here",
# because 'baz' doesn't have an EMAIL scrubber
'baz': "talk to bill@gates.com"},
]
}
assert data == expect
class TestSmartWhitelistMatcher(TestCase):
def test_basic_in(self):
whitelist = ['some', 'thing*']
matcher = SmartWhitelistMatcher(whitelist)
assert 'some' in matcher
assert 'something' not in matcher
assert 'awesome' not in matcher
assert 'thing' in matcher
assert 'things' in matcher
assert 'nothing' not in matcher
|
Tayamarn/socorro
|
webapp-django/crashstats/api/tests/test_cleaner.py
|
Python
|
mpl-2.0
| 6,751
|
#  Contributing to Vertical Tabs Reloaded
## Platform Support
* Firefox only
* only respective latest version
* latest version of [Firefox ESR](https://www.mozilla.org/en-US/firefox/organizations/faq/) is _somewhat_ supported
* this means, compatibility is not getting broken on purpose, but it might be necessary sometimes
* pull requests concerning the latest ESR version are welcome, but if keeping compatibility means introducing major nasty hacks, the chance of merging is low
If you want to extend the platform support please start first a discussion by creating an issue (and as always search first for an existing one).
## Issues
* search first for an existing issue addressing your concern
* provide as much relevant information as you can
## Pull Requests
* you agree to license your code and additional contributions under the terms of the [MPL v2.0](LICENSE.md)
* if you want to make sure to have explicit credits within the project itself, then please add yourself to the [credits.md](credits.md) file within your pull request
* pull requests are requests. There is no guarantee that they will be accepted. Therefore, it might be wise to first start a discussion via opening an issue before starting to implement your idea
|
Croydon/vertical-tabs-reloaded
|
CONTRIBUTING.md
|
Markdown
|
mpl-2.0
| 1,341
|
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* The list of phases mapped to their corresponding profiles. The object
* here must be in strict JSON format, as it will get parsed by the Python
* testrunner (no single quotes, extra comma's, etc).
*/
EnableEngines(["history"]);
var phases = { "phase1": "profile1",
"phase2": "profile2" };
/*
* History asset lists: these define history entries that are used during
* the test
*/
// the initial list of history items to add to the browser
var history1 = [
{ uri: "http://www.google.com/",
title: "Google",
visits: [
{ type: 1,
date: 0
},
{ type: 2,
date: -1
}
]
},
{ uri: "http://www.cnn.com/",
title: "CNN",
visits: [
{ type: 1,
date: -1
},
{ type: 2,
date: -36
}
]
},
{ uri: "http://www.google.com/language_tools?hl=en",
title: "Language Tools",
visits: [
{ type: 1,
date: 0
},
{ type: 2,
date: -40
}
]
},
{ uri: "http://www.mozilla.com/",
title: "Mozilla",
visits: [
{ type: 1,
date: 0
},
{ type: 1,
date: -1
},
{ type: 1,
date: -20
},
{ type: 2,
date: -36
}
]
}
];
// a list of items to delete from the history
var history_to_delete = [
{ uri: "http://www.cnn.com/" },
{ begin: -24,
end: -1
},
{ host: "www.google.com" }
];
// a list which reflects items that should be in the history after
// the above items are deleted
var history2 = [
{ uri: "http://www.mozilla.com/",
title: "Mozilla",
visits: [
{ type: 1,
date: 0
},
{ type: 2,
date: -36
}
]
}
];
// a list which includes history entries that should not be present
// after deletion of the history_to_delete entries
var history_not = [
{ uri: "http://www.google.com/",
title: "Google",
visits: [
{ type: 1,
date: 0
},
{ type: 2,
date: -1
}
]
},
{ uri: "http://www.cnn.com/",
title: "CNN",
visits: [
{ type: 1,
date: -1
},
{ type: 2,
date: -36
}
]
},
{ uri: "http://www.google.com/language_tools?hl=en",
title: "Language Tools",
visits: [
{ type: 1,
date: 0
},
{ type: 2,
date: -40
}
]
},
{ uri: "http://www.mozilla.com/",
title: "Mozilla",
visits: [
{ type: 1,
date: -1
},
{ type: 1,
date: -20
}
]
}
];
/*
* Test phases
* Note: there is no test phase in which deleted history entries are
* synced to other clients. This functionality is not supported by
* Sync, see bug 446517.
*/
Phase("phase1", [
[History.add, history1],
[Sync],
]);
Phase("phase2", [
[Sync],
[History.verify, history1],
[History.delete, history_to_delete],
[History.verify, history2],
[History.verifyNot, history_not],
[Sync]
]);
|
Yukarumya/Yukarum-Redfoxes
|
services/sync/tests/tps/test_history.js
|
JavaScript
|
mpl-2.0
| 3,085
|
# Caring for ActiveData
Updated June 2019
### Overview of Parts
Here are a couple of diagrams that will help with descriptions below
* [Logical View](https://github.com/mozilla/ActiveData/blob/dev/docs/ActiveData%20Architecture%20Logical%20181117.pdf)
* [Machine View](https://github.com/mozilla/ActiveData/blob/dev/docs/ActiveData%20Architecture%20181020.png)
### Reference Doc
Once you are familiar with this doc, then you will only need the reference doc:
* [List of Moving Parts](https://docs.google.com/spreadsheets/d/1ReUDh94YBP8VgdRJe9KW0PJqJHkICQFvaSuyZQd0uJY/edit#gid=0)
## Setup
### Code
Tending to ActiveData will require
* **ActiveData code** - `git clone https://github.com/mozilla/ActiveData.git`
* **ActiveData-ETL code** - `git clone https://github.com/klahnakoski/ActiveData-ETL.git`
* **Elasticsearch Head** - `git clone https://github.com/mobz/elasticsearch-head.git`
* **esShardBalancer** - `git clone https://github.com/klahnakoski/esShardBalancer.git`
### Config
All the secrets are assumed to be in `~/private.json` on your development machine. All config files point to this file.
{
"fabric":{
"key_filename": "path/to/private/key.pem",
},
"aws_credentials":{
"aws_access_key_id":"id",
"aws_secret_access_key" :"secret",
"region":"us-west-2"
}
}
### Connections
All machines are listed in the moving parts, but these two are the most useful
* Frontend
* Manager
Use the AWS dashboard to ensure your IP is allowed to connect to each machine.
#### Test Connection
**Linux**
Be sure to add the ssh private key: `ssh-add ~/.ssh/<key>.pem`, and test your connection:
ssh ec2-user@activedata.allizom.org
**Windows**
Setup a Putty configuration (called "`active-data-frontend`"). Ensure you can connect.
#### Test Tunneling
You must be able to tunnel from localhost:9201 to the frontend on port 9200 so you can access the ES cluster:
**Linux**
ssh -v -N -L 9201:localhost:9200 ec2-user@activedata.allizom.org
**Windows**
If you are using Windows, with Putty, then you can tunnelling to ES using SSH on windows
plink -v -N -L 9201:localhost:9200 "active-data-frontend"
### AWS
There are three resource categories that may interest you in AWS:
* **EC2** - Listing all machines, and links to security groups. Security groups are used to open your local machine to ActiveData instances
* **SQS** - Used to monitor ETL backlog, and ingestion backlog
* **S3** - Used to peruse the raw data that went through the pipeline
## Daily Operations
### Machine Health
When logging into machines, always check the disk. Some logs do not roll over, and some crashes can fill the drives with crash reports
df -h
### Check ES Health
The **coordinator** node is a small node on the **FrontEnd** that serves all query requests to the outside world, and acts as a circuit breaker for the rest of the cluster. It can be bounced without affecting ES the overall cluster. No queries can be serviced when this node is down.
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* Map port 9201 to remote port 9200:<br>
Linux - `ssh -v -N -L 9201:localhost:9200 ec2-user@activedata.allizom.org`<br>
Windows - `plink -v -N -L 9201:localhost:9200 "active-data-frontend"`
* Use Elasticsearch Head (connecting to `localhost:9201`) to verify ES is available, or not
If you can connect, then review the status:
> When ES suffers from node loss, the status endpoint will stall, making it appears ES is down. Attempt an ActiveData query `{"from":"unittest"}` to see if the query endpoint is still working. If the query endpoint is still working, wait a bit.
* **green** - everything ok. IF there is a problem, then it must be elsewhere.
* **yellow** - If a large number of random shards are not allocated, then there was a recent loss of spot nodes, or an OutOfMemory event.
* **red** - look at which shards are not allocated: If it is just new indexes, then this state should disappear in a minute. If random shards are not allocated, then there has been a catastrophic failure over many machines proceed to [Emergency Proceedures](https://github.com/mozilla/ActiveData/blob/dev/docs/_Caring_for_ActiveData.md#Emergency+Procedures)
If you can not connect, then attempt to bounce the **coordinator** node.
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* Login to **FrontEnd** machine
* `sudo supervisorctl`
* `restart es`
* `tail -f es`
Watch the logs for connection problems. It will take a short while for the node to reconnect. If the node continues to complain it can not find the cluster, then proceed to [Emergency Proceedures](https://github.com/mozilla/ActiveData/blob/dev/docs/_Caring_for_ActiveData.md#Emergency+Procedures)
### Drive is full?
The problem may be caused by a full drive (`df -h`). This is most often caused by a crash dump filling the drive; remove it:
sudo rm /usr/local/elasticsearch/*.hprof
If that is not the problem, then you can hunt down the big directories with:
du -sh -- *
### Check ETL Pipeline Health
Use Elasticsearch Head, look at the coverage indexes: If the latest one is today, then everything is OK. If not, then look at the SQS queues to see the backlog. A backlog will happen if
* The ES cluster has been recovering
* The push-to-es on the ES spot nodes is not running
* The ETL is not given enough money to cover the load
* The ETL is sending large amounts of errors with specifics
### Check service throughput
If there is a problem, but ES is "fine", then cause might be `gunicorn` (the ActiveData service).
Check the nginx logs, to get a sense of the problem
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* Login to **FrontEnd** machine
* `cd /data1/logs`
* `tail -f nginx_access.log`
If the logs are busy, and returning errors, then maybe someone is making too many requests. If we know who it is, then we can ask them to stop. We could try blocking IPs, but the one time this happened, it was from a distributed botnet, with too many ips.
Maybe bouncing the service will help:
* `sudo supervisorctl`
* `restart gunicorn`
If there are still problems, then "it is complicated": Coding will be required to filter out the problem.
## Overview of Parts
### ActiveData Frontend
ActiveData has a web server on the **Frontend** machine. It has a local instance of ES (with no data) to minimize search delays, and to improve search load balancing in the ES cluster.
**Nginx**
Nginx is used in production for three reasons.
- Serve static files (located at `~/ActiveData/active_data/public`)
- Serve SSH (The Flask server can deliver its own SSH, probably slower, if required)
- Distribute calls to other services; primarily the query service
A **copy** of the Configuration is `~/ActiveData/resources/config/nginx.conf`
**Gunicorn**
Gunicorn is used to pre-fork the ActiveData service, so it can serve multiple requests at once, and quicker than Flask. Since ActiveData has no concept of session, so coordinating instances is not required.
Configuration is `~/ActiveData/resources/config/gunicorn.conf`
**ActiveData Python Program**
The ActiveData program is a stateless query translation service. It was designed to be agnostic about schema changes and migrations. Upgrading is simple.
**Production Deployment Steps**
Updating the web server is relatively easy
1. On the `frontend` machine run `git pull origin master`
2. `sudo supervisorctl restart gunicorn`
#### Config and Logs
* Configuration is `~/ActiveData/resources/config/supervisord.conf`
* Logs are `/data1/logs/active_data.log`
### ActiveData Manager
Overall, the **Manager** machine is responsible for running CRON jobs against ActiveData. The code for these jobs are found on multiple repositories, under the `manager` branch.
* The [Manager setup](https://github.com/klahnakoski/ActiveData-ETL/blob/manager/resources/scripts/setup_manager.sh) reveals the repositories being used
* [CRON jobs](https://github.com/klahnakoski/ActiveData-ETL/blob/manager/resources/cron/manager.cron) is the list of actions being performed
* Logs are found at `/data1/logs`
#### Shard Balancer
the `esShardBalancer` is responsible for distributing shards over the cluster so that the shards are evenly distributed according to the capabilities of the machines available.
> It is safe to turn off the `esShardBalancer` for hours at a time. When `esShardBalancer` is down, ES can recover lost shards, but it will be unable to balance those shards, or setup new ones. Over ?days?, query speeds will get ever-slower as spot nodes are lost; more load goes to the three backup nodes, which will be unable to keep up, and will then crash, turning the cluster red.
#### Spot Manager
The SpotManager is responsible for bidding on EC2 machines and setting them up. There are two instances running: One manages the ETL machines, and the other manages the ES cluster.
> It is not safe to change the spending on the ES cluster; spending less will cause nodes to be shutdown. It is safe to mess with spending on the ETL pipeline, and it is safe to disable the cron jobs that execute the Spot Managers; but not for too many hours.
### TC Logger
This is a simple machine running a simple program the listens to the taskcluster pulse queues and writes the messages to S3. It has not been touched in years. It is listed in the moving parts.
> This is the only critical piece of the whole system: During failure, there is less than 1/2 hour before data starts getting lost.
### ETL (Extract Transform Load)
The ETL is covered by two projects
* [ActiveData-ETL](https://github.com/klahnakoski/ActiveData-ETL) (using the `etl` branch) - is the main program
* [SpotManager](https://github.com/klahnakoski/SpotManager) (using the `manager` branch) - responsible for deploying instances of the above
#### Upgrading existing pipelines
Code pushed to the `etl` branch is deployed automatically by the SpotManager, but existing machines are not touched. Despite being spot instances, these ETL machines can run for days. To upgrade the existing running machines
* Ensure your IP is allowed inbound to the `ActiveData-ETL` group
* `export PYTHONPATH=.:vendor`
* `python activedata_etl\update_etl.py --settings=resources\settings\update_etl.json`
The program will login to 40 machines at a time; update the repo and bounce the ETL process on each.
#### Adding Pipelines
In the event we are adding new ETL pipelines, we must make sure the schema is properly established before the army of robots start filling it. Otherwise we run the risk of creating multiple table instances, all with similar names.
With new ETL comes new tables, new S3 buckets and new Amazon Queues.
1. Stop SpotManager
2. Terminate all ETL instances
3. Create S3 buckets and queues
4. Use development to run ETL and confirm use of buckets and queues, and confirm creation of new tables in production
5. Push code to `etl` branch
6. Pull SpotManager changes (on `manager` branch) to its instance
7. Start Spot manager;
8. Confirm nothing blows up; which will take several minutes as SpotManager negotiates pricing and waits to setup instances
9. Run the backfill, if desired
10. Increase SpotManager budget, if desired
### ElasticSearch
Elasticsearch is powerful magic. Only the ES developers really know the plethora of ways this magic will turn against you. There are only two paths forward: You have already performed the operation before on a multi-terabyte index, and you know the safe incantation. Or, you have not done this before, and you will screw things up. Feeling lucky? Please ensure you got the next two days free to fix your mistake: Everything is backed up to S3, so the worst case is you must rebuild the index. (Which has not been done for years, so the code is probably rotten).
#### Fixing Cluster
ES still breaks, sometimes. All problems encountered so far only require a bounce, but that bounce must be controlled. Be sure these commands are run on the **coordinator6** node (which is the ES master located on the **Frontend** machine).
1. **Ensure all nodes are reliable** - This is a lengthy process, disable the SPOT nodes, or `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude.zone" : "spot"}}' http://localhost:9200/_cluster/settings` If you do not do this step, a shutdown of a node may leave a single shard in the `spot` zone, which will be at risk of loss until it is replicated back to a safe node.
2. **Disable shard movement** - This will prevent the cluster from making copies of any shards that are on the bouncing node. `curl -X PUT -d "{\"persistent\": {\"cluster.routing.allocation.enable\": \"none\"}}" http://localhost:9200/_cluster/settings`
3. Bounce the nodes as you see fit
4. **Enable shard movement** - `curl -XPUT -d "{\"persistent\": {\"cluster.routing.allocation.enable\": \"all\"}}" http://localhost:9200/_cluster/settings`
5. **Re-enable spot nodes** - `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude.zone" : ""}}' http://localhost:9200/_cluster/settings`
#### Changing Cluster Config
ES will take any opportunity to loose your data if you make any configuration changes. To prevent this you must ensure no important shards are on the node you are changing: Either it has no primaries, or all primaries are replicated to another node. You can ensure this happens by telling ES to exclude the machine you want cleared of shards. Due to enormous size of the ActiveData indexes, you will probably need to deploy more machines to handle the volume while you make a transition.
curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude._ip" : "172.31.0.39"}}' http://localhost:9200/_cluster/settings
be sure the transient settings for the same do not interfere with your plans:
curl -XPUT -d '{"transient": {"cluster.routing.allocation.exclude._ip" : ""}}' http://localhost:9200/_cluster/settings
1. **Ensure all nodes are reliable** - This is a lengthy process, disable the SPOT nodes, or `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude.zone" : "spot"}}' http://localhost:9200/_cluster/settings` If you do not do this step, a shutdown of a node may leave a single shard in the `spot` zone, which will be at risk of loss until it is replicated back to a safe node.
2. Move shards off the node you plan to change `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude._ip" : "172.31.0.39"}}' http://localhost:9200/_cluster/settings`
3. Wait while ES moves the shards of the node. *Jan2016 - took 1 day to move 2 terabytes off a node.*
4. Disable shard movement `curl -X PUT -d "{\"persistent\": {\"cluster.routing.allocation.enable\": \"none\"}}" http://localhost:9200/_cluster/settings`
5. Stop node, perform changes, start node
6. Enable shard movement `curl -XPUT -d "{\"persistent\": {\"cluster.routing.allocation.enable\": \"all\"}}" http://localhost:9200/_cluster/settings`
7. Allow allocation back to node: `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude._ip" : ""}}' http://localhost:9200/_cluster/settings`
8. Re-enable spot nodes: `curl -XPUT -d '{"persistent" : {"cluster.routing.allocation.exclude.zone" : ""}}' http://localhost:9200/_cluster/settings`
Upon which another node can be upgraded
# Emergency Procedures
The ES cluster is red! Nodes are missing! Everything is broken!
### Stop the esShardBalancer
The esShardBalancer will try it's best to bring ES to yellow state, even to the point of allowing data loss. ES will bring the cluster to yellow without loosing data, so it is best to let it do that.
* Ensure your IP is allowed inbound to the `ActiveData-Manager` group
* Login to **manager** machine
* Find PID of shardbalancer `tail -f ~/esShardBalancer6/logs/balance.log`
* Kill it `kill -9 <pid>`
### Stop the FrontEnd
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* Login to Frontend machine
* `sudo supervisorctl`
* `stop gunicorn`
### Stopping ETL
The ETL machines put a significant query load on the ES cluster. Stopping them will allow ES to heal faster, and reduce the number of errors emitted by the ETL machines.
* Ensure your IP is allowed inbound to the `ActiveData-Manager` group
* Login to **manager** machine
* `nano SpotManager-ETL/examples/config/etl_settings.json`
* set price to zero
> **Warning** - Be sure you are changing the "ETL" settings. The manager machine also has configuration for the ES cluster: dialing it down to zero will cause suffering
Here is an example, with price set to `2` (2 dollars per hour)
```javascript
{
"budget": 2, //MAXIMUM SPEND PER HOUR FOR ALL INSTANCES
"max_utility_price": 0.02, //MOST THAT WILL BE SPENT ON A SINGLE UTIL$
"max_new_utility": 30, //MOST NEW UTILITY THAT WILL BE REQUESTED IN A $
"max_requests_per_type": 10,
"max_percent_per_type": 0.70, //ALL INSTANCE TYPES MAY NOT GO OVER THI$
"price_file": "resources/aws/prices.json",
```
To resume ETL, turn the price back up.
> Changing the price, either up or down, has no destructive effect; in the short term, you can set it as you please without loosing data. If set too low, a backlog will form, which will start to expire in 14 days, and then data is lost.
### Stopping ingestion
Every ES spot instance has an ingestion process which puts significant load on the ES cluster.
* Ensure your IP is allowed inbound to the `ActiveData es5` group
* Use your local machine
* `cd Activedata-ETL`
* `git checkout push-to-es6`
* `export PYTHONPATH=.:vendor`
* `python activedata_etl\update_push_to_es.py --settings=resources\settings\update_push_to_es.json --stop`
What follows is an echo of the machine interactions as the program will connects to 10 machines at a time and tells supervisor to stop the `push-to-es` process.
> Turning ingestion on, or off, has has no destructive effect in the short term. While off, a backlog is maintained for up to 14 days.
### Solve the problem
At this point the cluster is in a state where you can mess with it to bring it back to yellow. If you are lucky, you just wait: Use ES Head to monitor positive progress.
### Establish connection to a master node
Ensure you have a connection. Try to connect to any of the master nodes (the `coordinator` on the **Frontend** machine is also a master node). Try ssh login and connect locally (`curl http://localhost:9200/`) first, and bounce the node if it is down.
### Find ES OutOfMemory events
Once you can connect to the cluster, you can use `find_es_oom.py` to review the logs; it will find any OoM events and bounce the problem nodes.
* Ensure your IP is allowed inbound to the `ActiveData es5` group
* Use your local machine
* `cd Activedata-ETL`
* `git checkout push-to-es6`
* `export PYTHONPATH=.:vendor`
* `python activedata_etl\find_es_oom.py --settings=resources\settings\find_es_oom.json`
This will take a while, as only one node is reviewed at a time. Wait for the ES cluster to return to yellow
### Still RED?
A manual review of the nodes (starting with the backup nodes) will be required: Ensuring each ES instance can startup, and diagnosing what is going wrong.
### Run esShardBalancer locally
If the cluster continues to stay in the red state, then we must accept the cluster lost data. If the `repo` or `saved_queries` indexes are missing primary shards, then the situation is really sad. This situation has not happened for years. The final resort is to run the esShardBalancer in `ACCEPT_DATA_LOSS=True` mode
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* `cd ~/esShardBalancer`
* `git checkout es6`
* `python balance.py --settings=resources/config/dev_to_staging_es6/balance.json`
### Resume esShardBalancer on manager machine
When you get a yellow cluster, you can
* Ensure your IP is allowed inbound to the `ActiveData-Manager` group
* Login to **manager** machine
```
cd ~/esShardBalancer6
export PYTHONPATH=.
python27 balance.py --settings=resources/config/staging/balance.json >& /dev/null < /dev/null &
disown -h
tail -n200 -f logs/balance.log
```
### Resume the FrontEnd
The frontend will apply little load, you can start it back up as soon as ES is yellow
* Ensure your IP is allowed inbound to the `ActiveData-Frontend` group
* Login to Frontend machine
* `sudo supervisorctl`
* `start gunicorn`
### Resume Ingestion
You should wait to resume ingestion until after the recent indexes are green.
* Ensure your IP is allowed inbound to the `ActiveData es5` group
* Use your local machine
* `cd Activedata-ETL`
* `git checkout push-to-es6`
* `export PYTHONPATH=.;vendor`
* `python activedata_etl\update_push_to_es.py --settings=resources\settings\update_push_to_es.json --start`
### Resume ETL
You should wait to resume ingestion until after the recent indexes are green.
|
klahnakoski/ActiveData
|
docs/_Caring_for_ActiveData.md
|
Markdown
|
mpl-2.0
| 21,016
|
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\User;
/**
* FiscalEntityRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class FiscalEntityRepository extends EntityRepository
{
/**
* @param User $user
*
* @return array
*/
public function getEntitiesForUser(User $user)
{
$queryBuilder = $this->createQueryBuilder('FE')
->innerJoin('FE.users', 'U')
->where('U.id = :user_id')
->setParameter('user_id', $user->getId());
return $queryBuilder->getQuery()->getResult();
}
}
|
ITGuys-RO/onrc-parser
|
src/AppBundle/Repository/FiscalEntityRepository.php
|
PHP
|
mpl-2.0
| 675
|
import tape from 'tape'
import { BN } from 'ethereumjs-util'
import Common, { Chain, Hardfork } from '@ethereumjs/common'
import VM from '../../../src'
import { ERROR } from '../../../src/exceptions'
const testCases = [
{ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul, chainId: new BN(1) },
{ chain: Chain.Mainnet, hardfork: Hardfork.Constantinople, err: ERROR.INVALID_OPCODE },
{ chain: Chain.Ropsten, hardfork: Hardfork.Istanbul, chainId: new BN(3) },
]
// CHAINID PUSH8 0x00 MSTORE8 PUSH8 0x01 PUSH8 0x00 RETURN
const code = ['46', '60', '00', '53', '60', '01', '60', '00', 'f3']
tape('Istanbul: EIP-1344', async (t) => {
t.test('CHAINID', async (st) => {
const runCodeArgs = {
code: Buffer.from(code.join(''), 'hex'),
gasLimit: new BN(0xffff),
}
for (const testCase of testCases) {
const { chain, hardfork } = testCase
const common = new Common({ chain, hardfork })
const vm = new VM({ common })
try {
const res = await vm.runCode(runCodeArgs)
if (testCase.err) {
st.equal(res.exceptionError?.error, testCase.err)
} else {
st.assert(res.exceptionError === undefined)
st.assert(testCase.chainId.eq(new BN(res.returnValue)))
}
} catch (e: any) {
st.fail(e.message)
}
}
st.end()
})
})
|
ethereumjs/ethereumjs-vm
|
packages/vm/tests/api/istanbul/eip-1344.spec.ts
|
TypeScript
|
mpl-2.0
| 1,343
|
/*
* gomacro - A Go interpreter with Lisp-like macros
*
* Copyright (C) 2017-2019 Massimiliano Ghilardi
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*
* ast_node.go
*
* Created on Feb 25, 2017
* Author Massimiliano Ghilardi
*/
package ast2
import (
"go/ast"
"go/token"
"github.com/cosmos72/gomacro/go/etoken"
)
func asInterface(x interface{}, isnil bool) interface{} {
if isnil {
return nil
}
return x
}
func asNode(x ast.Node, isnil bool) ast.Node {
if isnil {
return nil
}
return x
}
//
// .................. functions Interface() interface{}
//
func (x ArrayType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x AssignStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BadDecl) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BadExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BadStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BasicLit) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BinaryExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x BranchStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x CallExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x CaseClause) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ChanType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x CommClause) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x CompositeLit) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x DeclStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x DeferStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x Ellipsis) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x EmptyStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ExprStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x Field) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ForStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x FuncDecl) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x FuncLit) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x FuncType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x GoStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x Ident) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x IfStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ImportSpec) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x IncDecStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x IndexExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x InterfaceType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x KeyValueExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x LabeledStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x MapType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x Package) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ParenExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x RangeStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x SelectStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x SelectorExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x SendStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x SliceExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x StarExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x StructType) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x SwitchStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x TypeAssertExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x TypeSpec) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x TypeSwitchStmt) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x UnaryExpr) Interface() interface{} { return asInterface(x.X, x.X == nil) }
func (x ValueSpec) Interface() interface{} { return asInterface(x.X, x.X == nil) }
//
// .................. functions Node() ast.Node
//
func (x ArrayType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x AssignStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BadDecl) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BadExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BadStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BasicLit) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BinaryExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x BranchStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x CallExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x CaseClause) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ChanType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x CommClause) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x CompositeLit) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x DeclStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x DeferStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x Ellipsis) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x EmptyStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ExprStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x Field) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ForStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x FuncDecl) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x FuncLit) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x FuncType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x GoStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x Ident) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x IfStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ImportSpec) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x IncDecStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x IndexExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x InterfaceType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x KeyValueExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x LabeledStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x MapType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x Package) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ParenExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x RangeStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x SelectStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x SelectorExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x SendStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x SliceExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x StarExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x StructType) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x SwitchStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x TypeAssertExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x TypeSpec) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x TypeSwitchStmt) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x UnaryExpr) Node() ast.Node { return asNode(x.X, x.X == nil) }
func (x ValueSpec) Node() ast.Node { return asNode(x.X, x.X == nil) }
//
// .................. functions Op() token.Token
//
func (x ArrayType) Op() token.Token { return token.LBRACK }
func (x AssignStmt) Op() token.Token { return x.X.Tok }
func (x BadDecl) Op() token.Token { return token.ILLEGAL }
func (x BadExpr) Op() token.Token { return token.ILLEGAL }
func (x BadStmt) Op() token.Token { return token.ILLEGAL }
func (x BasicLit) Op() token.Token { return x.X.Kind }
func (x BinaryExpr) Op() token.Token { return x.X.Op }
func (x BranchStmt) Op() token.Token { return x.X.Tok }
func (x CallExpr) Op() token.Token { return etoken.E_CALL }
func (x CaseClause) Op() token.Token {
if len(x.X.List) != 0 {
return token.CASE
} else {
return token.DEFAULT
}
}
func (x ChanType) Op() token.Token { return token.CHAN }
func (x CommClause) Op() token.Token {
if x.X.Comm != nil {
return token.CASE
} else {
return token.DEFAULT
}
}
func (x CompositeLit) Op() token.Token { return token.RBRACE }
func (x DeclStmt) Op() token.Token { return etoken.E_DECLSTMT }
func (x DeferStmt) Op() token.Token { return token.DEFER }
func (x Ellipsis) Op() token.Token { return token.ELLIPSIS }
func (x EmptyStmt) Op() token.Token { return token.SEMICOLON }
func (x ExprStmt) Op() token.Token { return token.LPAREN } // same as ParenExpr
func (x Field) Op() token.Token { return etoken.E_FIELDDECL }
func (x ForStmt) Op() token.Token { return token.FOR }
func (x FuncDecl) Op() token.Token { return etoken.E_FUNCDECL }
func (x FuncLit) Op() token.Token { return etoken.LAMBDA }
func (x FuncType) Op() token.Token { return etoken.E_FUNCTYPE }
func (x GoStmt) Op() token.Token { return token.GO }
func (x Ident) Op() token.Token { return token.IDENT }
func (x IfStmt) Op() token.Token { return token.IF }
func (x ImportSpec) Op() token.Token { return token.IMPORT }
func (x IncDecStmt) Op() token.Token { return x.X.Tok }
func (x IndexExpr) Op() token.Token { return token.LBRACK }
func (x InterfaceType) Op() token.Token { return token.INTERFACE }
func (x KeyValueExpr) Op() token.Token { return etoken.E_KEYVALUE }
func (x LabeledStmt) Op() token.Token { return etoken.E_LABELEDSTMT }
func (x MapType) Op() token.Token { return token.MAP }
func (x Package) Op() token.Token { return token.PACKAGE }
func (x ParenExpr) Op() token.Token { return token.LPAREN }
func (x RangeStmt) Op() token.Token { return token.RANGE }
func (x SelectStmt) Op() token.Token { return token.SELECT }
func (x SelectorExpr) Op() token.Token { return token.PERIOD }
func (x SendStmt) Op() token.Token { return etoken.E_SENDSTMT }
func (x SliceExpr) Op() token.Token { return token.RBRACK }
func (x StarExpr) Op() token.Token { return token.MUL }
func (x StructType) Op() token.Token { return token.STRUCT }
func (x SwitchStmt) Op() token.Token { return token.SWITCH }
func (x TypeAssertExpr) Op() token.Token { return etoken.E_TYPEASSERT }
func (x TypeSpec) Op() token.Token {
if x.X.Assign == token.NoPos {
return token.TYPE
} else {
return etoken.E_ALIASTYPE
}
}
func (x TypeSwitchStmt) Op() token.Token { return etoken.E_TYPESWITCH }
func (x UnaryExpr) Op() token.Token { return x.X.Op }
func (x ValueSpec) Op() token.Token { return token.VAR } // can be VAR or CONST
//
// .................. functions New() Ast
//
func (x ArrayType) New() Ast { return ArrayType{&ast.ArrayType{Lbrack: x.X.Lbrack}} }
func (x AssignStmt) New() Ast { return AssignStmt{&ast.AssignStmt{TokPos: x.X.TokPos, Tok: x.X.Tok}} }
func (x BadDecl) New() Ast { return BadDecl{&ast.BadDecl{From: x.X.From, To: x.X.To}} }
func (x BadExpr) New() Ast { return BadExpr{&ast.BadExpr{From: x.X.From, To: x.X.To}} }
func (x BadStmt) New() Ast { return BadStmt{&ast.BadStmt{From: x.X.From, To: x.X.To}} }
func (x BasicLit) New() Ast {
return BasicLit{&ast.BasicLit{ValuePos: x.X.ValuePos, Value: x.X.Value, Kind: x.X.Kind}}
}
func (x BinaryExpr) New() Ast { return BinaryExpr{&ast.BinaryExpr{OpPos: x.X.OpPos, Op: x.X.Op}} }
func (x BranchStmt) New() Ast { return BranchStmt{&ast.BranchStmt{TokPos: x.X.TokPos, Tok: x.X.Tok}} }
func (x CallExpr) New() Ast {
return CallExpr{&ast.CallExpr{Lparen: x.X.Lparen, Ellipsis: x.X.Ellipsis, Rparen: x.X.Rparen}}
}
func (x CaseClause) New() Ast { return CaseClause{&ast.CaseClause{Case: x.X.Case, Colon: x.X.Colon}} }
func (x ChanType) New() Ast {
return ChanType{&ast.ChanType{Begin: x.X.Begin, Arrow: x.X.Arrow, Dir: x.X.Dir}}
}
func (x CommClause) New() Ast { return CommClause{&ast.CommClause{Case: x.X.Case, Colon: x.X.Colon}} }
func (x CompositeLit) New() Ast {
return CompositeLit{&ast.CompositeLit{Lbrace: x.X.Lbrace, Rbrace: x.X.Rbrace}}
}
func (x DeclStmt) New() Ast { return DeclStmt{&ast.DeclStmt{}} }
func (x DeferStmt) New() Ast { return DeferStmt{&ast.DeferStmt{Defer: x.X.Defer}} }
func (x Ellipsis) New() Ast { return Ellipsis{&ast.Ellipsis{Ellipsis: x.X.Ellipsis}} }
func (x EmptyStmt) New() Ast {
return EmptyStmt{&ast.EmptyStmt{Semicolon: x.X.Semicolon, Implicit: x.X.Implicit}}
}
func (x ExprStmt) New() Ast { return ExprStmt{&ast.ExprStmt{}} }
func (x Field) New() Ast { return Field{&ast.Field{Doc: x.X.Doc, Comment: x.X.Comment}} }
func (x ForStmt) New() Ast { return ForStmt{&ast.ForStmt{For: x.X.For}} }
func (x FuncDecl) New() Ast { return FuncDecl{&ast.FuncDecl{Doc: x.X.Doc}} }
func (x FuncLit) New() Ast { return FuncLit{&ast.FuncLit{}} }
func (x FuncType) New() Ast { return FuncType{&ast.FuncType{Func: x.X.Func}} }
func (x GoStmt) New() Ast { return GoStmt{&ast.GoStmt{Go: x.X.Go}} }
func (x Ident) New() Ast { return Ident{&ast.Ident{NamePos: x.X.NamePos, Name: x.X.Name}} }
func (x IfStmt) New() Ast { return IfStmt{&ast.IfStmt{If: x.X.If}} }
func (x ImportSpec) New() Ast {
return ImportSpec{&ast.ImportSpec{Doc: x.X.Doc, Comment: x.X.Comment, EndPos: x.X.EndPos}}
}
func (x IncDecStmt) New() Ast { return IncDecStmt{&ast.IncDecStmt{TokPos: x.X.TokPos, Tok: x.X.Tok}} }
func (x IndexExpr) New() Ast { return IndexExpr{&ast.IndexExpr{Lbrack: x.X.Lbrack, Rbrack: x.X.Rbrack}} }
func (x InterfaceType) New() Ast {
return InterfaceType{&ast.InterfaceType{Interface: x.X.Interface, Incomplete: x.X.Incomplete}}
}
func (x KeyValueExpr) New() Ast { return KeyValueExpr{&ast.KeyValueExpr{Colon: x.X.Colon}} }
func (x LabeledStmt) New() Ast { return LabeledStmt{&ast.LabeledStmt{Colon: x.X.Colon}} }
func (x MapType) New() Ast { return MapType{&ast.MapType{Map: x.X.Map}} }
func (x Package) New() Ast {
return Package{&ast.Package{Name: x.X.Name, Scope: x.X.Scope, Imports: x.X.Imports}}
}
func (x ParenExpr) New() Ast { return ParenExpr{&ast.ParenExpr{Lparen: x.X.Lparen, Rparen: x.X.Rparen}} }
func (x RangeStmt) New() Ast {
return RangeStmt{&ast.RangeStmt{For: x.X.For, TokPos: x.X.TokPos, Tok: x.X.Tok}}
}
func (x SelectStmt) New() Ast { return SelectStmt{&ast.SelectStmt{Select: x.X.Select}} }
func (x SelectorExpr) New() Ast { return SelectorExpr{&ast.SelectorExpr{}} }
func (x SendStmt) New() Ast { return SendStmt{&ast.SendStmt{Arrow: x.X.Arrow}} }
func (x SliceExpr) New() Ast { return SliceExpr{&ast.SliceExpr{Lbrack: x.X.Lbrack, Rbrack: x.X.Rbrack}} }
func (x StarExpr) New() Ast { return StarExpr{&ast.StarExpr{Star: x.X.Star}} }
func (x StructType) New() Ast { return StructType{&ast.StructType{Incomplete: x.X.Incomplete}} }
func (x SwitchStmt) New() Ast { return SwitchStmt{&ast.SwitchStmt{Switch: x.X.Switch}} }
func (x TypeAssertExpr) New() Ast {
return TypeAssertExpr{&ast.TypeAssertExpr{Lparen: x.X.Lparen, Rparen: x.X.Rparen}}
}
func (x TypeSpec) New() Ast {
return TypeSpec{&ast.TypeSpec{Doc: x.X.Doc, Assign: x.X.Assign, Comment: x.X.Comment}}
}
func (x TypeSwitchStmt) New() Ast { return TypeSwitchStmt{&ast.TypeSwitchStmt{Switch: x.X.Switch}} }
func (x UnaryExpr) New() Ast { return UnaryExpr{&ast.UnaryExpr{OpPos: x.X.OpPos, Op: x.X.Op}} }
func (x ValueSpec) New() Ast { return ValueSpec{&ast.ValueSpec{Doc: x.X.Doc, Comment: x.X.Comment}} }
//
// .................. functions Size() int
//
func (x ArrayType) Size() int { return 2 }
func (x AssignStmt) Size() int { return 2 }
func (x BadDecl) Size() int { return 0 }
func (x BadExpr) Size() int { return 0 }
func (x BadStmt) Size() int { return 0 }
func (x BasicLit) Size() int { return 0 }
func (x BinaryExpr) Size() int { return 2 }
func (x BranchStmt) Size() int { return 1 }
func (x CallExpr) Size() int { return 2 }
func (x CaseClause) Size() int { return 2 }
func (x ChanType) Size() int { return 1 }
func (x CommClause) Size() int { return 2 }
func (x CompositeLit) Size() int { return 2 }
func (x DeclStmt) Size() int { return 1 }
func (x DeferStmt) Size() int { return 1 }
func (x Ellipsis) Size() int { return 1 }
func (x EmptyStmt) Size() int { return 0 }
func (x ExprStmt) Size() int { return 1 }
func (x Field) Size() int {
// do not crash on nil *ast.Field as first receiver of generic functions
if x.X == nil {
return 0
}
return 3
}
func (x ForStmt) Size() int { return 4 }
func (x FuncDecl) Size() int { return 4 }
func (x FuncLit) Size() int { return 2 }
func (x FuncType) Size() int { return 2 }
func (x GoStmt) Size() int { return 1 }
func (x Ident) Size() int { return 0 }
func (x IfStmt) Size() int { return 4 }
func (x ImportSpec) Size() int { return 2 }
func (x IncDecStmt) Size() int { return 1 }
func (x IndexExpr) Size() int { return 2 }
func (x InterfaceType) Size() int { return 1 }
func (x KeyValueExpr) Size() int { return 2 }
func (x LabeledStmt) Size() int { return 2 }
func (x MapType) Size() int { return 2 }
func (x Package) Size() int { return 2 }
func (x ParenExpr) Size() int { return 1 }
func (x RangeStmt) Size() int { return 4 }
func (x SelectStmt) Size() int { return 1 }
func (x SelectorExpr) Size() int { return 2 }
func (x SendStmt) Size() int { return 2 }
func (x SliceExpr) Size() int { return 4 }
func (x StarExpr) Size() int { return 1 }
func (x StructType) Size() int { return 1 }
func (x SwitchStmt) Size() int { return 3 }
func (x TypeAssertExpr) Size() int { return 2 }
func (x TypeSpec) Size() int { return 2 }
func (x TypeSwitchStmt) Size() int { return 3 }
func (x UnaryExpr) Size() int { return 1 }
func (x ValueSpec) Size() int { return 3 }
//
// .................. functions Get(int) Ast
//
func (x ArrayType) Get(i int) Ast { return ToAst2(i, x.X.Len, x.X.Elt) }
func (x AssignStmt) Get(i int) Ast {
var slice []ast.Expr
switch i {
case 0:
slice = x.X.Lhs
case 1:
slice = x.X.Rhs
default:
return badIndex(i, 2)
}
if slice != nil {
return ExprSlice{slice}
}
return nil
}
func (x BadDecl) Get(i int) Ast { return badIndex(i, 0) }
func (x BadExpr) Get(i int) Ast { return badIndex(i, 0) }
func (x BadStmt) Get(i int) Ast { return badIndex(i, 0) }
func (x BasicLit) Get(i int) Ast { return badIndex(i, 0) }
func (x BinaryExpr) Get(i int) Ast { return ToAst2(i, x.X.X, x.X.Y) }
func (x BranchStmt) Get(i int) Ast { return Ident{x.X.Label} }
func (x CallExpr) Get(i int) Ast {
if i == 0 {
return ToAst(x.X.Fun)
} else if i == 1 {
if node := x.X.Args; node != nil {
return ExprSlice{node}
}
return nil
} else {
return badIndex(i, 2)
}
}
func (x CaseClause) Get(i int) Ast {
if i == 0 {
if list := x.X.List; list != nil {
return ExprSlice{list}
}
return nil
} else if i == 1 {
if list := x.X.Body; list != nil {
return StmtSlice{list}
}
return nil
} else {
return badIndex(i, 2)
}
}
func (x ChanType) Get(i int) Ast { return ToAst1(i, x.X.Value) }
func (x CommClause) Get(i int) Ast {
if i == 0 {
return ToAst(x.X.Comm)
} else if i == 1 {
if list := x.X.Body; list != nil {
return StmtSlice{list}
}
return nil
} else {
return badIndex(i, 2)
}
}
func (x CompositeLit) Get(i int) Ast {
if i == 0 {
return ToAst(x.X.Type)
} else if i == 1 {
if x.X.Elts != nil {
return ExprSlice{x.X.Elts}
}
return nil
} else {
return badIndex(i, 2)
}
}
func (x DeclStmt) Get(i int) Ast { return ToAst1(i, x.X.Decl) }
func (x DeferStmt) Get(i int) Ast { return CallExpr{x.X.Call} }
func (x Ellipsis) Get(i int) Ast { return ToAst1(i, x.X.Elt) }
func (x EmptyStmt) Get(i int) Ast { return badIndex(i, 0) }
func (x ExprStmt) Get(i int) Ast { return ToAst1(i, x.X.X) }
func (x Field) Get(i int) Ast {
if i == 0 {
if x.X.Names != nil {
return IdentSlice{x.X.Names}
}
return nil
} else if i == 1 {
return ToAst(x.X.Type)
} else if i == 2 {
return ToAst(x.X.Tag)
} else {
return badIndex(i, 3)
}
}
func (x ForStmt) Get(i int) Ast {
var node ast.Node
switch i {
case 0:
node = x.X.Init
case 1:
node = x.X.Cond
case 2:
node = x.X.Post
case 3:
node = x.X.Body
default:
return badIndex(i, 4)
}
return ToAst(node)
}
func (x FuncDecl) Get(i int) Ast { return ToAst4(i, x.X.Recv, x.X.Name, x.X.Type, x.X.Body) }
func (x FuncLit) Get(i int) Ast { return ToAst2(i, x.X.Type, x.X.Body) }
func (x FuncType) Get(i int) Ast { return ToAst2(i, x.X.Params, x.X.Results) }
func (x GoStmt) Get(i int) Ast { return CallExpr{x.X.Call} }
func (x Ident) Get(i int) Ast { return badIndex(i, 0) }
func (x IfStmt) Get(i int) Ast { return ToAst4(i, x.X.Init, x.X.Cond, x.X.Body, x.X.Else) }
func (x ImportSpec) Get(i int) Ast { return ToAst2(i, x.X.Name, x.X.Path) }
func (x IncDecStmt) Get(i int) Ast { return ToAst1(i, x.X.X) }
func (x IndexExpr) Get(i int) Ast { return ToAst2(i, x.X.X, x.X.Index) }
func (x InterfaceType) Get(i int) Ast {
if i == 0 {
if x.X.Methods != nil {
return FieldList{x.X.Methods}
}
return nil
} else {
return badIndex(i, 1)
}
}
func (x KeyValueExpr) Get(i int) Ast { return ToAst2(i, x.X.Key, x.X.Value) }
func (x LabeledStmt) Get(i int) Ast { return ToAst2(i, x.X.Label, x.X.Stmt) }
func (x MapType) Get(i int) Ast { return ToAst2(i, x.X.Key, x.X.Value) }
func (x Package) Get(i int) Ast { return nil } // TODO
func (x ParenExpr) Get(i int) Ast { return ToAst1(i, x.X.X) }
func (x RangeStmt) Get(i int) Ast { return ToAst4(i, x.X.Key, x.X.Value, x.X.X, x.X.Body) }
func (x SelectStmt) Get(i int) Ast { return ToAst1(i, x.X.Body) }
func (x SelectorExpr) Get(i int) Ast { return ToAst2(i, x.X.X, x.X.Sel) }
func (x SendStmt) Get(i int) Ast { return ToAst2(i, x.X.Chan, x.X.Value) }
func (x SliceExpr) Get(i int) Ast { return ToAst4(i, x.X.X, x.X.Low, x.X.High, x.X.Max) }
func (x StarExpr) Get(i int) Ast { return ToAst1(i, x.X.X) }
func (x StructType) Get(i int) Ast { return ToAst1(i, x.X.Fields) }
func (x SwitchStmt) Get(i int) Ast { return ToAst3(i, x.X.Init, x.X.Tag, x.X.Body) }
func (x TypeAssertExpr) Get(i int) Ast { return ToAst2(i, x.X.X, x.X.Type) }
func (x TypeSpec) Get(i int) Ast { return ToAst2(i, x.X.Name, x.X.Type) }
func (x TypeSwitchStmt) Get(i int) Ast { return ToAst3(i, x.X.Init, x.X.Assign, x.X.Body) }
func (x UnaryExpr) Get(i int) Ast { return ToAst1(i, x.X.X) }
func (x ValueSpec) Get(i int) Ast {
switch i {
case 0:
if x.X.Names != nil {
return IdentSlice{x.X.Names}
}
case 1:
if x.X.Type != nil {
return ToAst(x.X.Type)
}
case 2:
if x.X.Values != nil {
return ExprSlice{x.X.Values}
}
default:
return badIndex(i, 3)
}
return nil
}
//
// .................. functions Set(int, Ast)
//
func (x ArrayType) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.Len = expr
} else if i == 1 {
x.X.Elt = expr
} else {
badIndex(i, 2)
}
}
func (x AssignStmt) Set(i int, child Ast) {
exprs := ToExprSlice(child)
if i == 0 {
x.X.Lhs = exprs
} else if i == 1 {
x.X.Rhs = exprs
} else {
badIndex(i, 2)
}
}
func (x BadDecl) Set(i int, child Ast) { badIndex(i, 0) }
func (x BadExpr) Set(i int, child Ast) { badIndex(i, 0) }
func (x BadStmt) Set(i int, child Ast) { badIndex(i, 0) }
func (x BasicLit) Set(i int, child Ast) { badIndex(i, 0) }
func (x BinaryExpr) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.X = expr
} else if i == 1 {
x.X.Y = expr
} else {
badIndex(i, 2)
}
}
func (x BranchStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Label = ToIdent(child)
} else {
badIndex(i, 1)
}
}
func (x CallExpr) Set(i int, child Ast) {
if i == 0 {
x.X.Fun = ToExpr(child)
} else if i == 1 {
x.X.Args = ToExprSlice(child)
} else {
badIndex(i, 2)
}
}
func (x CaseClause) Set(i int, child Ast) {
if i == 0 {
x.X.List = ToExprSlice(child)
} else if i == 1 {
x.X.Body = ToStmtSlice(child)
} else {
badIndex(i, 2)
}
}
func (x ChanType) Set(i int, child Ast) {
if i == 0 {
x.X.Value = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x CommClause) Set(i int, child Ast) {
if i == 0 {
x.X.Comm = ToStmt(child)
} else if i == 1 {
x.X.Body = ToStmtSlice(child)
} else {
badIndex(i, 2)
}
}
func (x CompositeLit) Set(i int, child Ast) {
if i == 0 {
x.X.Type = ToExpr(child)
} else if i == 1 {
x.X.Elts = ToExprSlice(child)
} else {
badIndex(i, 2)
}
}
func (x DeclStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Decl = ToDecl(child)
} else {
badIndex(i, 1)
}
}
func (x DeferStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Call = ToCallExpr(child)
} else {
badIndex(i, 1)
}
}
func (x Ellipsis) Set(i int, child Ast) {
if i == 0 {
x.X.Elt = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x EmptyStmt) Set(i int, child Ast) { badIndex(i, 0) }
func (x ExprStmt) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x Field) Set(i int, child Ast) {
if i == 0 {
x.X.Names = ToIdentSlice(child)
} else if i == 1 {
x.X.Type = ToExpr(child)
} else if i == 2 {
x.X.Tag = ToBasicLit(child)
} else {
badIndex(i, 3)
}
}
func (x ForStmt) Set(i int, child Ast) {
switch i {
case 0:
x.X.Init = ToStmt(child)
case 1:
x.X.Cond = ToExpr(child)
case 2:
x.X.Post = ToStmt(child)
case 3:
x.X.Body = ToBlockStmt(child)
default:
badIndex(i, 4)
}
}
func (x FuncDecl) Set(i int, child Ast) {
switch i {
case 0:
x.X.Recv = ToFieldList(child)
case 1:
x.X.Name = ToIdent(child)
case 2:
x.X.Type = ToFuncType(child)
case 3:
x.X.Body = ToBlockStmt(child)
default:
badIndex(i, 4)
}
}
func (x FuncLit) Set(i int, child Ast) {
if i == 0 {
x.X.Type = ToFuncType(child)
} else if i == 1 {
x.X.Body = ToBlockStmt(child)
} else {
badIndex(i, 2)
}
}
func (x FuncType) Set(i int, child Ast) {
list := ToFieldList(child)
if i == 0 {
x.X.Params = list
} else if i == 1 {
x.X.Results = list
} else {
badIndex(i, 2)
}
}
func (x GoStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Call = ToCallExpr(child)
} else {
badIndex(i, 1)
}
}
func (x Ident) Set(i int, child Ast) { badIndex(i, 0) }
func (x IfStmt) Set(i int, child Ast) {
switch i {
case 0:
x.X.Init = ToStmt(child)
case 1:
x.X.Cond = ToExpr(child)
case 2:
x.X.Body = ToBlockStmt(child)
case 3:
x.X.Else = ToStmt(child)
default:
badIndex(i, 4)
}
}
func (x ImportSpec) Set(i int, child Ast) {
if i == 0 {
x.X.Name = ToIdent(child)
} else if i == 1 {
x.X.Path = ToBasicLit(child)
} else {
badIndex(i, 2)
}
}
func (x IncDecStmt) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x IndexExpr) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.X = expr
} else if i == 1 {
x.X.Index = expr
} else {
badIndex(i, 2)
}
}
func (x InterfaceType) Set(i int, child Ast) {
if i == 0 {
x.X.Methods = ToFieldList(child)
} else {
badIndex(i, 1)
}
}
func (x KeyValueExpr) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.Key = expr
} else if i == 1 {
x.X.Value = expr
} else {
badIndex(i, 2)
}
}
func (x LabeledStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Label = ToIdent(child)
} else if i == 1 {
x.X.Stmt = ToStmt(child)
} else {
badIndex(i, 2)
}
}
func (x MapType) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.Key = expr
} else if i == 1 {
x.X.Value = expr
} else {
badIndex(i, 2)
}
}
func (x Package) Set(i int, child Ast) {} // TODO
func (x ParenExpr) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x RangeStmt) Set(i int, child Ast) {
switch i {
case 0:
x.X.Key = ToExpr(child)
case 1:
x.X.Value = ToExpr(child)
case 2:
x.X.X = ToExpr(child)
case 3:
x.X.Body = ToBlockStmt(child)
default:
badIndex(i, 4)
}
}
func (x SelectStmt) Set(i int, child Ast) {
if i == 0 {
x.X.Body = ToBlockStmt(child)
} else {
badIndex(i, 1)
}
}
func (x SelectorExpr) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else if i == 1 {
x.X.Sel = ToIdent(child)
} else {
badIndex(i, 2)
}
}
func (x SendStmt) Set(i int, child Ast) {
expr := ToExpr(child)
if i == 0 {
x.X.Chan = expr
} else if i == 1 {
x.X.Value = expr
} else {
badIndex(i, 2)
}
}
func (x SliceExpr) Set(i int, child Ast) {
expr := ToExpr(child)
switch i {
case 0:
x.X.X = expr
case 1:
x.X.Low = expr
case 2:
x.X.High = expr
case 3:
x.X.Max = expr
x.X.Slice3 = expr != nil
default:
badIndex(i, 4)
}
}
func (x StarExpr) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x StructType) Set(i int, child Ast) {
if i == 0 {
x.X.Fields = ToFieldList(child)
} else {
badIndex(i, 1)
}
}
func (x SwitchStmt) Set(i int, child Ast) {
switch i {
case 0:
x.X.Init = ToStmt(child)
case 1:
x.X.Tag = ToExpr(child)
case 2:
x.X.Body = ToBlockStmt(child)
default:
badIndex(i, 3)
}
}
func (x TypeAssertExpr) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else if i == 1 {
x.X.Type = ToExpr(child)
} else {
badIndex(i, 2)
}
}
func (x TypeSpec) Set(i int, child Ast) {
if i == 0 {
x.X.Name = ToIdent(child)
} else if i == 1 {
x.X.Type = ToExpr(child)
} else {
badIndex(i, 2)
}
}
func (x TypeSwitchStmt) Set(i int, child Ast) {
switch i {
case 0:
x.X.Init = ToStmt(child)
case 1:
x.X.Assign = ToStmt(child)
case 2:
x.X.Body = ToBlockStmt(child)
default:
badIndex(i, 3)
}
}
func (x UnaryExpr) Set(i int, child Ast) {
if i == 0 {
x.X.X = ToExpr(child)
} else {
badIndex(i, 1)
}
}
func (x ValueSpec) Set(i int, child Ast) {
switch i {
case 0:
x.X.Names = ToIdentSlice(child)
case 1:
x.X.Type = ToExpr(child)
case 2:
x.X.Values = ToExprSlice(child)
default:
badIndex(i, 3)
}
}
|
cosmos72/gomacro
|
ast2/ast_node.go
|
GO
|
mpl-2.0
| 31,198
|
/*
* Copyright © 2013-2021, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.undertow;
import io.restassured.response.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seedstack.seed.Configuration;
import org.seedstack.seed.testing.junit4.SeedITRunner;
import static io.restassured.RestAssured.expect;
import static org.assertj.core.api.Assertions.assertThat;
@LaunchWithUndertow
@RunWith(SeedITRunner.class)
public class LaunchWithUndertowIT {
@Configuration("web.server.port")
protected int configuredPort;
@Configuration("runtime.web.server.port")
protected int realPort;
@Configuration("runtime.web.baseUrl")
protected String baseUrl;
@Test
public void servlet() {
assertThat(realPort).isEqualTo(configuredPort);
Response servletResponse = expect()
.statusCode(200)
.when()
.get(baseUrl + "/hello");
assertThat(servletResponse.asString()).isEqualTo("Hello World!");
}
}
|
seedstack/seed
|
web/undertow/src/test/java/org/seedstack/seed/undertow/LaunchWithUndertowIT.java
|
Java
|
mpl-2.0
| 1,247
|
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
*
* Date: 03 June 2002
* SUMMARY: Function param or local var with same name as a function property
*
* See http://bugzilla.mozilla.org/show_bug.cgi?id=137000
* See http://bugzilla.mozilla.org/show_bug.cgi?id=138708
* See http://bugzilla.mozilla.org/show_bug.cgi?id=150032
* See http://bugzilla.mozilla.org/show_bug.cgi?id=150859
*
*/
//-----------------------------------------------------------------------------
var gTestfile = 'regress-137000.js';
var UBound = 0;
var BUGNUMBER = 137000;
var summary = 'Function param or local var with same name as a function prop';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];
/*
* Note use of 'x' both for the parameter to f,
* and as a property name for |f| as an object
*/
function f(x)
{
}
status = inSection(1);
f.x = 12;
actual = f.x;
expect = 12;
addThis();
/*
* A more elaborate example, using the call() method
* to chain constructors from child to parent.
*
* The key point is the use of the same name 'p' for both
* the parameter to the constructor, and as a property name
*/
function parentObject(p)
{
this.p = 1;
}
function childObject()
{
parentObject.call(this);
}
childObject.prototype = parentObject;
status = inSection(2);
var objParent = new parentObject();
actual = objParent.p;
expect = 1;
addThis();
status = inSection(3);
var objChild = new childObject();
actual = objChild.p;
expect = 1;
addThis();
/*
* A similar set-up. Here the same name is being used for
* the parameter to both the Base and Child constructors,
*/
function Base(id)
{
}
function Child(id)
{
this.prop = id;
}
Child.prototype=Base;
status = inSection(4);
var c1 = new Child('child1');
actual = c1.prop;
expect = 'child1';
addThis();
/*
* Use same identifier as a property name, too -
*/
function BaseX(id)
{
}
function ChildX(id)
{
this.id = id;
}
ChildX.prototype=BaseX;
status = inSection(5);
c1 = new ChildX('child1');
actual = c1.id;
expect = 'child1';
addThis();
/*
* From http://bugzilla.mozilla.org/show_bug.cgi?id=150032
*
* Here the same name is being used both for a local variable
* declared in g(), and as a property name for |g| as an object
*/
function g()
{
var propA = g.propA;
var propB = g.propC;
this.getVarA = function() {return propA;}
this.getVarB = function() {return propB;}
}
g.propA = 'A';
g.propB = 'B';
g.propC = 'C';
var obj = new g();
status = inSection(6);
actual = obj.getVarA(); // this one was returning 'undefined'
expect = 'A';
addThis();
status = inSection(7);
actual = obj.getVarB(); // this one is easy; it never failed
expect = 'C';
addThis();
/*
* By martin.honnen@gmx.de
* From http://bugzilla.mozilla.org/show_bug.cgi?id=150859
*
* Here the same name is being used for a local var in F
* and as a property name for |F| as an object
*
* Twist: the property is added via another function.
*/
function setFProperty(val)
{
F.propA = val;
}
function F()
{
var propA = 'Local variable in F';
}
status = inSection(8);
setFProperty('Hello');
actual = F.propA; // this was returning 'undefined'
expect = 'Hello';
addThis();
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual;
expectedvalues[UBound] = expect;
UBound++;
}
function test()
{
enterFunc('test');
printBugNumber(BUGNUMBER);
printStatus(summary);
for (var i=0; i<UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
}
exitFunc ('test');
}
|
mozilla/rhino
|
testsrc/tests/js1_5/Object/regress-137000.js
|
JavaScript
|
mpl-2.0
| 3,991
|
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0
package oci
import (
"testing"
"github.com/terraform-providers/terraform-provider-oci/httpreplay"
"regexp"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
// issue-routing-tag: load_balancer/default
func TestAccDatasourceLoadBalancerCertificates_basic(t *testing.T) {
httpreplay.SetScenario("TestAccDatasourceLoadBalancerCertificates_basic")
defer httpreplay.SaveScenario()
providers := testAccProviders
config := legacyTestProviderConfig() + caCertificateVariableStr + privateKeyVariableStr + `
data "oci_identity_availability_domains" "ADs" {
compartment_id = "${var.compartment_id}"
}
resource "oci_core_virtual_network" "t" {
compartment_id = "${var.compartment_id}"
cidr_block = "10.0.0.0/16"
display_name = "-tf-vcn"
}
resource "oci_core_subnet" "t" {
compartment_id = "${var.compartment_id}"
vcn_id = "${oci_core_virtual_network.t.id}"
availability_domain = "${lookup(data.oci_identity_availability_domains.ADs.availability_domains[0],"name")}"
route_table_id = "${oci_core_virtual_network.t.default_route_table_id}"
security_list_ids = ["${oci_core_virtual_network.t.default_security_list_id}"]
dhcp_options_id = "${oci_core_virtual_network.t.default_dhcp_options_id}"
cidr_block = "10.0.0.0/24"
display_name = "-tf-subnet"
}
resource "oci_load_balancer" "t" {
shape = "100Mbps"
compartment_id = "${var.compartment_id}"
subnet_ids = ["${oci_core_subnet.t.id}"]
display_name = "-tf-lb"
is_private = true
}
resource "oci_load_balancer_certificate" "t" {
load_balancer_id = "${oci_load_balancer.t.id}"
ca_certificate = "${var.ca_certificate_value}"
certificate_name = "tf_cert_name"
private_key = "${var.private_key_value}"
public_certificate = "${var.ca_certificate_value}"
}
data "oci_load_balancer_certificates" "t" {
load_balancer_id = "${oci_load_balancer.t.id}"
}`
resourceName := "data.oci_load_balancer_certificates.t"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
PreventPostDestroyRefresh: true,
Providers: providers,
Steps: []resource.TestStep{
{
Config: config,
},
{
Config: config,
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttrSet(resourceName, "load_balancer_id"),
resource.TestCheckResourceAttr(resourceName, "certificates.#", "1"),
resource.TestMatchResourceAttr(resourceName, "certificates.0.ca_certificate", regexp.MustCompile("-----BEGIN CERT.*")),
resource.TestCheckResourceAttr(resourceName, "certificates.0.certificate_name", "tf_cert_name"),
resource.TestMatchResourceAttr(resourceName, "certificates.0.public_certificate", regexp.MustCompile("-----BEGIN CERT.*")),
),
},
},
})
}
|
oracle/terraform-provider-baremetal
|
oci/load_balancer_certificates_data_source_test.go
|
GO
|
mpl-2.0
| 2,896
|
package autoconf
import (
"context"
"fmt"
"net"
"github.com/hashicorp/consul/agent/cache"
cachetype "github.com/hashicorp/consul/agent/cache-types"
"github.com/hashicorp/consul/agent/connect"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/proto/pbautoconf"
)
const (
// ID of the roots watch
rootsWatchID = "roots"
// ID of the leaf watch
leafWatchID = "leaf"
unknownTrustDomain = "unknown"
)
var (
defaultDNSSANs = []string{"localhost"}
defaultIPSANs = []net.IP{{127, 0, 0, 1}, net.ParseIP("::1")}
)
func extractPEMs(roots *structs.IndexedCARoots) []string {
var pems []string
for _, root := range roots.Roots {
pems = append(pems, root.RootCert)
}
return pems
}
// updateTLSFromResponse will update the TLS certificate and roots in the shared
// TLS configurator.
func (ac *AutoConfig) updateTLSFromResponse(resp *pbautoconf.AutoConfigResponse) error {
var pems []string
for _, root := range resp.GetCARoots().GetRoots() {
pems = append(pems, root.RootCert)
}
err := ac.acConfig.TLSConfigurator.UpdateAutoTLS(
resp.ExtraCACertificates,
pems,
resp.Certificate.GetCertPEM(),
resp.Certificate.GetPrivateKeyPEM(),
resp.Config.GetTLS().GetVerifyServerHostname(),
)
if err != nil {
return fmt.Errorf("Failed to update the TLS configurator with new certificates: %w", err)
}
return nil
}
func (ac *AutoConfig) setInitialTLSCertificates(certs *structs.SignedResponse) error {
if certs == nil {
return nil
}
if err := ac.populateCertificateCache(certs); err != nil {
return fmt.Errorf("error populating cache with certificates: %w", err)
}
connectCAPems := extractPEMs(&certs.ConnectCARoots)
err := ac.acConfig.TLSConfigurator.UpdateAutoTLS(
certs.ManualCARoots,
connectCAPems,
certs.IssuedCert.CertPEM,
certs.IssuedCert.PrivateKeyPEM,
certs.VerifyServerHostname,
)
if err != nil {
return fmt.Errorf("error updating TLS configurator with certificates: %w", err)
}
return nil
}
func (ac *AutoConfig) populateCertificateCache(certs *structs.SignedResponse) error {
cert, err := connect.ParseCert(certs.IssuedCert.CertPEM)
if err != nil {
return fmt.Errorf("Failed to parse certificate: %w", err)
}
// prepolutate roots cache
rootRes := cache.FetchResult{Value: &certs.ConnectCARoots, Index: certs.ConnectCARoots.QueryMeta.Index}
rootsReq := ac.caRootsRequest()
// getting the roots doesn't require a token so in order to potentially share the cache with another
if err := ac.acConfig.Cache.Prepopulate(cachetype.ConnectCARootName, rootRes, ac.config.Datacenter, "", rootsReq.CacheInfo().Key); err != nil {
return err
}
leafReq := ac.leafCertRequest()
// prepolutate leaf cache
certRes := cache.FetchResult{
Value: &certs.IssuedCert,
Index: certs.IssuedCert.RaftIndex.ModifyIndex,
State: cachetype.ConnectCALeafSuccess(connect.EncodeSigningKeyID(cert.AuthorityKeyId)),
}
if err := ac.acConfig.Cache.Prepopulate(cachetype.ConnectCALeafName, certRes, leafReq.Datacenter, leafReq.Token, leafReq.Key()); err != nil {
return err
}
return nil
}
func (ac *AutoConfig) setupCertificateCacheWatches(ctx context.Context) (context.CancelFunc, error) {
notificationCtx, cancel := context.WithCancel(ctx)
rootsReq := ac.caRootsRequest()
err := ac.acConfig.Cache.Notify(notificationCtx, cachetype.ConnectCARootName, &rootsReq, rootsWatchID, ac.cacheUpdates)
if err != nil {
cancel()
return nil, err
}
leafReq := ac.leafCertRequest()
err = ac.acConfig.Cache.Notify(notificationCtx, cachetype.ConnectCALeafName, &leafReq, leafWatchID, ac.cacheUpdates)
if err != nil {
cancel()
return nil, err
}
return cancel, nil
}
func (ac *AutoConfig) updateCARoots(roots *structs.IndexedCARoots) error {
switch {
case ac.config.AutoConfig.Enabled:
ac.Lock()
defer ac.Unlock()
var err error
ac.autoConfigResponse.CARoots, err = translateCARootsToProtobuf(roots)
if err != nil {
return err
}
if err := ac.updateTLSFromResponse(ac.autoConfigResponse); err != nil {
return err
}
return ac.persistAutoConfig(ac.autoConfigResponse)
case ac.config.AutoEncryptTLS:
pems := extractPEMs(roots)
if err := ac.acConfig.TLSConfigurator.UpdateAutoTLSCA(pems); err != nil {
return fmt.Errorf("failed to update Connect CA certificates: %w", err)
}
return nil
default:
return nil
}
}
func (ac *AutoConfig) updateLeafCert(cert *structs.IssuedCert) error {
switch {
case ac.config.AutoConfig.Enabled:
ac.Lock()
defer ac.Unlock()
var err error
ac.autoConfigResponse.Certificate, err = translateIssuedCertToProtobuf(cert)
if err != nil {
return err
}
if err := ac.updateTLSFromResponse(ac.autoConfigResponse); err != nil {
return err
}
return ac.persistAutoConfig(ac.autoConfigResponse)
case ac.config.AutoEncryptTLS:
if err := ac.acConfig.TLSConfigurator.UpdateAutoTLSCert(cert.CertPEM, cert.PrivateKeyPEM); err != nil {
return fmt.Errorf("failed to update the agent leaf cert: %w", err)
}
return nil
default:
return nil
}
}
func (ac *AutoConfig) caRootsRequest() structs.DCSpecificRequest {
return structs.DCSpecificRequest{Datacenter: ac.config.Datacenter}
}
func (ac *AutoConfig) leafCertRequest() cachetype.ConnectCALeafRequest {
return cachetype.ConnectCALeafRequest{
Datacenter: ac.config.Datacenter,
Agent: ac.config.NodeName,
DNSSAN: ac.getDNSSANs(),
IPSAN: ac.getIPSANs(),
Token: ac.acConfig.Tokens.AgentToken(),
EnterpriseMeta: *structs.NodeEnterpriseMetaInPartition(ac.config.PartitionOrEmpty()),
}
}
// generateCSR will generate a CSR for an Agent certificate. This should
// be sent along with the AutoConfig.InitialConfiguration RPC or the
// AutoEncrypt.Sign RPC. The generated CSR does NOT have a real trust domain
// as when generating this we do not yet have the CA roots. The server will
// update the trust domain for us though.
func (ac *AutoConfig) generateCSR() (csr string, key string, err error) {
// We don't provide the correct host here, because we don't know any
// better at this point. Apart from the domain, we would need the
// ClusterID, which we don't have. This is why we go with
// unknownTrustDomain the first time. Subsequent CSRs will have the
// correct TrustDomain.
id := &connect.SpiffeIDAgent{
// will be replaced
Host: unknownTrustDomain,
Datacenter: ac.config.Datacenter,
Agent: ac.config.NodeName,
Partition: ac.config.PartitionOrDefault(),
}
caConfig, err := ac.config.ConnectCAConfiguration()
if err != nil {
return "", "", fmt.Errorf("Cannot generate CSR: %w", err)
}
conf, err := caConfig.GetCommonConfig()
if err != nil {
return "", "", fmt.Errorf("Failed to load common CA configuration: %w", err)
}
if conf.PrivateKeyType == "" {
conf.PrivateKeyType = connect.DefaultPrivateKeyType
}
if conf.PrivateKeyBits == 0 {
conf.PrivateKeyBits = connect.DefaultPrivateKeyBits
}
// Create a new private key
pk, pkPEM, err := connect.GeneratePrivateKeyWithConfig(conf.PrivateKeyType, conf.PrivateKeyBits)
if err != nil {
return "", "", fmt.Errorf("Failed to generate private key: %w", err)
}
dnsNames := ac.getDNSSANs()
ipAddresses := ac.getIPSANs()
// Create a CSR.
csr, err = connect.CreateCSR(id, pk, dnsNames, ipAddresses)
if err != nil {
return "", "", err
}
return csr, pkPEM, nil
}
func (ac *AutoConfig) getDNSSANs() []string {
sans := defaultDNSSANs
switch {
case ac.config.AutoConfig.Enabled:
sans = append(sans, ac.config.AutoConfig.DNSSANs...)
case ac.config.AutoEncryptTLS:
sans = append(sans, ac.config.AutoEncryptDNSSAN...)
}
return sans
}
func (ac *AutoConfig) getIPSANs() []net.IP {
sans := defaultIPSANs
switch {
case ac.config.AutoConfig.Enabled:
sans = append(sans, ac.config.AutoConfig.IPSANs...)
case ac.config.AutoEncryptTLS:
sans = append(sans, ac.config.AutoEncryptIPSAN...)
}
return sans
}
|
hashicorp/consul
|
agent/auto-config/tls.go
|
GO
|
mpl-2.0
| 7,900
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.