max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,045 | /******************************************************************************\
* Copyright (c) 2016, <NAME>, Genivia Inc. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* (1) Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* (2) Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* (3) The name of the author may not be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO *
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; *
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, *
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
\******************************************************************************/
/**
@file posix.cpp
@brief Get POSIX character class ranges and regex translations
@author <NAME> - <EMAIL>
@copyright (c) 2016-2020, <NAME>, Genivia Inc. All rights reserved.
@copyright (c) BSD-3 License - see LICENSE.txt
*/
#include <reflex/posix.h>
namespace reflex {
namespace Posix {
Tables::Tables()
{
static const int Alnum[] = { '0', '9', 'A', 'Z', 'a', 'z', 0, 0 };
static const int Alpha[] = { 'A', 'Z', 'a', 'z', 0, 0 };
static const int ASCII[] = { 0, 127, 0, 0 };
static const int Blank[] = { 9, 9, 32, 32, 0, 0 };
static const int Cntrl[] = { 0, 31, 127, 127, 0, 0 };
static const int Digit[] = { '0', '9', 0, 0 };
static const int Graph[] = { '!', '~', 0, 0 };
static const int Lower[] = { 'a', 'z', 0, 0 };
static const int Print[] = { ' ', '~', 0, 0 };
static const int Punct[] = { '!', '/', ':', '@', '[', '`', '{', '~', 0, 0 };
static const int Space[] = { 9, 13, 32, 32, 0, 0 };
static const int Upper[] = { 'A', 'Z', 0, 0 };
static const int Word[] = { '0', '9', 'A', 'Z', '_', '_', 'a', 'z', 0, 0 };
static const int XDigit[] = { '0', '9', 'A', 'F', 'a', 'f', 0, 0 };
range["Alnum"] = Alnum;
range["Alpha"] = Alpha;
range["ASCII"] = ASCII;
range["Blank"] = range["h"] = Blank;
range["Cntrl"] = Cntrl;
range["Digit"] = range["d"] = Digit;
range["Graph"] = Graph;
range["Lower"] = range["l"] = Lower;
range["Print"] = Print;
range["Punct"] = Punct;
range["Space"] = range["s"] = Space;
range["Upper"] = range["u"] = Upper;
range["Word"] = range["w"] = Word;
range["XDigit"] = range["x"] = XDigit;
}
static const Tables tables;
const int * range(const char *s)
{
Tables::Range::const_iterator i = tables.range.find(s);
if (i != tables.range.end())
return i->second;
return NULL;
}
}
}
| 1,794 |
790 | <gh_stars>100-1000
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Helpers iterators for input_readers.DatastoreInputReader."""
from google.appengine.datastore import datastore_query
from google.appengine.datastore import datastore_rpc
from google.appengine.ext import db
from google.appengine.ext import key_range
from google.appengine.ext.mapreduce import json_util
from google.appengine.ext.mapreduce import key_ranges
from google.appengine.ext.mapreduce import model
from google.appengine.ext.mapreduce import namespace_range
from google.appengine.ext.mapreduce import property_range
from google.appengine.ext.mapreduce import util
__all__ = [
"RangeIteratorFactory",
"RangeIterator",
"AbstractKeyRangeIterator",
"KeyRangeModelIterator",
"KeyRangeEntityIterator",
"KeyRangeKeyIterator",
"KeyRangeEntityProtoIterator"]
class RangeIteratorFactory(object):
"""Factory to create RangeIterator."""
@classmethod
def create_property_range_iterator(cls,
p_range,
ns_range,
query_spec):
"""Create a _PropertyRangeModelIterator.
Args:
p_range: a property_range.PropertyRange object that defines the
conditions entities should safisfy.
ns_range: a namesrange.NamespaceRange object that defines the namespaces
to examine.
query_spec: a model.QuerySpec object that defines how to retrieve
entities from datastore.
Returns:
a RangeIterator.
"""
return _PropertyRangeModelIterator(p_range,
ns_range,
query_spec)
@classmethod
def create_key_ranges_iterator(cls,
k_ranges,
query_spec,
key_range_iter_cls):
"""Create a _KeyRangesIterator.
Args:
k_ranges: a key_ranges._KeyRanges object.
query_spec: a model.query_spec object that defines how to retrieve
entities from datastore.
key_range_iter_cls: the class that iterates over a single key range.
The value yielded by this class is yielded.
Returns:
a RangeIterator.
"""
return _KeyRangesIterator(k_ranges, query_spec, key_range_iter_cls)
@classmethod
def from_json(cls, json):
return _RANGE_ITERATORS[json["name"]].from_json(json)
class RangeIterator(json_util.JsonMixin):
"""Interface for DatastoreInputReader helpers.
Technically, RangeIterator is a container. It contains all datastore
entities that fall under a certain range (key range or proprety range).
It implements __iter__, which returns a generator that can iterate
through entities. It also implements marshalling logics. Marshalling
saves the state of the container so that any new generator created
can resume where the old generator left off.
Caveats:
1. Calling next() on the generators may also modify the container.
2. Marshlling after StopIteration is raised has undefined behavior.
"""
def __iter__(self):
"""Iter.
Yields:
Iterates over datastore entities and yields some kind of value
for each entity.
"""
raise NotImplementedError()
def __repr__(self):
raise NotImplementedError()
def to_json(self):
"""Serializes all states into json form.
Returns:
all states in json-compatible map.
"""
raise NotImplementedError()
@classmethod
def from_json(cls, json):
"""Reverse of to_json."""
raise NotImplementedError()
class _PropertyRangeModelIterator(RangeIterator):
"""Yields db/ndb model entities within a property range."""
def __init__(self, p_range, ns_range, query_spec):
"""Init.
Args:
p_range: a property_range.PropertyRange object that defines the
conditions entities should safisfy.
ns_range: a namesrange.NamespaceRange object that defines the namespaces
to examine.
query_spec: a model.QuerySpec object that defines how to retrieve
entities from datastore.
"""
self._property_range = p_range
self._ns_range = ns_range
self._query_spec = query_spec
self._cursor = None
self._query = None
def __repr__(self):
return "PropertyRangeIterator for %s" % str(self._property_range)
def __iter__(self):
"""Iterate over entities.
Yields:
db model entities or ndb model entities if the model is defined with ndb.
"""
for ns in self._ns_range:
self._query = self._property_range.make_query(ns)
if isinstance(self._query, db.Query):
if self._cursor:
self._query.with_cursor(self._cursor)
for model_instance in self._query.run(
batch_size=self._query_spec.batch_size,
keys_only=self._query_spec.keys_only):
yield model_instance
else:
self._query = self._query.iter(batch_size=self._query_spec.batch_size,
keys_only=self._query_spec.keys_only,
start_cursor=self._cursor,
produce_cursors=True)
for model_instance in self._query:
yield model_instance
self._query = None
self._cursor = None
if ns != self._ns_range.namespace_end:
self._ns_range = self._ns_range.with_start_after(ns)
def to_json(self):
"""Inherit doc."""
cursor = self._cursor
if self._query is not None:
if isinstance(self._query, db.Query):
cursor = self._query.cursor()
else:
cursor = self._query.cursor_after()
if cursor is None or isinstance(cursor, basestring):
cursor_object = False
else:
cursor_object = True
cursor = cursor.to_websafe_string()
return {"property_range": self._property_range.to_json(),
"query_spec": self._query_spec.to_json(),
"cursor": cursor,
"ns_range": self._ns_range.to_json_object(),
"name": self.__class__.__name__,
"cursor_object": cursor_object}
@classmethod
def from_json(cls, json):
"""Inherit doc."""
obj = cls(property_range.PropertyRange.from_json(json["property_range"]),
namespace_range.NamespaceRange.from_json_object(json["ns_range"]),
model.QuerySpec.from_json(json["query_spec"]))
cursor = json["cursor"]
if cursor and json["cursor_object"]:
obj._cursor = datastore_query.Cursor.from_websafe_string(cursor)
else:
obj._cursor = cursor
return obj
class _KeyRangesIterator(RangeIterator):
"""Create an iterator over a key_ranges.KeyRanges object."""
def __init__(self,
k_ranges,
query_spec,
key_range_iter_cls):
"""Init.
Args:
k_ranges: a key_ranges._KeyRanges object.
query_spec: a model.query_spec object that defines how to retrieve
entities from datastore.
key_range_iter_cls: the class that iterates over a single key range.
The value yielded by this class is yielded.
"""
self._key_ranges = k_ranges
self._query_spec = query_spec
self._key_range_iter_cls = key_range_iter_cls
self._current_iter = None
self._current_key_range = None
def __repr__(self):
return "KeyRangesIterator for %s" % str(self._key_ranges)
def __iter__(self):
while True:
need_checkpoint = False
if self._current_iter:
need_checkpoint = True
for o in self._current_iter:
need_checkpoint = False
yield o
try:
k_range = self._key_ranges.next()
self._current_iter = self._key_range_iter_cls(k_range,
self._query_spec)
if need_checkpoint:
yield util.ALLOW_CHECKPOINT
except StopIteration:
self._current_iter = None
break
def to_json(self):
"""Inherit doc."""
current_iter = None
if self._current_iter:
current_iter = self._current_iter.to_json()
return {"key_ranges": self._key_ranges.to_json(),
"query_spec": self._query_spec.to_json(),
"current_iter": current_iter,
"key_range_iter_cls": self._key_range_iter_cls.__name__,
"name": self.__class__.__name__}
@classmethod
def from_json(cls, json):
"""Inherit doc."""
key_range_iter_cls = _KEY_RANGE_ITERATORS[json["key_range_iter_cls"]]
obj = cls(key_ranges.KeyRangesFactory.from_json(json["key_ranges"]),
model.QuerySpec.from_json(json["query_spec"]),
key_range_iter_cls)
current_iter = None
if json["current_iter"]:
current_iter = key_range_iter_cls.from_json(json["current_iter"])
obj._current_iter = current_iter
return obj
_RANGE_ITERATORS = {
_PropertyRangeModelIterator.__name__: _PropertyRangeModelIterator,
_KeyRangesIterator.__name__: _KeyRangesIterator
}
class AbstractKeyRangeIterator(json_util.JsonMixin):
"""Iterates over a single key_range.KeyRange and yields value for each key.
All subclasses do the same thing: iterate over a single KeyRange.
They do so using different APIs (db, ndb, datastore) to return entities
of different types (db model, ndb model, datastore entity, raw proto).
"""
def __init__(self, k_range, query_spec):
"""Init.
Args:
k_range: a key_range.KeyRange object that defines the entity keys to
operate on. KeyRange object already contains a namespace.
query_spec: a model.query_spec object that defines how to retrieve
entities from datastore.
"""
self._key_range = k_range
self._query_spec = query_spec
self._cursor = None
self._query = None
def __iter__(self):
"""Iter."""
raise NotImplementedError()
def _get_cursor(self):
"""Get cursor on current query iterator for serialization."""
raise NotImplementedError()
def to_json(self):
"""Serializes all states into json form.
Returns:
all states in json-compatible map.
"""
cursor = self._get_cursor()
cursor_object = False
if cursor and isinstance(cursor, datastore_query.Cursor):
cursor = cursor.to_websafe_string()
cursor_object = True
return {"key_range": self._key_range.to_json(),
"query_spec": self._query_spec.to_json(),
"cursor": cursor,
"cursor_object": cursor_object}
@classmethod
def from_json(cls, json):
"""Reverse of to_json."""
obj = cls(key_range.KeyRange.from_json(json["key_range"]),
model.QuerySpec.from_json(json["query_spec"]))
cursor = json["cursor"]
if cursor and json["cursor_object"]:
obj._cursor = datastore_query.Cursor.from_websafe_string(cursor)
else:
obj._cursor = cursor
return obj
class KeyRangeModelIterator(AbstractKeyRangeIterator):
"""Yields db/ndb model entities with a key range."""
def __iter__(self):
self._query = self._key_range.make_ascending_query(
util.for_name(self._query_spec.model_class_path),
filters=self._query_spec.filters)
if isinstance(self._query, db.Query):
if self._cursor:
self._query.with_cursor(self._cursor)
for model_instance in self._query.run(
batch_size=self._query_spec.batch_size,
keys_only=self._query_spec.keys_only):
yield model_instance
else:
self._query = self._query.iter(batch_size=self._query_spec.batch_size,
keys_only=self._query_spec.keys_only,
start_cursor=self._cursor,
produce_cursors=True)
for model_instance in self._query:
yield model_instance
def _get_cursor(self):
if self._query is None:
return self._cursor
if isinstance(self._query, db.Query):
return self._query.cursor()
else:
return self._query.cursor_after()
class KeyRangeEntityIterator(AbstractKeyRangeIterator):
"""Yields datastore.Entity type within a key range."""
_KEYS_ONLY = False
def __iter__(self):
self._query = self._key_range.make_ascending_datastore_query(
self._query_spec.entity_kind, filters=self._query_spec.filters)
for entity in self._query.Run(config=datastore_query.QueryOptions(
batch_size=self._query_spec.batch_size,
keys_only=self._query_spec.keys_only or self._KEYS_ONLY,
start_cursor=self._cursor)):
yield entity
def _get_cursor(self):
if self._query is None:
return self._cursor
return self._query.GetCursor()
class KeyRangeKeyIterator(KeyRangeEntityIterator):
"""Yields datastore.Key type within a key range."""
_KEYS_ONLY = True
class KeyRangeEntityProtoIterator(AbstractKeyRangeIterator):
"""Yields datastore.Entity's raw proto within a key range."""
def __iter__(self):
query = self._key_range.make_ascending_datastore_query(
self._query_spec.entity_kind, filters=self._query_spec.filters)
connection = datastore_rpc.Connection()
query_options = datastore_query.QueryOptions(
batch_size=self._query_spec.batch_size,
start_cursor=self._cursor,
produce_cursors=True)
self._query = datastore_query.ResultsIterator(
query.GetQuery().run(connection, query_options))
for entity_proto in self._query:
yield entity_proto
def _get_cursor(self):
if self._query is None:
return self._cursor
return self._query.cursor()
_KEY_RANGE_ITERATORS = {
KeyRangeModelIterator.__name__: KeyRangeModelIterator,
KeyRangeEntityIterator.__name__: KeyRangeEntityIterator,
KeyRangeKeyIterator.__name__: KeyRangeKeyIterator,
KeyRangeEntityProtoIterator.__name__: KeyRangeEntityProtoIterator
}
| 5,829 |
7,302 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# 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.
#
from typing import *
import json
import urllib
from edb.testbase import http as tb
class TestHttpNotebook(tb.BaseHttpExtensionTest, tb.server.QueryTestCase):
# EdgeQL/HTTP queries cannot run in a transaction
TRANSACTION_ISOLATION = False
@classmethod
def get_extension_name(cls):
return 'notebook'
def run_queries(self, queries: List[str]):
req_data = {
'queries': queries
}
req = urllib.request.Request(
self.http_addr, method='POST') # type: ignore
req.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(
req, json.dumps(req_data).encode(), context=self.tls_context
)
self.assertIsNotNone(response.headers['EdgeDB-Protocol-Version'])
resp_data = json.loads(response.read())
return resp_data
def test_http_notebook_01(self):
results = self.run_queries([
'SELECT 1',
'SELECT "AAAA"',
])
self.assertEqual(
results,
{
'kind': 'results',
'results': [
{
'kind': 'data',
'data': [
'AAAAAAAAAAAAAAAAAAABBQ==',
'AgAAAAAAAAAAAAAAAAAAAQU=',
'RAAAABIAAQAAAAgAAAAAAAAAAQ==',
'U0VMRUNU'
]
},
{
'kind': 'data',
'data': [
'AAAAAAAAAAAAAAAAAAABAQ==',
'AgAAAAAAAAAAAAAAAAAAAQE=',
'RAAAAA4AAQAAAARBQUFB',
'U0VMRUNU'
]
},
]
}
)
def test_http_notebook_02(self):
results = self.run_queries([
'SELECT 1',
'SELECT "AAAA" * 1',
'SELECT 55',
])
self.assertEqual(
results,
{
'kind': 'results',
'results': [
{
'kind': 'data',
'data': [
'AAAAAAAAAAAAAAAAAAABBQ==',
'AgAAAAAAAAAAAAAAAAAAAQU=',
'RAAAABIAAQAAAAgAAAAAAAAAAQ==',
'U0VMRUNU'
]
},
{
'kind': 'error',
'error': [
'QueryError',
"operator '*' cannot be applied to operands "
"of type 'std::str' and 'std::int64'",
{
'65523': '1',
'65524': '8',
'65521': '7',
'65522': '17',
'65525': '7',
'65526': '1',
'65527': '18',
'65528': '17',
'65529': '7',
'65530': '17',
'1': 'Consider using an explicit type '
'cast or a conversion function.'
}
]
}
]
}
)
def test_http_notebook_03(self):
results = self.run_queries([
'SELECT "a',
])
self.assertEqual(
results,
{
'kind': 'results',
'results': [
{
'kind': 'error',
'error': [
'EdgeQLSyntaxError',
'unterminated string, quoted by `"`',
{
'65521': '7',
'65522': '7',
'65523': '1',
'65524': '8',
}
]
}
]
}
)
def test_http_notebook_04(self):
req = urllib.request.Request(self.http_addr + '/status',
method='GET')
response = urllib.request.urlopen(req, context=self.tls_context)
resp_data = json.loads(response.read())
self.assertEqual(resp_data, {'kind': 'status', 'status': 'OK'})
def test_http_notebook_05(self):
results = self.run_queries([
'SELECT 1',
'SELECT [1][2]',
'SELECT 2'
])
self.assertEqual(
results,
{
'kind': 'results',
'results': [
{
'kind': 'data',
'data': [
'AAAAAAAAAAAAAAAAAAABBQ==',
'AgAAAAAAAAAAAAAAAAAAAQU=',
'RAAAABIAAQAAAAgAAAAAAAAAAQ==',
'U0VMRUNU'
]
},
{
'kind': 'error',
'error': [
'Error', 'array index 2 is out of bounds', {}
]
}
]
}
)
def test_http_notebook_06(self):
results = self.run_queries([
'SELECT {protocol := "notebook"}'
])
self.assertEqual(results['kind'], 'results')
self.assertEqual(results['results'][0]['kind'], 'data')
| 4,090 |
777 | <gh_stars>100-1000
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/extensions/extension_settings_browsertest.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/web_contents_sizer.h"
#include "chrome/common/chrome_paths.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/browser/extension_system.h"
using extensions::Extension;
using extensions::TestManagementPolicyProvider;
ExtensionSettingsUIBrowserTest::ExtensionSettingsUIBrowserTest()
: policy_provider_(TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS |
TestManagementPolicyProvider::MUST_REMAIN_ENABLED |
TestManagementPolicyProvider::MUST_REMAIN_INSTALLED) {
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
test_data_dir_ = test_data_dir_.AppendASCII("extensions");
}
ExtensionSettingsUIBrowserTest::~ExtensionSettingsUIBrowserTest() {}
void ExtensionSettingsUIBrowserTest::InstallGoodExtension() {
EXPECT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx")));
}
void ExtensionSettingsUIBrowserTest::InstallErrorsExtension() {
EXPECT_TRUE(
InstallExtension(test_data_dir_.AppendASCII("error_console")
.AppendASCII("runtime_and_manifest_errors")));
}
void ExtensionSettingsUIBrowserTest::InstallSharedModule() {
base::FilePath shared_module_path =
test_data_dir_.AppendASCII("api_test").AppendASCII("shared_module");
EXPECT_TRUE(InstallExtension(shared_module_path.AppendASCII("shared")));
EXPECT_TRUE(InstallExtension(shared_module_path.AppendASCII("import_pass")));
}
void ExtensionSettingsUIBrowserTest::InstallPackagedApp() {
EXPECT_TRUE(InstallExtension(test_data_dir_.AppendASCII("packaged_app")));
}
void ExtensionSettingsUIBrowserTest::InstallHostedApp() {
EXPECT_TRUE(InstallExtension(test_data_dir_.AppendASCII("hosted_app")));
}
void ExtensionSettingsUIBrowserTest::InstallPlatformApp() {
EXPECT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("platform_apps").AppendASCII("minimal")));
}
void ExtensionSettingsUIBrowserTest::AddManagedPolicyProvider() {
extensions::ExtensionSystem* extension_system =
extensions::ExtensionSystem::Get(browser()->profile());
extension_system->management_policy()->RegisterProvider(&policy_provider_);
}
void ExtensionSettingsUIBrowserTest::SetAutoConfirmUninstall() {
uninstall_auto_confirm_.reset(new extensions::ScopedTestDialogAutoConfirm(
extensions::ScopedTestDialogAutoConfirm::ACCEPT));
}
void ExtensionSettingsUIBrowserTest::EnableErrorConsole() {
error_console_override_.reset(new extensions::FeatureSwitch::ScopedOverride(
extensions::FeatureSwitch::error_console(), true));
}
void ExtensionSettingsUIBrowserTest::ShrinkWebContentsView() {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
CHECK(web_contents);
ResizeWebContents(web_contents, gfx::Rect(0, 0, 400, 400));
}
const Extension* ExtensionSettingsUIBrowserTest::InstallExtension(
const base::FilePath& path) {
extensions::ChromeTestExtensionLoader loader(browser()->profile());
loader.set_ignore_manifest_warnings(true);
return loader.LoadExtension(path).get();
}
| 1,244 |
12,278 | <gh_stars>1000+
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
// Allow implicit conversion from char16_t* to UnicodeString for this file:
// Helpful in toString methods and elsewhere.
#define UNISTR_FROM_STRING_EXPLICIT
#include "numparse_types.h"
#include "numparse_decimal.h"
#include "static_unicode_sets.h"
#include "numparse_utils.h"
#include "unicode/uchar.h"
#include "putilimp.h"
#include "number_decimalquantity.h"
using namespace icu;
using namespace icu::numparse;
using namespace icu::numparse::impl;
DecimalMatcher::DecimalMatcher(const DecimalFormatSymbols& symbols, const Grouper& grouper,
parse_flags_t parseFlags) {
if (0 != (parseFlags & PARSE_FLAG_MONETARY_SEPARATORS)) {
groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol);
decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
} else {
groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
bool strictSeparators = 0 != (parseFlags & PARSE_FLAG_STRICT_SEPARATORS);
unisets::Key groupingKey = strictSeparators ? unisets::STRICT_ALL_SEPARATORS
: unisets::ALL_SEPARATORS;
// Attempt to find separators in the static cache
groupingUniSet = unisets::get(groupingKey);
unisets::Key decimalKey = unisets::chooseFrom(
decimalSeparator,
strictSeparators ? unisets::STRICT_COMMA : unisets::COMMA,
strictSeparators ? unisets::STRICT_PERIOD : unisets::PERIOD);
if (decimalKey >= 0) {
decimalUniSet = unisets::get(decimalKey);
} else if (!decimalSeparator.isEmpty()) {
auto* set = new UnicodeSet();
set->add(decimalSeparator.char32At(0));
set->freeze();
decimalUniSet = set;
fLocalDecimalUniSet.adoptInstead(set);
} else {
decimalUniSet = unisets::get(unisets::EMPTY);
}
if (groupingKey >= 0 && decimalKey >= 0) {
// Everything is available in the static cache
separatorSet = groupingUniSet;
leadSet = unisets::get(
strictSeparators ? unisets::DIGITS_OR_ALL_SEPARATORS
: unisets::DIGITS_OR_STRICT_ALL_SEPARATORS);
} else {
auto* set = new UnicodeSet();
set->addAll(*groupingUniSet);
set->addAll(*decimalUniSet);
set->freeze();
separatorSet = set;
fLocalSeparatorSet.adoptInstead(set);
leadSet = nullptr;
}
UChar32 cpZero = symbols.getCodePointZero();
if (cpZero == -1 || !u_isdigit(cpZero) || u_digit(cpZero, 10) != 0) {
// Uncommon case: okay to allocate.
auto digitStrings = new UnicodeString[10];
fLocalDigitStrings.adoptInstead(digitStrings);
for (int32_t i = 0; i <= 9; i++) {
digitStrings[i] = symbols.getConstDigitSymbol(i);
}
}
requireGroupingMatch = 0 != (parseFlags & PARSE_FLAG_STRICT_GROUPING_SIZE);
groupingDisabled = 0 != (parseFlags & PARSE_FLAG_GROUPING_DISABLED);
integerOnly = 0 != (parseFlags & PARSE_FLAG_INTEGER_ONLY);
grouping1 = grouper.getPrimary();
grouping2 = grouper.getSecondary();
// Fraction grouping parsing is disabled for now but could be enabled later.
// See http://bugs.icu-project.org/trac/ticket/10794
// fractionGrouping = 0 != (parseFlags & PARSE_FLAG_FRACTION_GROUPING_ENABLED);
}
bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode& status) const {
return match(segment, result, 0, status);
}
bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, int8_t exponentSign,
UErrorCode&) const {
if (result.seenNumber() && exponentSign == 0) {
// A number has already been consumed.
return false;
} else if (exponentSign != 0) {
// scientific notation always comes after the number
U_ASSERT(!result.quantity.bogus);
}
// Initial offset before any character consumption.
int32_t initialOffset = segment.getOffset();
// Return value: whether to ask for more characters.
bool maybeMore = false;
// All digits consumed so far.
number::impl::DecimalQuantity digitsConsumed;
digitsConsumed.bogus = true;
// The total number of digits after the decimal place, used for scaling the result.
int32_t digitsAfterDecimalPlace = 0;
// The actual grouping and decimal separators used in the string.
// If non-null, we have seen that token.
UnicodeString actualGroupingString;
UnicodeString actualDecimalString;
actualGroupingString.setToBogus();
actualDecimalString.setToBogus();
// Information for two groups: the previous group and the current group.
//
// Each group has three pieces of information:
//
// Offset: the string position of the beginning of the group, including a leading separator
// if there was a leading separator. This is needed in case we need to rewind the parse to
// that position.
//
// Separator type:
// 0 => beginning of string
// 1 => lead separator is a grouping separator
// 2 => lead separator is a decimal separator
//
// Count: the number of digits in the group. If -1, the group has been validated.
int32_t currGroupOffset = 0;
int32_t currGroupSepType = 0;
int32_t currGroupCount = 0;
int32_t prevGroupOffset = -1;
int32_t prevGroupSepType = -1;
int32_t prevGroupCount = -1;
while (segment.length() > 0) {
maybeMore = false;
// Attempt to match a digit.
int8_t digit = -1;
// Try by code point digit value.
UChar32 cp = segment.getCodePoint();
if (u_isdigit(cp)) {
segment.adjustOffset(U16_LENGTH(cp));
digit = static_cast<int8_t>(u_digit(cp, 10));
}
// Try by digit string.
if (digit == -1 && !fLocalDigitStrings.isNull()) {
for (int32_t i = 0; i < 10; i++) {
const UnicodeString& str = fLocalDigitStrings[i];
if (str.isEmpty()) {
continue;
}
int32_t overlap = segment.getCommonPrefixLength(str);
if (overlap == str.length()) {
segment.adjustOffset(overlap);
digit = static_cast<int8_t>(i);
break;
}
maybeMore = maybeMore || (overlap == segment.length());
}
}
if (digit >= 0) {
// Digit was found.
if (digitsConsumed.bogus) {
digitsConsumed.bogus = false;
digitsConsumed.clear();
}
digitsConsumed.appendDigit(digit, 0, true);
currGroupCount++;
if (!actualDecimalString.isBogus()) {
digitsAfterDecimalPlace++;
}
continue;
}
// Attempt to match a literal grouping or decimal separator.
bool isDecimal = false;
bool isGrouping = false;
// 1) Attempt the decimal separator string literal.
// if (we have not seen a decimal separator yet) { ... }
if (actualDecimalString.isBogus() && !decimalSeparator.isEmpty()) {
int32_t overlap = segment.getCommonPrefixLength(decimalSeparator);
maybeMore = maybeMore || (overlap == segment.length());
if (overlap == decimalSeparator.length()) {
isDecimal = true;
actualDecimalString = decimalSeparator;
}
}
// 2) Attempt to match the actual grouping string literal.
if (!actualGroupingString.isBogus()) {
int32_t overlap = segment.getCommonPrefixLength(actualGroupingString);
maybeMore = maybeMore || (overlap == segment.length());
if (overlap == actualGroupingString.length()) {
isGrouping = true;
}
}
// 2.5) Attempt to match a new the grouping separator string literal.
// if (we have not seen a grouping or decimal separator yet) { ... }
if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus() &&
!groupingSeparator.isEmpty()) {
int32_t overlap = segment.getCommonPrefixLength(groupingSeparator);
maybeMore = maybeMore || (overlap == segment.length());
if (overlap == groupingSeparator.length()) {
isGrouping = true;
actualGroupingString = groupingSeparator;
}
}
// 3) Attempt to match a decimal separator from the equivalence set.
// if (we have not seen a decimal separator yet) { ... }
// The !isGrouping is to confirm that we haven't yet matched the current character.
if (!isGrouping && actualDecimalString.isBogus()) {
if (decimalUniSet->contains(cp)) {
isDecimal = true;
actualDecimalString = UnicodeString(cp);
}
}
// 4) Attempt to match a grouping separator from the equivalence set.
// if (we have not seen a grouping or decimal separator yet) { ... }
if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus()) {
if (groupingUniSet->contains(cp)) {
isGrouping = true;
actualGroupingString = UnicodeString(cp);
}
}
// Leave if we failed to match this as a separator.
if (!isDecimal && !isGrouping) {
break;
}
// Check for conditions when we don't want to accept the separator.
if (isDecimal && integerOnly) {
break;
} else if (currGroupSepType == 2 && isGrouping) {
// Fraction grouping
break;
}
// Validate intermediate grouping sizes.
bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false);
bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true);
if (!prevValidSecondary || (isDecimal && !currValidPrimary)) {
// Invalid grouping sizes.
if (isGrouping && currGroupCount == 0) {
// Trailing grouping separators: these are taken care of below
U_ASSERT(currGroupSepType == 1);
} else if (requireGroupingMatch) {
// Strict mode: reject the parse
digitsConsumed.clear();
digitsConsumed.bogus = true;
}
break;
} else if (requireGroupingMatch && currGroupCount == 0 && currGroupSepType == 1) {
break;
} else {
// Grouping sizes OK so far.
prevGroupOffset = currGroupOffset;
prevGroupCount = currGroupCount;
if (isDecimal) {
// Do not validate this group any more.
prevGroupSepType = -1;
} else {
prevGroupSepType = currGroupSepType;
}
}
// OK to accept the separator.
// Special case: don't update currGroup if it is empty; this allows two grouping
// separators in a row in lenient mode.
if (currGroupCount != 0) {
currGroupOffset = segment.getOffset();
}
currGroupSepType = isGrouping ? 1 : 2;
currGroupCount = 0;
if (isGrouping) {
segment.adjustOffset(actualGroupingString.length());
} else {
segment.adjustOffset(actualDecimalString.length());
}
}
// End of main loop.
// Back up if there was a trailing grouping separator.
// Shift prev -> curr so we can check it as a final group.
if (currGroupSepType != 2 && currGroupCount == 0) {
maybeMore = true;
segment.setOffset(currGroupOffset);
currGroupOffset = prevGroupOffset;
currGroupSepType = prevGroupSepType;
currGroupCount = prevGroupCount;
prevGroupOffset = -1;
prevGroupSepType = 0;
prevGroupCount = 1;
}
// Validate final grouping sizes.
bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false);
bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true);
if (!requireGroupingMatch) {
// The cases we need to handle here are lone digits.
// Examples: "1,1" "1,1," "1,1,1" "1,1,1," ",1" (all parse as 1)
// See more examples in numberformattestspecification.txt
int32_t digitsToRemove = 0;
if (!prevValidSecondary) {
segment.setOffset(prevGroupOffset);
digitsToRemove += prevGroupCount;
digitsToRemove += currGroupCount;
} else if (!currValidPrimary && (prevGroupSepType != 0 || prevGroupCount != 0)) {
maybeMore = true;
segment.setOffset(currGroupOffset);
digitsToRemove += currGroupCount;
}
if (digitsToRemove != 0) {
digitsConsumed.adjustMagnitude(-digitsToRemove);
digitsConsumed.truncate();
}
prevValidSecondary = true;
currValidPrimary = true;
}
if (currGroupSepType != 2 && (!prevValidSecondary || !currValidPrimary)) {
// Grouping failure.
digitsConsumed.bogus = true;
}
// Strings that start with a separator but have no digits,
// or strings that failed a grouping size check.
if (digitsConsumed.bogus) {
maybeMore = maybeMore || (segment.length() == 0);
segment.setOffset(initialOffset);
return maybeMore;
}
// We passed all inspections. Start post-processing.
// Adjust for fraction part.
digitsConsumed.adjustMagnitude(-digitsAfterDecimalPlace);
// Set the digits, either normal or exponent.
if (exponentSign != 0 && segment.getOffset() != initialOffset) {
bool overflow = false;
if (digitsConsumed.fitsInLong()) {
int64_t exponentLong = digitsConsumed.toLong(false);
U_ASSERT(exponentLong >= 0);
if (exponentLong <= INT32_MAX) {
auto exponentInt = static_cast<int32_t>(exponentLong);
if (result.quantity.adjustMagnitude(exponentSign * exponentInt)) {
overflow = true;
}
} else {
overflow = true;
}
} else {
overflow = true;
}
if (overflow) {
if (exponentSign == -1) {
// Set to zero
result.quantity.clear();
} else {
// Set to infinity
result.quantity.bogus = true;
result.flags |= FLAG_INFINITY;
}
}
} else {
result.quantity = digitsConsumed;
}
// Set other information into the result and return.
if (!actualDecimalString.isBogus()) {
result.flags |= FLAG_HAS_DECIMAL_SEPARATOR;
}
result.setCharsConsumed(segment);
return segment.length() == 0 || maybeMore;
}
bool DecimalMatcher::validateGroup(int32_t sepType, int32_t count, bool isPrimary) const {
if (requireGroupingMatch) {
if (sepType == -1) {
// No such group (prevGroup before first shift).
return true;
} else if (sepType == 0) {
// First group.
if (isPrimary) {
// No grouping separators is OK.
return true;
} else {
return count != 0 && count <= grouping2;
}
} else if (sepType == 1) {
// Middle group.
if (isPrimary) {
return count == grouping1;
} else {
return count == grouping2;
}
} else {
U_ASSERT(sepType == 2);
// After the decimal separator.
return true;
}
} else {
if (sepType == 1) {
// #11230: don't accept middle groups with only 1 digit.
return count != 1;
} else {
return true;
}
}
}
bool DecimalMatcher::smokeTest(const StringSegment& segment) const {
// The common case uses a static leadSet for efficiency.
if (fLocalDigitStrings.isNull() && leadSet != nullptr) {
return segment.startsWith(*leadSet);
}
if (segment.startsWith(*separatorSet) || u_isdigit(segment.getCodePoint())) {
return true;
}
if (fLocalDigitStrings.isNull()) {
return false;
}
for (int32_t i = 0; i < 10; i++) {
if (segment.startsWith(fLocalDigitStrings[i])) {
return true;
}
}
return false;
}
UnicodeString DecimalMatcher::toString() const {
return u"<Decimal>";
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| 7,549 |
593 | const uint8_t FreeSerif24pt7bBitmaps[] PROGMEM = {
0x77, 0xBF, 0xFF, 0xFF, 0xFF, 0xFB, 0x9C, 0xE7, 0x39, 0xCE, 0x61, 0x08,
0x42, 0x10, 0x84, 0x00, 0x00, 0xEF, 0xFF, 0xEE, 0x60, 0x6F, 0x0F, 0xF0,
0xFF, 0x0F, 0xF0, 0xFF, 0x0F, 0x60, 0x66, 0x06, 0x60, 0x66, 0x06, 0x60,
0x66, 0x06, 0x00, 0xE0, 0x70, 0x01, 0xC0, 0xE0, 0x03, 0x81, 0xC0, 0x07,
0x03, 0x80, 0x0E, 0x06, 0x00, 0x18, 0x0C, 0x00, 0x30, 0x38, 0x00, 0xE0,
0x70, 0x01, 0xC0, 0xE0, 0x03, 0x81, 0xC1, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF,
0xF0, 0x18, 0x0C, 0x00, 0x70, 0x38, 0x00, 0xE0, 0x70, 0x01, 0xC0, 0xE0,
0x03, 0x81, 0xC0, 0x07, 0x03, 0x80, 0x0C, 0x06, 0x07, 0xFF, 0xFF, 0xEF,
0xFF, 0xFF, 0xC0, 0xE0, 0x70, 0x01, 0xC0, 0xE0, 0x03, 0x81, 0xC0, 0x06,
0x03, 0x80, 0x0C, 0x06, 0x00, 0x38, 0x1C, 0x00, 0x70, 0x38, 0x00, 0xE0,
0x70, 0x01, 0xC0, 0xE0, 0x03, 0x81, 0xC0, 0x00, 0x00, 0x40, 0x00, 0x08,
0x00, 0x01, 0x00, 0x01, 0xFC, 0x01, 0xE4, 0xF8, 0x70, 0x87, 0x9C, 0x10,
0x77, 0x02, 0x06, 0xE0, 0x40, 0xDC, 0x08, 0x0B, 0x81, 0x00, 0x78, 0x20,
0x07, 0x84, 0x00, 0xFC, 0x80, 0x0F, 0xF0, 0x00, 0xFE, 0x00, 0x07, 0xF0,
0x00, 0x7F, 0x80, 0x03, 0xFC, 0x00, 0x3F, 0xC0, 0x05, 0xFC, 0x00, 0x8F,
0x80, 0x10, 0xF8, 0x02, 0x0F, 0x00, 0x40, 0xF0, 0x08, 0x1E, 0x01, 0x03,
0xE0, 0x20, 0x7C, 0x04, 0x0F, 0xC0, 0x83, 0xBC, 0x10, 0xE3, 0xE2, 0x78,
0x3F, 0xFE, 0x00, 0xFE, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x01, 0xF0, 0x00, 0xC0, 0x03, 0xFC, 0x01, 0xE0, 0x03, 0xC7, 0x81, 0xE0,
0x03, 0xC0, 0x7F, 0x60, 0x03, 0xC0, 0x20, 0x70, 0x01, 0xE0, 0x10, 0x30,
0x01, 0xE0, 0x08, 0x38, 0x00, 0xE0, 0x04, 0x18, 0x00, 0xF0, 0x02, 0x1C,
0x00, 0x78, 0x02, 0x0C, 0x00, 0x38, 0x01, 0x0E, 0x00, 0x1C, 0x01, 0x86,
0x00, 0x0E, 0x00, 0x86, 0x00, 0x07, 0x00, 0x87, 0x03, 0xE1, 0x80, 0xC3,
0x07, 0xFC, 0xE1, 0xC3, 0x87, 0xC6, 0x3F, 0xC1, 0x87, 0x81, 0x8F, 0x81,
0xC7, 0x80, 0x40, 0x00, 0xC3, 0xC0, 0x20, 0x00, 0xE3, 0xC0, 0x10, 0x00,
0x61, 0xC0, 0x08, 0x00, 0x61, 0xE0, 0x04, 0x00, 0x70, 0xF0, 0x06, 0x00,
0x30, 0x70, 0x02, 0x00, 0x38, 0x38, 0x03, 0x00, 0x18, 0x1C, 0x01, 0x00,
0x1C, 0x0E, 0x01, 0x80, 0x0C, 0x07, 0x01, 0x80, 0x0E, 0x01, 0xC3, 0x80,
0x06, 0x00, 0x7F, 0x80, 0x06, 0x00, 0x1F, 0x00, 0x07, 0x00, 0x00, 0x00,
0x00, 0x1F, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x70, 0xE0, 0x00,
0x00, 0xE0, 0x60, 0x00, 0x00, 0xC0, 0x30, 0x00, 0x01, 0xC0, 0x30, 0x00,
0x01, 0xC0, 0x30, 0x00, 0x01, 0xC0, 0x30, 0x00, 0x01, 0xC0, 0x70, 0x00,
0x01, 0xE0, 0xE0, 0x00, 0x01, 0xE1, 0xC0, 0x00, 0x00, 0xF3, 0x80, 0x00,
0x00, 0xFF, 0x0F, 0xFC, 0x00, 0xFC, 0x03, 0xF0, 0x00, 0xF8, 0x01, 0xE0,
0x01, 0xFC, 0x01, 0xC0, 0x07, 0x7C, 0x01, 0xC0, 0x0F, 0x3E, 0x01, 0x80,
0x1E, 0x3E, 0x03, 0x00, 0x3C, 0x1F, 0x03, 0x00, 0x7C, 0x1F, 0x06, 0x00,
0x78, 0x0F, 0x86, 0x00, 0x78, 0x07, 0xCC, 0x00, 0xF8, 0x07, 0xE8, 0x00,
0xF8, 0x03, 0xF8, 0x00, 0xF8, 0x01, 0xF0, 0x00, 0xF8, 0x01, 0xF8, 0x00,
0xFC, 0x00, 0xFC, 0x01, 0xFC, 0x01, 0xFE, 0x01, 0x7E, 0x03, 0xBF, 0x86,
0x7F, 0x0F, 0x1F, 0xFE, 0x3F, 0xFC, 0x0F, 0xF8, 0x0F, 0xE0, 0x03, 0xF0,
0x6F, 0xFF, 0xFF, 0x66, 0x66, 0x66, 0x00, 0x10, 0x02, 0x00, 0xC0, 0x18,
0x03, 0x00, 0x60, 0x0E, 0x00, 0xC0, 0x1C, 0x03, 0x80, 0x38, 0x03, 0x80,
0x78, 0x07, 0x00, 0x70, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00,
0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x07, 0x00, 0x70, 0x07, 0x80,
0x38, 0x03, 0x80, 0x38, 0x01, 0xC0, 0x0C, 0x00, 0xC0, 0x06, 0x00, 0x30,
0x01, 0x80, 0x0C, 0x00, 0x60, 0x03, 0xC0, 0x06, 0x00, 0x30, 0x01, 0x80,
0x0C, 0x00, 0x60, 0x07, 0x00, 0x30, 0x03, 0x80, 0x1C, 0x01, 0xC0, 0x1C,
0x01, 0xE0, 0x0E, 0x00, 0xE0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F,
0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0E, 0x00, 0xE0, 0x1E,
0x01, 0xC0, 0x1C, 0x01, 0xC0, 0x38, 0x03, 0x00, 0x70, 0x0E, 0x00, 0xC0,
0x18, 0x03, 0x00, 0x40, 0x08, 0x00, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80,
0x43, 0x86, 0xE1, 0x0F, 0xF1, 0x1F, 0xF9, 0x3E, 0x3D, 0x78, 0x07, 0xC0,
0x01, 0x00, 0x07, 0xC0, 0x19, 0x30, 0xF9, 0x1E, 0xF1, 0x0F, 0xE1, 0x07,
0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x00, 0x38, 0x00, 0x00,
0x70, 0x00, 0x00, 0xE0, 0x00, 0x01, 0xC0, 0x00, 0x03, 0x80, 0x00, 0x07,
0x00, 0x00, 0x0E, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x38, 0x00, 0x00, 0x70,
0x00, 0x00, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0x00,
0x00, 0x0E, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x38, 0x00, 0x00, 0x70, 0x00,
0x00, 0xE0, 0x00, 0x01, 0xC0, 0x00, 0x03, 0x80, 0x00, 0x07, 0x00, 0x00,
0x0E, 0x00, 0x00, 0x73, 0xEF, 0xFF, 0x7C, 0x10, 0x42, 0x08, 0xC6, 0x00,
0xFF, 0xFF, 0xFC, 0x77, 0xFF, 0xF7, 0x00, 0x00, 0x1C, 0x00, 0xE0, 0x03,
0x80, 0x0E, 0x00, 0x70, 0x01, 0xC0, 0x07, 0x00, 0x38, 0x00, 0xE0, 0x03,
0x80, 0x1C, 0x00, 0x70, 0x01, 0xC0, 0x0E, 0x00, 0x38, 0x01, 0xE0, 0x07,
0x00, 0x1C, 0x00, 0xF0, 0x03, 0x80, 0x0E, 0x00, 0x78, 0x01, 0xC0, 0x07,
0x00, 0x3C, 0x00, 0xE0, 0x03, 0x80, 0x1E, 0x00, 0x70, 0x01, 0xC0, 0x0F,
0x00, 0x38, 0x00, 0x00, 0xFC, 0x00, 0x0E, 0x1C, 0x00, 0x70, 0x38, 0x03,
0x80, 0x70, 0x1E, 0x01, 0xE0, 0xF0, 0x03, 0x83, 0xC0, 0x0F, 0x0F, 0x00,
0x3C, 0x7C, 0x00, 0xF9, 0xE0, 0x01, 0xE7, 0x80, 0x07, 0xBE, 0x00, 0x1F,
0xF8, 0x00, 0x7F, 0xE0, 0x01, 0xFF, 0x80, 0x07, 0xFE, 0x00, 0x1F, 0xF8,
0x00, 0x7F, 0xE0, 0x01, 0xFF, 0x80, 0x07, 0xFE, 0x00, 0x1F, 0xF8, 0x00,
0x7F, 0xE0, 0x01, 0xF7, 0x80, 0x07, 0x9E, 0x00, 0x1E, 0x7C, 0x00, 0xF8,
0xF0, 0x03, 0xC3, 0xC0, 0x0F, 0x07, 0x00, 0x38, 0x1E, 0x01, 0xE0, 0x38,
0x07, 0x00, 0x70, 0x38, 0x00, 0xE1, 0xC0, 0x00, 0xFC, 0x00, 0x00, 0x80,
0x1C, 0x03, 0xE0, 0x7F, 0x0C, 0x78, 0x03, 0xC0, 0x1E, 0x00, 0xF0, 0x07,
0x80, 0x3C, 0x01, 0xE0, 0x0F, 0x00, 0x78, 0x03, 0xC0, 0x1E, 0x00, 0xF0,
0x07, 0x80, 0x3C, 0x01, 0xE0, 0x0F, 0x00, 0x78, 0x03, 0xC0, 0x1E, 0x00,
0xF0, 0x07, 0x80, 0x3C, 0x01, 0xE0, 0x0F, 0x00, 0x78, 0x03, 0xC0, 0x3F,
0x0F, 0xFF, 0x01, 0xF8, 0x00, 0x3F, 0xF0, 0x07, 0xFF, 0xE0, 0x70, 0x3F,
0x83, 0x00, 0x7C, 0x30, 0x01, 0xF1, 0x00, 0x0F, 0x98, 0x00, 0x3C, 0x80,
0x01, 0xE0, 0x00, 0x0F, 0x00, 0x00, 0x78, 0x00, 0x03, 0x80, 0x00, 0x1C,
0x00, 0x01, 0xC0, 0x00, 0x0E, 0x00, 0x00, 0xE0, 0x00, 0x07, 0x00, 0x00,
0x70, 0x00, 0x03, 0x00, 0x00, 0x30, 0x00, 0x03, 0x00, 0x00, 0x30, 0x00,
0x03, 0x00, 0x00, 0x30, 0x00, 0x03, 0x00, 0x00, 0x30, 0x00, 0x43, 0x00,
0x02, 0x30, 0x00, 0x23, 0xFF, 0xFF, 0x3F, 0xFF, 0xF3, 0xFF, 0xFF, 0x80,
0x03, 0xF8, 0x03, 0xFF, 0x01, 0x83, 0xE0, 0x80, 0x3C, 0x40, 0x0F, 0x10,
0x01, 0xC8, 0x00, 0x70, 0x00, 0x1C, 0x00, 0x06, 0x00, 0x03, 0x00, 0x00,
0x80, 0x00, 0xC0, 0x00, 0x78, 0x00, 0x7F, 0x80, 0x7F, 0xF0, 0x01, 0xFE,
0x00, 0x0F, 0x80, 0x01, 0xF0, 0x00, 0x3C, 0x00, 0x0F, 0x00, 0x01, 0xC0,
0x00, 0x70, 0x00, 0x1C, 0x00, 0x07, 0x00, 0x01, 0x80, 0x00, 0x60, 0x00,
0x30, 0x00, 0x0C, 0x70, 0x06, 0x3F, 0x07, 0x0F, 0xFF, 0x00, 0xFF, 0x00,
0x00, 0x03, 0x00, 0x00, 0x38, 0x00, 0x01, 0xC0, 0x00, 0x1E, 0x00, 0x01,
0xF0, 0x00, 0x0F, 0x80, 0x00, 0xDC, 0x00, 0x0C, 0xE0, 0x00, 0x47, 0x00,
0x06, 0x38, 0x00, 0x61, 0xC0, 0x06, 0x0E, 0x00, 0x30, 0x70, 0x03, 0x03,
0x80, 0x30, 0x1C, 0x01, 0x80, 0xE0, 0x18, 0x07, 0x01, 0x80, 0x38, 0x08,
0x01, 0xC0, 0xC0, 0x0E, 0x0C, 0x00, 0x70, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF,
0xE0, 0x00, 0xE0, 0x00, 0x07, 0x00, 0x00, 0x38, 0x00, 0x01, 0xC0, 0x00,
0x0E, 0x00, 0x00, 0x70, 0x00, 0x03, 0x80, 0x00, 0x1C, 0x00, 0x00, 0x00,
0x40, 0x7F, 0xF8, 0x1F, 0xFE, 0x03, 0xFF, 0xC0, 0xC0, 0x00, 0x18, 0x00,
0x06, 0x00, 0x00, 0xC0, 0x00, 0x1C, 0x00, 0x07, 0xF8, 0x00, 0xFF, 0xC0,
0x3F, 0xFE, 0x00, 0xFF, 0xE0, 0x01, 0xFE, 0x00, 0x0F, 0xE0, 0x00, 0x7C,
0x00, 0x07, 0x80, 0x00, 0xF8, 0x00, 0x0F, 0x00, 0x01, 0xE0, 0x00, 0x1C,
0x00, 0x03, 0x80, 0x00, 0x70, 0x00, 0x0E, 0x00, 0x01, 0xC0, 0x00, 0x30,
0x00, 0x0E, 0x00, 0x01, 0x80, 0x00, 0x71, 0xE0, 0x1C, 0x3F, 0x07, 0x07,
0xFF, 0x80, 0x3F, 0x80, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x3E, 0x00, 0x0F,
0x80, 0x01, 0xF0, 0x00, 0x1F, 0x00, 0x01, 0xF0, 0x00, 0x1F, 0x00, 0x01,
0xF0, 0x00, 0x1F, 0x00, 0x01, 0xF8, 0x00, 0x0F, 0x80, 0x00, 0xFC, 0x00,
0x07, 0xC7, 0xE0, 0x3E, 0xFF, 0xC3, 0xF8, 0x3F, 0x1F, 0x80, 0x7C, 0xF8,
0x03, 0xF7, 0xC0, 0x0F, 0xBE, 0x00, 0x7F, 0xF0, 0x01, 0xFF, 0x80, 0x0F,
0xFC, 0x00, 0x7F, 0xE0, 0x03, 0xFF, 0x00, 0x1F, 0x78, 0x00, 0xFB, 0xE0,
0x07, 0x9F, 0x00, 0x3C, 0x78, 0x03, 0xE3, 0xE0, 0x1E, 0x0F, 0x81, 0xE0,
0x3E, 0x1E, 0x00, 0xFF, 0xE0, 0x00, 0xFC, 0x00, 0x3F, 0xFF, 0xF3, 0xFF,
0xFF, 0x3F, 0xFF, 0xE7, 0x00, 0x0E, 0x40, 0x00, 0xEC, 0x00, 0x1C, 0x80,
0x01, 0xC0, 0x00, 0x1C, 0x00, 0x03, 0x80, 0x00, 0x38, 0x00, 0x03, 0x80,
0x00, 0x70, 0x00, 0x07, 0x00, 0x00, 0x70, 0x00, 0x0E, 0x00, 0x00, 0xE0,
0x00, 0x0E, 0x00, 0x01, 0xC0, 0x00, 0x1C, 0x00, 0x01, 0xC0, 0x00, 0x38,
0x00, 0x03, 0x80, 0x00, 0x38, 0x00, 0x07, 0x00, 0x00, 0x70, 0x00, 0x07,
0x00, 0x00, 0xE0, 0x00, 0x0E, 0x00, 0x00, 0xE0, 0x00, 0x1E, 0x00, 0x01,
0xC0, 0x00, 0x03, 0xF0, 0x03, 0xFF, 0x03, 0xC1, 0xE0, 0xC0, 0x1C, 0x70,
0x07, 0x18, 0x00, 0xEE, 0x00, 0x3B, 0x80, 0x0E, 0xF0, 0x03, 0xBC, 0x00,
0xE7, 0x80, 0x71, 0xF0, 0x38, 0x3E, 0x1C, 0x07, 0xEE, 0x00, 0xFE, 0x00,
0x1F, 0xC0, 0x03, 0xF8, 0x03, 0xFF, 0x01, 0xC7, 0xE0, 0xE0, 0xFC, 0x70,
0x0F, 0x98, 0x01, 0xEE, 0x00, 0x3F, 0x80, 0x0F, 0xE0, 0x01, 0xF8, 0x00,
0x7E, 0x00, 0x1F, 0xC0, 0x07, 0x70, 0x03, 0x9E, 0x00, 0xE3, 0xE0, 0xF0,
0x7F, 0xF0, 0x07, 0xF0, 0x00, 0x01, 0xF8, 0x00, 0x3F, 0xF0, 0x03, 0xC3,
0xE0, 0x3C, 0x0F, 0x83, 0xC0, 0x3C, 0x3E, 0x00, 0xF1, 0xE0, 0x07, 0xCF,
0x00, 0x3E, 0xF8, 0x00, 0xF7, 0xC0, 0x07, 0xFE, 0x00, 0x3F, 0xF0, 0x01,
0xFF, 0x80, 0x0F, 0xFC, 0x00, 0x7F, 0xF0, 0x03, 0xEF, 0x80, 0x1F, 0x7C,
0x00, 0xF9, 0xF0, 0x0F, 0xC7, 0xE1, 0xFC, 0x1F, 0xF9, 0xE0, 0x3F, 0x1F,
0x00, 0x00, 0xF0, 0x00, 0x0F, 0x80, 0x00, 0x78, 0x00, 0x07, 0xC0, 0x00,
0x7C, 0x00, 0x03, 0xC0, 0x00, 0x3C, 0x00, 0x07, 0xC0, 0x00, 0x7C, 0x00,
0x0F, 0x80, 0x01, 0xE0, 0x00, 0x78, 0x00, 0x00, 0x77, 0xFF, 0xF7, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xBF, 0xFF, 0xB8, 0x39, 0xF7,
0xDF, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0xEF,
0xFF, 0x7C, 0x10, 0x42, 0x08, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x7F, 0x00, 0x01, 0xFC, 0x00, 0x07,
0xF0, 0x00, 0x3F, 0xC0, 0x00, 0xFF, 0x00, 0x03, 0xFC, 0x00, 0x0F, 0xE0,
0x00, 0x3F, 0x80, 0x00, 0xFE, 0x00, 0x00, 0xF8, 0x00, 0x00, 0xFC, 0x00,
0x00, 0x7F, 0x80, 0x00, 0x1F, 0xE0, 0x00, 0x07, 0xF8, 0x00, 0x00, 0xFE,
0x00, 0x00, 0x3F, 0x80, 0x00, 0x0F, 0xF0, 0x00, 0x03, 0xFC, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x07, 0x00, 0x00, 0x01, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0xE0, 0x00,
0x00, 0xF8, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x0F, 0xF0,
0x00, 0x01, 0xFC, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x1F, 0xE0, 0x00, 0x07,
0xF8, 0x00, 0x01, 0xFE, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x1F, 0x00, 0x00,
0x7F, 0x00, 0x01, 0xFC, 0x00, 0x07, 0xF0, 0x00, 0x3F, 0xC0, 0x00, 0xFF,
0x00, 0x03, 0xFC, 0x00, 0x0F, 0xE0, 0x00, 0x3F, 0x80, 0x00, 0xFE, 0x00,
0x00, 0xF8, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0,
0x0F, 0xFE, 0x0C, 0x1F, 0x88, 0x03, 0xEC, 0x01, 0xF7, 0x00, 0x7F, 0xC0,
0x3F, 0xE0, 0x1F, 0x70, 0x0F, 0x80, 0x07, 0xC0, 0x03, 0xC0, 0x01, 0xE0,
0x01, 0xE0, 0x00, 0xF0, 0x00, 0x70, 0x00, 0x70, 0x00, 0x30, 0x00, 0x10,
0x00, 0x18, 0x00, 0x08, 0x00, 0x04, 0x00, 0x06, 0x00, 0x02, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x3E, 0x00,
0x1F, 0x00, 0x0F, 0x80, 0x03, 0x80, 0x00, 0x07, 0xF8, 0x00, 0x00, 0x3F,
0xFF, 0x00, 0x00, 0xFC, 0x07, 0xC0, 0x01, 0xE0, 0x00, 0xE0, 0x07, 0xC0,
0x00, 0x30, 0x0F, 0x00, 0x00, 0x18, 0x1E, 0x00, 0x00, 0x0C, 0x1E, 0x00,
0x00, 0x04, 0x3C, 0x00, 0xF8, 0x06, 0x3C, 0x01, 0xFD, 0xC2, 0x78, 0x03,
0xC7, 0xC3, 0x78, 0x07, 0x07, 0x81, 0xF0, 0x0E, 0x03, 0x81, 0xF0, 0x0E,
0x03, 0x81, 0xF0, 0x1C, 0x07, 0x81, 0xF0, 0x1C, 0x07, 0x01, 0xF0, 0x38,
0x07, 0x01, 0xF0, 0x38, 0x07, 0x03, 0xF0, 0x38, 0x0F, 0x02, 0xF0, 0x38,
0x0E, 0x02, 0xF0, 0x38, 0x1E, 0x04, 0x78, 0x38, 0x1E, 0x0C, 0x78, 0x1C,
0x6E, 0x18, 0x38, 0x1F, 0xC7, 0xF0, 0x3C, 0x0F, 0x03, 0xE0, 0x1E, 0x00,
0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x07, 0xC0,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x60, 0x00, 0xFC, 0x03, 0xE0, 0x00, 0x3F,
0xFF, 0x80, 0x00, 0x07, 0xFC, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x80, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x07,
0xC0, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x0D,
0xF0, 0x00, 0x00, 0x0D, 0xF0, 0x00, 0x00, 0x18, 0xF0, 0x00, 0x00, 0x18,
0xF8, 0x00, 0x00, 0x38, 0x78, 0x00, 0x00, 0x30, 0x7C, 0x00, 0x00, 0x30,
0x7C, 0x00, 0x00, 0x60, 0x3E, 0x00, 0x00, 0x60, 0x3E, 0x00, 0x00, 0xE0,
0x1E, 0x00, 0x00, 0xC0, 0x1F, 0x00, 0x00, 0xC0, 0x1F, 0x00, 0x01, 0x80,
0x0F, 0x80, 0x01, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xC0, 0x03, 0x00,
0x07, 0xC0, 0x07, 0x00, 0x07, 0xC0, 0x06, 0x00, 0x03, 0xE0, 0x06, 0x00,
0x03, 0xE0, 0x0E, 0x00, 0x01, 0xF0, 0x0C, 0x00, 0x01, 0xF0, 0x1C, 0x00,
0x01, 0xF8, 0x3C, 0x00, 0x01, 0xF8, 0x7E, 0x00, 0x01, 0xFC, 0xFF, 0x80,
0x0F, 0xFF, 0xFF, 0xFF, 0xE0, 0x03, 0xFF, 0xFF, 0x80, 0x1F, 0x01, 0xF8,
0x03, 0xE0, 0x0F, 0x80, 0x7C, 0x00, 0xF8, 0x0F, 0x80, 0x1F, 0x81, 0xF0,
0x01, 0xF0, 0x3E, 0x00, 0x3E, 0x07, 0xC0, 0x07, 0xC0, 0xF8, 0x00, 0xF8,
0x1F, 0x00, 0x1F, 0x03, 0xE0, 0x07, 0xC0, 0x7C, 0x01, 0xF0, 0x0F, 0x80,
0xFC, 0x01, 0xFF, 0xFE, 0x00, 0x3F, 0xFF, 0xC0, 0x07, 0xC0, 0x7F, 0x00,
0xF8, 0x01, 0xF0, 0x1F, 0x00, 0x1F, 0x03, 0xE0, 0x03, 0xE0, 0x7C, 0x00,
0x3E, 0x0F, 0x80, 0x07, 0xC1, 0xF0, 0x00, 0xF8, 0x3E, 0x00, 0x1F, 0x07,
0xC0, 0x03, 0xE0, 0xF8, 0x00, 0xF8, 0x1F, 0x00, 0x1F, 0x03, 0xE0, 0x07,
0xC0, 0x7C, 0x07, 0xF0, 0x1F, 0xFF, 0xFC, 0x3F, 0xFF, 0xFC, 0x00, 0x00,
0x1F, 0xF0, 0x20, 0x07, 0xFF, 0xEE, 0x01, 0xF8, 0x1F, 0xE0, 0x3E, 0x00,
0x7E, 0x07, 0x80, 0x01, 0xE0, 0xF0, 0x00, 0x1E, 0x1F, 0x00, 0x00, 0xE3,
0xE0, 0x00, 0x06, 0x3C, 0x00, 0x00, 0x67, 0xC0, 0x00, 0x02, 0x7C, 0x00,
0x00, 0x27, 0x80, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x00,
0xF8, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x0F, 0x80,
0x00, 0x00, 0xF8, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x00, 0xF8, 0x00, 0x00,
0x0F, 0x80, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x00, 0x7C,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x01, 0xF0, 0x00,
0x02, 0x0F, 0x80, 0x00, 0xE0, 0x7E, 0x00, 0x1C, 0x03, 0xF8, 0x0F, 0x00,
0x0F, 0xFF, 0xC0, 0x00, 0x1F, 0xE0, 0x00, 0xFF, 0xFF, 0xC0, 0x00, 0x7F,
0xFF, 0xF8, 0x00, 0x3E, 0x03, 0xFC, 0x00, 0x7C, 0x00, 0xFC, 0x00, 0xF8,
0x00, 0x7E, 0x01, 0xF0, 0x00, 0x7E, 0x03, 0xE0, 0x00, 0x7C, 0x07, 0xC0,
0x00, 0x7C, 0x0F, 0x80, 0x00, 0xF8, 0x1F, 0x00, 0x00, 0xF8, 0x3E, 0x00,
0x01, 0xF0, 0x7C, 0x00, 0x03, 0xF0, 0xF8, 0x00, 0x03, 0xE1, 0xF0, 0x00,
0x07, 0xC3, 0xE0, 0x00, 0x0F, 0x87, 0xC0, 0x00, 0x1F, 0x0F, 0x80, 0x00,
0x3E, 0x1F, 0x00, 0x00, 0x7C, 0x3E, 0x00, 0x00, 0xF8, 0x7C, 0x00, 0x01,
0xF0, 0xF8, 0x00, 0x07, 0xC1, 0xF0, 0x00, 0x0F, 0x83, 0xE0, 0x00, 0x1E,
0x07, 0xC0, 0x00, 0x7C, 0x0F, 0x80, 0x01, 0xF0, 0x1F, 0x00, 0x03, 0xE0,
0x3E, 0x00, 0x1F, 0x80, 0x7C, 0x00, 0x7C, 0x00, 0xF8, 0x0F, 0xF0, 0x07,
0xFF, 0xFF, 0x80, 0x3F, 0xFF, 0xF0, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x07,
0xFF, 0xFF, 0xE0, 0x7C, 0x00, 0x1C, 0x0F, 0x80, 0x01, 0x81, 0xF0, 0x00,
0x30, 0x3E, 0x00, 0x02, 0x07, 0xC0, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x1F,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x7C, 0x00, 0x20, 0x0F, 0x80, 0x04,
0x01, 0xF0, 0x01, 0x80, 0x3E, 0x00, 0x70, 0x07, 0xFF, 0xFE, 0x00, 0xFF,
0xFF, 0xC0, 0x1F, 0x00, 0x38, 0x03, 0xE0, 0x03, 0x00, 0x7C, 0x00, 0x20,
0x0F, 0x80, 0x04, 0x01, 0xF0, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x07, 0xC0,
0x00, 0x00, 0xF8, 0x00, 0x03, 0x1F, 0x00, 0x00, 0x43, 0xE0, 0x00, 0x18,
0x7C, 0x00, 0x07, 0x0F, 0x80, 0x01, 0xC1, 0xF0, 0x00, 0xF8, 0x7F, 0xFF,
0xFF, 0x3F, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0x3F, 0xFF, 0xFF, 0x1F,
0x00, 0x07, 0x1F, 0x00, 0x03, 0x1F, 0x00, 0x03, 0x1F, 0x00, 0x01, 0x1F,
0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F,
0x00, 0x08, 0x1F, 0x00, 0x08, 0x1F, 0x00, 0x18, 0x1F, 0x00, 0x38, 0x1F,
0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x1F, 0x00, 0x38, 0x1F, 0x00, 0x18, 0x1F,
0x00, 0x08, 0x1F, 0x00, 0x08, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F,
0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F,
0x00, 0x00, 0x1F, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x3F, 0x80, 0x00, 0xFF,
0xF0, 0x00, 0x00, 0x0F, 0xF0, 0x08, 0x00, 0xFF, 0xFE, 0x70, 0x07, 0xE0,
0x1F, 0xE0, 0x1F, 0x00, 0x0F, 0xC0, 0x78, 0x00, 0x07, 0x81, 0xE0, 0x00,
0x07, 0x07, 0xC0, 0x00, 0x0E, 0x1F, 0x00, 0x00, 0x0C, 0x3E, 0x00, 0x00,
0x08, 0xF8, 0x00, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00,
0x0F, 0x80, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00,
0x7C, 0x00, 0x03, 0xFF, 0xF8, 0x00, 0x01, 0xFD, 0xF0, 0x00, 0x01, 0xF3,
0xE0, 0x00, 0x03, 0xE7, 0xC0, 0x00, 0x07, 0xCF, 0x80, 0x00, 0x0F, 0x8F,
0x80, 0x00, 0x1F, 0x1F, 0x00, 0x00, 0x3E, 0x3E, 0x00, 0x00, 0x7C, 0x3E,
0x00, 0x00, 0xF8, 0x7C, 0x00, 0x01, 0xF0, 0x7C, 0x00, 0x03, 0xE0, 0xFC,
0x00, 0x07, 0xC0, 0xFC, 0x00, 0x0F, 0x80, 0x7C, 0x00, 0x3F, 0x00, 0x7F,
0x01, 0xFC, 0x00, 0x3F, 0xFF, 0xC0, 0x00, 0x0F, 0xF8, 0x00, 0xFF, 0xE0,
0x1F, 0xFC, 0xFE, 0x00, 0x1F, 0xC1, 0xF0, 0x00, 0x3E, 0x07, 0xC0, 0x00,
0xF8, 0x1F, 0x00, 0x03, 0xE0, 0x7C, 0x00, 0x0F, 0x81, 0xF0, 0x00, 0x3E,
0x07, 0xC0, 0x00, 0xF8, 0x1F, 0x00, 0x03, 0xE0, 0x7C, 0x00, 0x0F, 0x81,
0xF0, 0x00, 0x3E, 0x07, 0xC0, 0x00, 0xF8, 0x1F, 0x00, 0x03, 0xE0, 0x7C,
0x00, 0x0F, 0x81, 0xFF, 0xFF, 0xFE, 0x07, 0xFF, 0xFF, 0xF8, 0x1F, 0x00,
0x03, 0xE0, 0x7C, 0x00, 0x0F, 0x81, 0xF0, 0x00, 0x3E, 0x07, 0xC0, 0x00,
0xF8, 0x1F, 0x00, 0x03, 0xE0, 0x7C, 0x00, 0x0F, 0x81, 0xF0, 0x00, 0x3E,
0x07, 0xC0, 0x00, 0xF8, 0x1F, 0x00, 0x03, 0xE0, 0x7C, 0x00, 0x0F, 0x81,
0xF0, 0x00, 0x3E, 0x07, 0xC0, 0x00, 0xF8, 0x1F, 0x00, 0x03, 0xE0, 0xFE,
0x00, 0x1F, 0xCF, 0xFE, 0x01, 0xFF, 0xC0, 0xFF, 0xF8, 0xFE, 0x03, 0xE0,
0x1F, 0x00, 0xF8, 0x07, 0xC0, 0x3E, 0x01, 0xF0, 0x0F, 0x80, 0x7C, 0x03,
0xE0, 0x1F, 0x00, 0xF8, 0x07, 0xC0, 0x3E, 0x01, 0xF0, 0x0F, 0x80, 0x7C,
0x03, 0xE0, 0x1F, 0x00, 0xF8, 0x07, 0xC0, 0x3E, 0x01, 0xF0, 0x0F, 0x80,
0x7C, 0x03, 0xE0, 0x1F, 0x00, 0xF8, 0x0F, 0xE3, 0xFF, 0xE0, 0x0F, 0xFF,
0x80, 0xFE, 0x00, 0x3E, 0x00, 0x1F, 0x00, 0x0F, 0x80, 0x07, 0xC0, 0x03,
0xE0, 0x01, 0xF0, 0x00, 0xF8, 0x00, 0x7C, 0x00, 0x3E, 0x00, 0x1F, 0x00,
0x0F, 0x80, 0x07, 0xC0, 0x03, 0xE0, 0x01, 0xF0, 0x00, 0xF8, 0x00, 0x7C,
0x00, 0x3E, 0x00, 0x1F, 0x00, 0x0F, 0x80, 0x07, 0xC0, 0x03, 0xE0, 0x01,
0xF0, 0x00, 0xF8, 0x00, 0x7C, 0x00, 0x3C, 0x0E, 0x1E, 0x0F, 0x8F, 0x07,
0xCF, 0x01, 0xFF, 0x00, 0x7E, 0x00, 0xFF, 0xF8, 0x3F, 0xFC, 0x3F, 0xC0,
0x07, 0xE0, 0x0F, 0x80, 0x07, 0x80, 0x0F, 0x80, 0x07, 0x00, 0x0F, 0x80,
0x0E, 0x00, 0x0F, 0x80, 0x1C, 0x00, 0x0F, 0x80, 0x38, 0x00, 0x0F, 0x80,
0x70, 0x00, 0x0F, 0x80, 0xE0, 0x00, 0x0F, 0x81, 0xC0, 0x00, 0x0F, 0x83,
0x80, 0x00, 0x0F, 0x87, 0x00, 0x00, 0x0F, 0x9E, 0x00, 0x00, 0x0F, 0xBC,
0x00, 0x00, 0x0F, 0xFE, 0x00, 0x00, 0x0F, 0xFF, 0x00, 0x00, 0x0F, 0xDF,
0x80, 0x00, 0x0F, 0x8F, 0xC0, 0x00, 0x0F, 0x87, 0xE0, 0x00, 0x0F, 0x83,
0xF0, 0x00, 0x0F, 0x81, 0xF8, 0x00, 0x0F, 0x80, 0xFC, 0x00, 0x0F, 0x80,
0x7E, 0x00, 0x0F, 0x80, 0x3F, 0x00, 0x0F, 0x80, 0x3F, 0x80, 0x0F, 0x80,
0x1F, 0x80, 0x0F, 0x80, 0x0F, 0xC0, 0x0F, 0x80, 0x07, 0xE0, 0x0F, 0x80,
0x07, 0xF0, 0x1F, 0xC0, 0x07, 0xFC, 0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xF0,
0x00, 0x0F, 0xF0, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x1F,
0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7C, 0x00, 0x00,
0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7C, 0x00,
0x00, 0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7C,
0x00, 0x00, 0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF0, 0x00, 0x00,
0x7C, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF0, 0x00,
0x00, 0x7C, 0x00, 0x01, 0x1F, 0x00, 0x00, 0xC7, 0xC0, 0x00, 0x21, 0xF0,
0x00, 0x18, 0x7C, 0x00, 0x0E, 0x1F, 0x00, 0x1F, 0x8F, 0xFF, 0xFF, 0xCF,
0xFF, 0xFF, 0xF0, 0xFF, 0x80, 0x00, 0x03, 0xFE, 0x7F, 0x80, 0x00, 0x07,
0xF0, 0x3F, 0x00, 0x00, 0x1F, 0xC0, 0x7E, 0x00, 0x00, 0x3F, 0x80, 0xFE,
0x00, 0x00, 0xFF, 0x01, 0xFC, 0x00, 0x01, 0xBE, 0x03, 0x7C, 0x00, 0x03,
0x7C, 0x06, 0xF8, 0x00, 0x0E, 0xF8, 0x0D, 0xF8, 0x00, 0x19, 0xF0, 0x19,
0xF0, 0x00, 0x73, 0xE0, 0x33, 0xF0, 0x00, 0xC7, 0xC0, 0x63, 0xE0, 0x03,
0x8F, 0x80, 0xC7, 0xE0, 0x06, 0x1F, 0x01, 0x87, 0xC0, 0x1C, 0x3E, 0x03,
0x0F, 0xC0, 0x30, 0x7C, 0x06, 0x0F, 0x80, 0x60, 0xF8, 0x0C, 0x1F, 0x81,
0x81, 0xF0, 0x18, 0x1F, 0x03, 0x03, 0xE0, 0x30, 0x3F, 0x0C, 0x07, 0xC0,
0x60, 0x3E, 0x18, 0x0F, 0x80, 0xC0, 0x7C, 0x70, 0x1F, 0x01, 0x80, 0x7C,
0xC0, 0x3E, 0x03, 0x00, 0xFB, 0x80, 0x7C, 0x06, 0x00, 0xFE, 0x00, 0xF8,
0x0C, 0x01, 0xFC, 0x01, 0xF0, 0x18, 0x03, 0xF0, 0x03, 0xE0, 0x30, 0x03,
0xE0, 0x07, 0xC0, 0x60, 0x07, 0x80, 0x0F, 0x81, 0xE0, 0x07, 0x00, 0x1F,
0x07, 0xE0, 0x0C, 0x00, 0xFF, 0x3F, 0xF0, 0x08, 0x07, 0xFF, 0x80, 0xFF,
0x00, 0x03, 0xFF, 0x3F, 0x80, 0x00, 0xFC, 0x1F, 0xC0, 0x00, 0x78, 0x0F,
0xC0, 0x00, 0x30, 0x0F, 0xE0, 0x00, 0x30, 0x0F, 0xF0, 0x00, 0x30, 0x0D,
0xF8, 0x00, 0x30, 0x0D, 0xFC, 0x00, 0x30, 0x0C, 0xFC, 0x00, 0x30, 0x0C,
0x7E, 0x00, 0x30, 0x0C, 0x3F, 0x00, 0x30, 0x0C, 0x1F, 0x80, 0x30, 0x0C,
0x1F, 0xC0, 0x30, 0x0C, 0x0F, 0xE0, 0x30, 0x0C, 0x07, 0xE0, 0x30, 0x0C,
0x03, 0xF0, 0x30, 0x0C, 0x01, 0xF8, 0x30, 0x0C, 0x01, 0xFC, 0x30, 0x0C,
0x00, 0xFE, 0x30, 0x0C, 0x00, 0x7E, 0x30, 0x0C, 0x00, 0x3F, 0x30, 0x0C,
0x00, 0x1F, 0xB0, 0x0C, 0x00, 0x0F, 0xF0, 0x0C, 0x00, 0x0F, 0xF0, 0x0C,
0x00, 0x07, 0xF0, 0x0C, 0x00, 0x03, 0xF0, 0x0C, 0x00, 0x01, 0xF0, 0x0C,
0x00, 0x00, 0xF0, 0x1E, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x70, 0xFF,
0xC0, 0x00, 0x30, 0x00, 0x00, 0x00, 0x10, 0x00, 0x1F, 0xE0, 0x00, 0x03,
0xFF, 0xF0, 0x00, 0x1F, 0x03, 0xE0, 0x01, 0xF0, 0x03, 0xE0, 0x0F, 0x80,
0x07, 0xC0, 0x7C, 0x00, 0x0F, 0x01, 0xE0, 0x00, 0x1E, 0x0F, 0x80, 0x00,
0x7C, 0x3C, 0x00, 0x00, 0xF1, 0xF0, 0x00, 0x03, 0xE7, 0xC0, 0x00, 0x0F,
0x9E, 0x00, 0x00, 0x1E, 0xF8, 0x00, 0x00, 0x7F, 0xE0, 0x00, 0x01, 0xFF,
0x80, 0x00, 0x07, 0xFE, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x7F, 0xE0,
0x00, 0x01, 0xFF, 0x80, 0x00, 0x07, 0xFE, 0x00, 0x00, 0x1F, 0xF8, 0x00,
0x00, 0x7D, 0xF0, 0x00, 0x03, 0xE7, 0xC0, 0x00, 0x0F, 0x9F, 0x00, 0x00,
0x3E, 0x3C, 0x00, 0x00, 0xF0, 0xF8, 0x00, 0x07, 0xC1, 0xE0, 0x00, 0x1E,
0x07, 0xC0, 0x00, 0xF8, 0x0F, 0x80, 0x07, 0xC0, 0x1F, 0x00, 0x3E, 0x00,
0x1F, 0x03, 0xE0, 0x00, 0x3F, 0xFF, 0x00, 0x00, 0x1F, 0xE0, 0x00, 0xFF,
0xFF, 0x00, 0x7F, 0xFF, 0x80, 0x7C, 0x1F, 0xC0, 0xF8, 0x07, 0xC1, 0xF0,
0x07, 0xC3, 0xE0, 0x0F, 0x87, 0xC0, 0x0F, 0x8F, 0x80, 0x1F, 0x1F, 0x00,
0x3E, 0x3E, 0x00, 0x7C, 0x7C, 0x00, 0xF8, 0xF8, 0x01, 0xF1, 0xF0, 0x07,
0xC3, 0xE0, 0x0F, 0x87, 0xC0, 0x3E, 0x0F, 0x81, 0xF8, 0x1F, 0xFF, 0xC0,
0x3F, 0xFE, 0x00, 0x7C, 0x00, 0x00, 0xF8, 0x00, 0x01, 0xF0, 0x00, 0x03,
0xE0, 0x00, 0x07, 0xC0, 0x00, 0x0F, 0x80, 0x00, 0x1F, 0x00, 0x00, 0x3E,
0x00, 0x00, 0x7C, 0x00, 0x00, 0xF8, 0x00, 0x01, 0xF0, 0x00, 0x07, 0xF0,
0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x1F, 0xE0, 0x00, 0x01, 0xFF, 0xF8,
0x00, 0x07, 0xC0, 0xF8, 0x00, 0x3E, 0x00, 0x7C, 0x00, 0xF8, 0x00, 0x7C,
0x03, 0xE0, 0x00, 0x7C, 0x07, 0x80, 0x00, 0x78, 0x1F, 0x00, 0x00, 0xF8,
0x3C, 0x00, 0x00, 0xF0, 0xF8, 0x00, 0x01, 0xF1, 0xF0, 0x00, 0x03, 0xE3,
0xC0, 0x00, 0x03, 0xCF, 0x80, 0x00, 0x07, 0xDF, 0x00, 0x00, 0x0F, 0xBE,
0x00, 0x00, 0x1F, 0x7C, 0x00, 0x00, 0x3E, 0xF8, 0x00, 0x00, 0x7D, 0xF0,
0x00, 0x00, 0xFB, 0xE0, 0x00, 0x01, 0xF7, 0xC0, 0x00, 0x03, 0xEF, 0x80,
0x00, 0x07, 0xCF, 0x00, 0x00, 0x1F, 0x1F, 0x00, 0x00, 0x3E, 0x3E, 0x00,
0x00, 0x7C, 0x3C, 0x00, 0x01, 0xF0, 0x7C, 0x00, 0x03, 0xE0, 0x78, 0x00,
0x0F, 0x80, 0x78, 0x00, 0x1E, 0x00, 0x78, 0x00, 0x78, 0x00, 0x7C, 0x03,
0xE0, 0x00, 0x3F, 0x3F, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x1F, 0xC0,
0x00, 0x00, 0x1F, 0xC0, 0x00, 0x00, 0x1F, 0xC0, 0x00, 0x00, 0x1F, 0xC0,
0x00, 0x00, 0x0F, 0xE0, 0x00, 0x00, 0x0F, 0xE0, 0x00, 0x00, 0x03, 0xF8,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFE, 0x00, 0x1F,
0x03, 0xF8, 0x01, 0xF0, 0x0F, 0x80, 0x1F, 0x00, 0x7C, 0x01, 0xF0, 0x03,
0xE0, 0x1F, 0x00, 0x3E, 0x01, 0xF0, 0x03, 0xE0, 0x1F, 0x00, 0x3E, 0x01,
0xF0, 0x03, 0xE0, 0x1F, 0x00, 0x3E, 0x01, 0xF0, 0x07, 0xC0, 0x1F, 0x00,
0x7C, 0x01, 0xF0, 0x0F, 0x80, 0x1F, 0x07, 0xF0, 0x01, 0xFF, 0xFC, 0x00,
0x1F, 0xFE, 0x00, 0x01, 0xF1, 0xF0, 0x00, 0x1F, 0x1F, 0x80, 0x01, 0xF0,
0xF8, 0x00, 0x1F, 0x07, 0xC0, 0x01, 0xF0, 0x3E, 0x00, 0x1F, 0x03, 0xF0,
0x01, 0xF0, 0x1F, 0x80, 0x1F, 0x00, 0xFC, 0x01, 0xF0, 0x07, 0xC0, 0x1F,
0x00, 0x7E, 0x01, 0xF0, 0x03, 0xF0, 0x1F, 0x00, 0x1F, 0x83, 0xF8, 0x00,
0xFC, 0xFF, 0xF0, 0x0F, 0xF0, 0x03, 0xF0, 0x20, 0x7F, 0xF3, 0x07, 0xC1,
0xF8, 0x78, 0x03, 0xC3, 0x80, 0x0E, 0x3C, 0x00, 0x31, 0xE0, 0x01, 0xCF,
0x00, 0x06, 0x7C, 0x00, 0x33, 0xE0, 0x01, 0x9F, 0x80, 0x00, 0x7E, 0x00,
0x03, 0xFC, 0x00, 0x0F, 0xF0, 0x00, 0x3F, 0xE0, 0x00, 0xFF, 0xC0, 0x01,
0xFF, 0x00, 0x07, 0xFE, 0x00, 0x0F, 0xF8, 0x00, 0x1F, 0xC0, 0x00, 0x7F,
0x00, 0x01, 0xFC, 0x00, 0x07, 0xF0, 0x00, 0x1F, 0xC0, 0x00, 0xFE, 0x00,
0x07, 0xF8, 0x00, 0x3F, 0xC0, 0x01, 0xEF, 0x00, 0x1F, 0x3C, 0x01, 0xF1,
0xF8, 0x1F, 0x0C, 0xFF, 0xF0, 0x40, 0xFE, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xC0, 0x7C, 0x07, 0xF0, 0x0F, 0x80, 0x3C, 0x01, 0xF0,
0x07, 0x00, 0x3E, 0x00, 0x60, 0x07, 0xC0, 0x08, 0x00, 0xF8, 0x00, 0x00,
0x1F, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x0F, 0x80,
0x00, 0x01, 0xF0, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x00,
0xF8, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x7C, 0x00,
0x00, 0x0F, 0x80, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x07,
0xC0, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x03, 0xE0, 0x00,
0x00, 0x7C, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7F,
0x00, 0x00, 0x7F, 0xFC, 0x00, 0xFF, 0xF8, 0x03, 0xFF, 0x3F, 0xE0, 0x00,
0xFC, 0x0F, 0x80, 0x00, 0x78, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00,
0x30, 0x0F, 0x80, 0x00, 0x30, 0x0F, 0x80, 0x00, 0x20, 0x07, 0xC0, 0x00,
0x60, 0x07, 0xC0, 0x00, 0x60, 0x03, 0xE0, 0x00, 0xC0, 0x03, 0xF0, 0x01,
0xC0, 0x01, 0xFC, 0x07, 0x80, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x0F, 0xF8,
0x00, 0xFF, 0xF8, 0x01, 0xFF, 0x3F, 0xC0, 0x00, 0x7E, 0x0F, 0x80, 0x00,
0x3C, 0x0F, 0xC0, 0x00, 0x38, 0x07, 0xC0, 0x00, 0x38, 0x07, 0xC0, 0x00,
0x30, 0x03, 0xE0, 0x00, 0x70, 0x03, 0xE0, 0x00, 0x60, 0x01, 0xF0, 0x00,
0x60, 0x01, 0xF0, 0x00, 0xE0, 0x01, 0xF8, 0x00, 0xC0, 0x00, 0xF8, 0x01,
0xC0, 0x00, 0xF8, 0x01, 0x80, 0x00, 0x7C, 0x01, 0x80, 0x00, 0x7C, 0x03,
0x80, 0x00, 0x3E, 0x03, 0x00, 0x00, 0x3E, 0x07, 0x00, 0x00, 0x1F, 0x06,
0x00, 0x00, 0x1F, 0x06, 0x00, 0x00, 0x1F, 0x8E, 0x00, 0x00, 0x0F, 0x8C,
0x00, 0x00, 0x0F, 0x9C, 0x00, 0x00, 0x07, 0xD8, 0x00, 0x00, 0x07, 0xD8,
0x00, 0x00, 0x03, 0xF8, 0x00, 0x00, 0x03, 0xF0, 0x00, 0x00, 0x01, 0xF0,
0x00, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x00, 0xE0,
0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x40, 0x00, 0xFF, 0xF1, 0xFF,
0xF0, 0x1F, 0xF3, 0xF8, 0x07, 0xF8, 0x00, 0x7C, 0x1F, 0x80, 0x3F, 0x00,
0x03, 0x80, 0xF8, 0x01, 0xF0, 0x00, 0x30, 0x0F, 0x80, 0x1F, 0x00, 0x03,
0x00, 0x7C, 0x00, 0xF8, 0x00, 0x30, 0x07, 0xC0, 0x0F, 0x80, 0x06, 0x00,
0x3E, 0x00, 0x7C, 0x00, 0x60, 0x03, 0xE0, 0x07, 0xC0, 0x06, 0x00, 0x3E,
0x00, 0x7C, 0x00, 0xC0, 0x01, 0xF0, 0x07, 0xE0, 0x0C, 0x00, 0x1F, 0x00,
0xFE, 0x01, 0xC0, 0x01, 0xF0, 0x0D, 0xE0, 0x18, 0x00, 0x0F, 0x80, 0xDF,
0x01, 0x80, 0x00, 0xF8, 0x19, 0xF0, 0x30, 0x00, 0x07, 0xC1, 0x8F, 0x83,
0x00, 0x00, 0x7C, 0x38, 0xF8, 0x30, 0x00, 0x07, 0xC3, 0x0F, 0x86, 0x00,
0x00, 0x3E, 0x30, 0x7C, 0x60, 0x00, 0x03, 0xE7, 0x07, 0xCE, 0x00, 0x00,
0x3E, 0x60, 0x3E, 0xC0, 0x00, 0x01, 0xF6, 0x03, 0xEC, 0x00, 0x00, 0x1F,
0xE0, 0x3F, 0xC0, 0x00, 0x01, 0xFC, 0x01, 0xF8, 0x00, 0x00, 0x0F, 0xC0,
0x1F, 0x80, 0x00, 0x00, 0xF8, 0x01, 0xF8, 0x00, 0x00, 0x0F, 0x80, 0x0F,
0x00, 0x00, 0x00, 0x78, 0x00, 0xF0, 0x00, 0x00, 0x07, 0x00, 0x07, 0x00,
0x00, 0x00, 0x70, 0x00, 0x60, 0x00, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00,
0x00, 0x20, 0x00, 0x20, 0x00, 0x7F, 0xFE, 0x03, 0xFF, 0x8F, 0xF8, 0x00,
0x7E, 0x01, 0xFC, 0x00, 0x1C, 0x00, 0x7E, 0x00, 0x1C, 0x00, 0x1F, 0x00,
0x0C, 0x00, 0x07, 0xC0, 0x0E, 0x00, 0x03, 0xF0, 0x0E, 0x00, 0x00, 0xF8,
0x0E, 0x00, 0x00, 0x3E, 0x06, 0x00, 0x00, 0x1F, 0x86, 0x00, 0x00, 0x07,
0xC7, 0x00, 0x00, 0x01, 0xF7, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x3F, 0x00, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00,
0x03, 0xF8, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x03, 0x9F, 0x00, 0x00,
0x01, 0x8F, 0xC0, 0x00, 0x01, 0x83, 0xF0, 0x00, 0x01, 0xC0, 0xF8, 0x00,
0x01, 0xC0, 0x7E, 0x00, 0x01, 0xC0, 0x1F, 0x80, 0x01, 0xC0, 0x07, 0xC0,
0x00, 0xC0, 0x03, 0xF0, 0x00, 0xE0, 0x00, 0xFC, 0x00, 0xE0, 0x00, 0x7F,
0x00, 0xF0, 0x00, 0x1F, 0x80, 0xFC, 0x00, 0x1F, 0xF3, 0xFF, 0x80, 0x7F,
0xFE, 0xFF, 0xF8, 0x03, 0xFF, 0x3F, 0xE0, 0x00, 0x7C, 0x1F, 0xC0, 0x00,
0x78, 0x0F, 0xC0, 0x00, 0x70, 0x07, 0xE0, 0x00, 0x60, 0x03, 0xF0, 0x00,
0xE0, 0x01, 0xF0, 0x01, 0xC0, 0x01, 0xF8, 0x01, 0x80, 0x00, 0xFC, 0x03,
0x80, 0x00, 0x7C, 0x07, 0x00, 0x00, 0x7E, 0x06, 0x00, 0x00, 0x3F, 0x0E,
0x00, 0x00, 0x1F, 0x1C, 0x00, 0x00, 0x1F, 0x98, 0x00, 0x00, 0x0F, 0xF8,
0x00, 0x00, 0x07, 0xF0, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x03, 0xE0,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0,
0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xF0,
0x00, 0x00, 0x3F, 0xFE, 0x00, 0x3F, 0xFF, 0xFF, 0xC7, 0xFF, 0xFF, 0xF8,
0xF0, 0x00, 0x3E, 0x38, 0x00, 0x0F, 0x86, 0x00, 0x03, 0xF0, 0xC0, 0x00,
0x7C, 0x10, 0x00, 0x1F, 0x02, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF8, 0x00,
0x00, 0x3E, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x03, 0xF0, 0x00, 0x00, 0xFC,
0x00, 0x00, 0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF8, 0x00, 0x00,
0x7E, 0x00, 0x00, 0x0F, 0x80, 0x00, 0x03, 0xF0, 0x00, 0x00, 0xFC, 0x00,
0x00, 0x1F, 0x00, 0x00, 0x07, 0xC0, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x7E,
0x00, 0x01, 0x0F, 0x80, 0x00, 0x63, 0xF0, 0x00, 0x0C, 0xFC, 0x00, 0x03,
0xBF, 0x00, 0x00, 0xE7, 0xC0, 0x00, 0x7D, 0xFF, 0xFF, 0xFF, 0xBF, 0xFF,
0xFF, 0xF0, 0xFF, 0xF0, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0,
0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0, 0x70, 0x38, 0x1C,
0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03,
0x81, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0F, 0x07, 0xFC, 0xE0, 0x01, 0xC0,
0x07, 0x00, 0x1C, 0x00, 0x38, 0x00, 0xE0, 0x03, 0x80, 0x07, 0x00, 0x1C,
0x00, 0x70, 0x00, 0xE0, 0x03, 0x80, 0x0E, 0x00, 0x1C, 0x00, 0x70, 0x01,
0xC0, 0x03, 0x80, 0x0E, 0x00, 0x38, 0x00, 0x70, 0x01, 0xC0, 0x07, 0x00,
0x0E, 0x00, 0x38, 0x00, 0xE0, 0x01, 0xC0, 0x07, 0x00, 0x1E, 0x00, 0x38,
0x00, 0xE0, 0x03, 0xC0, 0x07, 0xFF, 0x83, 0xC0, 0xE0, 0x70, 0x38, 0x1C,
0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03,
0x81, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0,
0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0, 0x70, 0x3F, 0xFC,
0x00, 0xF0, 0x00, 0x0F, 0x00, 0x01, 0xF8, 0x00, 0x1F, 0x80, 0x03, 0xDC,
0x00, 0x39, 0xC0, 0x07, 0x9E, 0x00, 0x70, 0xE0, 0x0F, 0x0F, 0x00, 0xE0,
0x70, 0x1E, 0x07, 0x81, 0xC0, 0x38, 0x3C, 0x03, 0xC3, 0x80, 0x1C, 0x78,
0x01, 0xE7, 0x00, 0x0E, 0xF0, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xE0, 0x3C, 0x0F, 0x81, 0xF0, 0x1E, 0x03, 0xC0, 0x38, 0x07, 0x03,
0xF0, 0x07, 0x0E, 0x03, 0x81, 0xC1, 0xE0, 0x30, 0x78, 0x0E, 0x1E, 0x03,
0x83, 0x00, 0xE0, 0x00, 0x38, 0x00, 0x3E, 0x00, 0x73, 0x80, 0x70, 0xE0,
0x70, 0x38, 0x38, 0x0E, 0x1C, 0x03, 0x8F, 0x00, 0xE3, 0xC0, 0x38, 0xF0,
0x0E, 0x3E, 0x07, 0x8F, 0xC3, 0xE1, 0xFF, 0x3F, 0x1F, 0x07, 0x80, 0x06,
0x00, 0x01, 0xF0, 0x00, 0x3F, 0x80, 0x00, 0x3C, 0x00, 0x01, 0xE0, 0x00,
0x0F, 0x00, 0x00, 0x78, 0x00, 0x03, 0xC0, 0x00, 0x1E, 0x00, 0x00, 0xF0,
0x00, 0x07, 0x80, 0x00, 0x3C, 0x7E, 0x01, 0xEF, 0xFC, 0x0F, 0xC3, 0xF0,
0x7C, 0x07, 0x83, 0xC0, 0x3E, 0x1E, 0x00, 0xF0, 0xF0, 0x07, 0xC7, 0x80,
0x1E, 0x3C, 0x00, 0xF1, 0xE0, 0x07, 0x8F, 0x00, 0x3C, 0x78, 0x01, 0xE3,
0xC0, 0x0F, 0x1E, 0x00, 0x70, 0xF0, 0x03, 0x87, 0x80, 0x38, 0x3C, 0x01,
0xC1, 0xE0, 0x1C, 0x0F, 0xC1, 0xC0, 0x1F, 0xFC, 0x00, 0x3F, 0x80, 0x01,
0xFC, 0x00, 0xFF, 0xE0, 0x38, 0x3E, 0x0E, 0x03, 0xE3, 0x80, 0x7C, 0xE0,
0x07, 0x18, 0x00, 0x03, 0x00, 0x00, 0xE0, 0x00, 0x1C, 0x00, 0x03, 0x80,
0x00, 0x70, 0x00, 0x0E, 0x00, 0x01, 0xE0, 0x00, 0x3C, 0x00, 0x1B, 0xC0,
0x02, 0x7C, 0x01, 0x87, 0xE0, 0x60, 0x7F, 0xF8, 0x07, 0xFE, 0x00, 0x3F,
0x00, 0x00, 0x00, 0x60, 0x00, 0x0F, 0x80, 0x00, 0xFE, 0x00, 0x00, 0x78,
0x00, 0x01, 0xE0, 0x00, 0x07, 0x80, 0x00, 0x1E, 0x00, 0x00, 0x78, 0x00,
0x01, 0xE0, 0x00, 0x07, 0x80, 0x00, 0x1E, 0x00, 0x7C, 0x78, 0x07, 0xFD,
0xE0, 0x3C, 0x3F, 0x81, 0xC0, 0x3E, 0x0E, 0x00, 0xF8, 0x38, 0x01, 0xE1,
0xE0, 0x07, 0x87, 0x00, 0x1E, 0x3C, 0x00, 0x78, 0xF0, 0x01, 0xE3, 0xC0,
0x07, 0x8F, 0x00, 0x1E, 0x3C, 0x00, 0x78, 0xF0, 0x01, 0xE3, 0xE0, 0x07,
0x87, 0x80, 0x1E, 0x1F, 0x00, 0x78, 0x3E, 0x03, 0xE0, 0xFC, 0x1F, 0xF0,
0xFF, 0xDF, 0x00, 0xFC, 0x60, 0x03, 0xF8, 0x03, 0xFF, 0x01, 0xC1, 0xE0,
0xC0, 0x3C, 0x70, 0x0F, 0x98, 0x01, 0xE7, 0xFF, 0xFB, 0xFF, 0xFE, 0xE0,
0x00, 0x38, 0x00, 0x0E, 0x00, 0x03, 0x80, 0x00, 0xF0, 0x00, 0x3C, 0x00,
0x1F, 0x00, 0x05, 0xE0, 0x02, 0x7C, 0x01, 0x8F, 0xC1, 0xC3, 0xFF, 0xE0,
0x7F, 0xF0, 0x07, 0xF0, 0x00, 0x00, 0x7E, 0x00, 0xFF, 0xC0, 0xE3, 0xE0,
0x60, 0x70, 0x70, 0x00, 0x38, 0x00, 0x1C, 0x00, 0x1E, 0x00, 0x0F, 0x00,
0x07, 0x80, 0x03, 0xC0, 0x01, 0xE0, 0x07, 0xFF, 0x83, 0xFF, 0xC0, 0x3C,
0x00, 0x1E, 0x00, 0x0F, 0x00, 0x07, 0x80, 0x03, 0xC0, 0x01, 0xE0, 0x00,
0xF0, 0x00, 0x78, 0x00, 0x3C, 0x00, 0x1E, 0x00, 0x0F, 0x00, 0x07, 0x80,
0x03, 0xC0, 0x01, 0xE0, 0x00, 0xF0, 0x00, 0x78, 0x00, 0x3C, 0x00, 0x3F,
0x00, 0xFF, 0xF0, 0x00, 0x01, 0xF8, 0x00, 0x3F, 0xF0, 0x03, 0xC7, 0xFE,
0x3C, 0x1F, 0xF1, 0xC0, 0x70, 0x1E, 0x03, 0xC0, 0xF0, 0x0E, 0x07, 0x80,
0x70, 0x3C, 0x03, 0x81, 0xE0, 0x1C, 0x07, 0x80, 0xC0, 0x3E, 0x0E, 0x00,
0x78, 0xE0, 0x01, 0xFC, 0x00, 0x18, 0x00, 0x01, 0x80, 0x00, 0x18, 0x00,
0x01, 0xE0, 0x00, 0x0F, 0xFF, 0xC0, 0x3F, 0xFF, 0x80, 0xFF, 0xFE, 0x0C,
0x00, 0x38, 0xC0, 0x00, 0x4C, 0x00, 0x02, 0x60, 0x00, 0x17, 0x00, 0x01,
0x38, 0x00, 0x09, 0xE0, 0x00, 0x87, 0xC0, 0x38, 0x1F, 0xFF, 0x00, 0x3F,
0xC0, 0x00, 0x06, 0x00, 0x00, 0xF8, 0x00, 0x0F, 0xE0, 0x00, 0x07, 0x80,
0x00, 0x1E, 0x00, 0x00, 0x78, 0x00, 0x01, 0xE0, 0x00, 0x07, 0x80, 0x00,
0x1E, 0x00, 0x00, 0x78, 0x00, 0x01, 0xE0, 0x00, 0x07, 0x87, 0xE0, 0x1E,
0x7F, 0xC0, 0x7B, 0x0F, 0x81, 0xF8, 0x1E, 0x07, 0x80, 0x3C, 0x1E, 0x00,
0xF0, 0x78, 0x03, 0xC1, 0xE0, 0x0F, 0x07, 0x80, 0x3C, 0x1E, 0x00, 0xF0,
0x78, 0x03, 0xC1, 0xE0, 0x0F, 0x07, 0x80, 0x3C, 0x1E, 0x00, 0xF0, 0x78,
0x03, 0xC1, 0xE0, 0x0F, 0x07, 0x80, 0x3C, 0x1E, 0x00, 0xF0, 0x78, 0x03,
0xC3, 0xF0, 0x1F, 0x9F, 0xF1, 0xFF, 0x0E, 0x03, 0xE0, 0x7C, 0x0F, 0x80,
0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x70,
0x7E, 0x1F, 0xC0, 0x78, 0x0F, 0x01, 0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x1E,
0x03, 0xC0, 0x78, 0x0F, 0x01, 0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x1E, 0x07,
0xE7, 0xFF, 0x00, 0xE0, 0x1F, 0x01, 0xF0, 0x1F, 0x00, 0xE0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x70, 0x3F, 0x07,
0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00,
0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00,
0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xE0, 0x0E, 0xE0,
0xEF, 0x1C, 0xFF, 0x87, 0xE0, 0x06, 0x00, 0x00, 0x7C, 0x00, 0x03, 0xF8,
0x00, 0x00, 0xF0, 0x00, 0x01, 0xE0, 0x00, 0x03, 0xC0, 0x00, 0x07, 0x80,
0x00, 0x0F, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x78, 0x00,
0x00, 0xF0, 0x7F, 0xE1, 0xE0, 0x3E, 0x03, 0xC0, 0x70, 0x07, 0x81, 0x80,
0x0F, 0x06, 0x00, 0x1E, 0x18, 0x00, 0x3C, 0x60, 0x00, 0x79, 0x80, 0x00,
0xFF, 0x00, 0x01, 0xFF, 0x00, 0x03, 0xDE, 0x00, 0x07, 0x9E, 0x00, 0x0F,
0x3E, 0x00, 0x1E, 0x3E, 0x00, 0x3C, 0x3E, 0x00, 0x78, 0x3C, 0x00, 0xF0,
0x3C, 0x01, 0xE0, 0x7C, 0x03, 0xC0, 0x7C, 0x0F, 0xC0, 0xFE, 0x7F, 0xE3,
0xFF, 0x03, 0x03, 0xE1, 0xFC, 0x07, 0x80, 0xF0, 0x1E, 0x03, 0xC0, 0x78,
0x0F, 0x01, 0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x1E, 0x03, 0xC0, 0x78, 0x0F,
0x01, 0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x1E, 0x03, 0xC0, 0x78, 0x0F, 0x01,
0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x1E, 0x07, 0xE7, 0xFF, 0x1E, 0x1F, 0x01,
0xF8, 0x1F, 0xCF, 0xF0, 0xFF, 0x80, 0xFF, 0x0F, 0x70, 0xF8, 0x0F, 0x81,
0xF8, 0x0F, 0x01, 0xE0, 0x1E, 0x00, 0xF0, 0x3C, 0x03, 0xC0, 0x1E, 0x07,
0x80, 0x78, 0x03, 0xC0, 0xF0, 0x0F, 0x00, 0x78, 0x1E, 0x01, 0xE0, 0x0F,
0x03, 0xC0, 0x3C, 0x01, 0xE0, 0x78, 0x07, 0x80, 0x3C, 0x0F, 0x00, 0xF0,
0x07, 0x81, 0xE0, 0x1E, 0x00, 0xF0, 0x3C, 0x03, 0xC0, 0x1E, 0x07, 0x80,
0x78, 0x03, 0xC0, 0xF0, 0x0F, 0x00, 0x78, 0x1E, 0x01, 0xE0, 0x0F, 0x03,
0xC0, 0x3C, 0x01, 0xE0, 0x78, 0x07, 0x80, 0x3C, 0x1F, 0x81, 0xF8, 0x0F,
0xCF, 0xFC, 0xFF, 0xC7, 0xFE, 0x1E, 0x1F, 0x83, 0xF9, 0xFF, 0x03, 0xFC,
0x3E, 0x07, 0xC0, 0x7C, 0x1E, 0x00, 0xF0, 0x78, 0x03, 0xC1, 0xE0, 0x0F,
0x07, 0x80, 0x3C, 0x1E, 0x00, 0xF0, 0x78, 0x03, 0xC1, 0xE0, 0x0F, 0x07,
0x80, 0x3C, 0x1E, 0x00, 0xF0, 0x78, 0x03, 0xC1, 0xE0, 0x0F, 0x07, 0x80,
0x3C, 0x1E, 0x00, 0xF0, 0x78, 0x03, 0xC1, 0xE0, 0x0F, 0x0F, 0xC0, 0x7E,
0x7F, 0xC3, 0xFC, 0x01, 0xFE, 0x00, 0x1F, 0xFE, 0x00, 0xF0, 0x7C, 0x0F,
0x80, 0xF8, 0x3C, 0x01, 0xF1, 0xE0, 0x03, 0xE7, 0x80, 0x0F, 0xBE, 0x00,
0x3F, 0xF8, 0x00, 0x7F, 0xE0, 0x01, 0xFF, 0x80, 0x07, 0xFE, 0x00, 0x1F,
0xF8, 0x00, 0x7F, 0xF0, 0x01, 0xE7, 0xC0, 0x07, 0x9F, 0x80, 0x3E, 0x3E,
0x00, 0xF0, 0x7C, 0x07, 0x80, 0xF8, 0x3C, 0x01, 0xFF, 0xE0, 0x00, 0xFC,
0x00, 0x0E, 0x3F, 0x07, 0xF7, 0xFE, 0x07, 0xE0, 0xF8, 0x3E, 0x03, 0xE1,
0xE0, 0x0F, 0x0F, 0x00, 0x7C, 0x78, 0x03, 0xE3, 0xC0, 0x0F, 0x1E, 0x00,
0x78, 0xF0, 0x03, 0xC7, 0x80, 0x1E, 0x3C, 0x00, 0xF1, 0xE0, 0x07, 0x8F,
0x00, 0x38, 0x78, 0x03, 0xC3, 0xC0, 0x1E, 0x1E, 0x00, 0xE0, 0xF8, 0x0E,
0x07, 0xE0, 0xE0, 0x3D, 0xFE, 0x01, 0xE7, 0xC0, 0x0F, 0x00, 0x00, 0x78,
0x00, 0x03, 0xC0, 0x00, 0x1E, 0x00, 0x00, 0xF0, 0x00, 0x07, 0x80, 0x00,
0x3C, 0x00, 0x01, 0xE0, 0x00, 0x1F, 0x80, 0x03, 0xFF, 0x80, 0x00, 0x01,
0xF8, 0x20, 0x3F, 0xF3, 0x03, 0xC1, 0xF8, 0x3C, 0x07, 0xC3, 0xC0, 0x1E,
0x1C, 0x00, 0xF1, 0xE0, 0x07, 0x8E, 0x00, 0x3C, 0xF0, 0x01, 0xE7, 0x80,
0x0F, 0x3C, 0x00, 0x79, 0xE0, 0x03, 0xCF, 0x00, 0x1E, 0x78, 0x00, 0xF3,
0xE0, 0x07, 0x9F, 0x00, 0x3C, 0x7C, 0x01, 0xE3, 0xE0, 0x1F, 0x0F, 0xC1,
0xF8, 0x3F, 0xF3, 0xC0, 0x7E, 0x1E, 0x00, 0x00, 0xF0, 0x00, 0x07, 0x80,
0x00, 0x3C, 0x00, 0x01, 0xE0, 0x00, 0x0F, 0x00, 0x00, 0x78, 0x00, 0x03,
0xC0, 0x00, 0x1E, 0x00, 0x03, 0xF8, 0x00, 0x7F, 0xE0, 0x06, 0x3C, 0xFC,
0xFE, 0xFA, 0x78, 0xF8, 0x71, 0xE0, 0x03, 0xC0, 0x07, 0x80, 0x0F, 0x00,
0x1E, 0x00, 0x3C, 0x00, 0x78, 0x00, 0xF0, 0x01, 0xE0, 0x03, 0xC0, 0x07,
0x80, 0x0F, 0x00, 0x1E, 0x00, 0x3C, 0x00, 0x78, 0x01, 0xF8, 0x0F, 0xFC,
0x00, 0x1F, 0x91, 0x87, 0x98, 0x1D, 0xC0, 0x6E, 0x03, 0x70, 0x0B, 0xC0,
0x5F, 0x80, 0x7E, 0x01, 0xFC, 0x07, 0xF0, 0x0F, 0xE0, 0x3F, 0x00, 0x7E,
0x01, 0xF0, 0x07, 0xC0, 0x3E, 0x01, 0xF8, 0x0D, 0xE0, 0xC8, 0xF8, 0x00,
0x04, 0x00, 0xC0, 0x0C, 0x01, 0xC0, 0x3C, 0x07, 0xFC, 0xFF, 0xC3, 0xC0,
0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xC0,
0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xC0, 0x3C, 0x03, 0xE2,
0x1F, 0xC0, 0xF8, 0xFC, 0x0F, 0xE1, 0xF0, 0x0F, 0x83, 0xC0, 0x1E, 0x0F,
0x00, 0x78, 0x3C, 0x01, 0xE0, 0xF0, 0x07, 0x83, 0xC0, 0x1E, 0x0F, 0x00,
0x78, 0x3C, 0x01, 0xE0, 0xF0, 0x07, 0x83, 0xC0, 0x1E, 0x0F, 0x00, 0x78,
0x3C, 0x01, 0xE0, 0xF0, 0x07, 0x83, 0xC0, 0x1E, 0x0F, 0x00, 0x78, 0x3C,
0x01, 0xE0, 0xF8, 0x0F, 0x81, 0xF0, 0xFF, 0x03, 0xFE, 0x7F, 0x07, 0xE1,
0xC0, 0xFF, 0x81, 0xFC, 0xFC, 0x01, 0xC1, 0xE0, 0x07, 0x07, 0x80, 0x18,
0x0F, 0x00, 0x60, 0x3C, 0x01, 0x00, 0x78, 0x0C, 0x01, 0xE0, 0x30, 0x07,
0x81, 0x80, 0x0F, 0x06, 0x00, 0x3C, 0x10, 0x00, 0x78, 0xC0, 0x01, 0xE3,
0x00, 0x03, 0x98, 0x00, 0x0F, 0x60, 0x00, 0x3D, 0x00, 0x00, 0x7C, 0x00,
0x01, 0xF0, 0x00, 0x03, 0x80, 0x00, 0x0E, 0x00, 0x00, 0x30, 0x00, 0x00,
0x40, 0x00, 0xFF, 0x8F, 0xF8, 0x3F, 0x7E, 0x07, 0xE0, 0x0E, 0x3E, 0x03,
0xC0, 0x0C, 0x1E, 0x03, 0xE0, 0x0C, 0x1E, 0x01, 0xE0, 0x0C, 0x1E, 0x01,
0xE0, 0x18, 0x0F, 0x00, 0xF0, 0x18, 0x0F, 0x01, 0xF0, 0x10, 0x07, 0x81,
0xF0, 0x30, 0x07, 0x81, 0x78, 0x30, 0x07, 0x83, 0x78, 0x60, 0x03, 0xC3,
0x38, 0x60, 0x03, 0xC6, 0x3C, 0x40, 0x01, 0xC6, 0x3C, 0xC0, 0x01, 0xEC,
0x1E, 0xC0, 0x01, 0xEC, 0x1F, 0x80, 0x00, 0xF8, 0x0F, 0x80, 0x00, 0xF8,
0x0F, 0x00, 0x00, 0x70, 0x0F, 0x00, 0x00, 0x70, 0x07, 0x00, 0x00, 0x60,
0x06, 0x00, 0x00, 0x20, 0x02, 0x00, 0x7F, 0xE7, 0xF0, 0x7E, 0x0F, 0x00,
0xF8, 0x38, 0x01, 0xE0, 0xC0, 0x07, 0xC6, 0x00, 0x0F, 0x30, 0x00, 0x1E,
0xC0, 0x00, 0x7E, 0x00, 0x00, 0xF0, 0x00, 0x01, 0xE0, 0x00, 0x07, 0xC0,
0x00, 0x3F, 0x00, 0x00, 0xDE, 0x00, 0x06, 0x7C, 0x00, 0x30, 0xF0, 0x01,
0xC1, 0xE0, 0x06, 0x07, 0xC0, 0x30, 0x0F, 0x01, 0xC0, 0x1E, 0x0F, 0x00,
0xFC, 0xFE, 0x07, 0xFC, 0xFF, 0xC0, 0xFC, 0xFC, 0x01, 0xE1, 0xE0, 0x03,
0x07, 0x80, 0x18, 0x0F, 0x00, 0x60, 0x3C, 0x01, 0x80, 0x78, 0x0C, 0x01,
0xE0, 0x30, 0x03, 0xC0, 0xC0, 0x0F, 0x06, 0x00, 0x3E, 0x18, 0x00, 0x78,
0x40, 0x01, 0xF3, 0x00, 0x03, 0xCC, 0x00, 0x0F, 0xE0, 0x00, 0x1F, 0x80,
0x00, 0x7C, 0x00, 0x00, 0xF0, 0x00, 0x03, 0xC0, 0x00, 0x06, 0x00, 0x00,
0x18, 0x00, 0x00, 0x40, 0x00, 0x03, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x60,
0x00, 0x01, 0x80, 0x00, 0x0C, 0x00, 0x0F, 0xF0, 0x00, 0x7F, 0x80, 0x01,
0xFC, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x7F, 0xFF, 0x9F, 0xFF, 0xE6, 0x00,
0xF1, 0x00, 0x78, 0x40, 0x3E, 0x00, 0x0F, 0x00, 0x07, 0x80, 0x03, 0xE0,
0x00, 0xF0, 0x00, 0x78, 0x00, 0x3E, 0x00, 0x0F, 0x00, 0x07, 0x80, 0x03,
0xE0, 0x01, 0xF0, 0x04, 0x78, 0x01, 0x3E, 0x00, 0xDF, 0x00, 0x37, 0x80,
0x1F, 0xFF, 0xFE, 0xFF, 0xFF, 0x80, 0x01, 0xE0, 0x78, 0x1C, 0x07, 0x80,
0xE0, 0x1C, 0x03, 0x80, 0x70, 0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0,
0x1C, 0x03, 0x80, 0x70, 0x0E, 0x01, 0xC0, 0x70, 0x1C, 0x0E, 0x00, 0x70,
0x07, 0x00, 0x70, 0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x1C, 0x03,
0x80, 0x70, 0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x1C, 0x01, 0xC0,
0x1E, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0x00, 0x70, 0x0F, 0x00, 0xE0, 0x1C, 0x03,
0x80, 0x70, 0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x1C, 0x03, 0x80,
0x70, 0x0E, 0x01, 0xC0, 0x1C, 0x01, 0xC0, 0x0E, 0x07, 0x01, 0xC0, 0x70,
0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x1C, 0x03, 0x80, 0x70, 0x0E,
0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x3C, 0x07, 0x03, 0xC0, 0xF0, 0x00,
0x1F, 0x80, 0x00, 0xFF, 0x80, 0xC7, 0x0F, 0x87, 0xB8, 0x0F, 0xFC, 0x00,
0x07, 0xC0};
const GFXglyph FreeSerif24pt7bGlyphs[] PROGMEM = {
{0, 0, 0, 12, 0, 1}, // 0x20 ' '
{0, 5, 32, 16, 6, -31}, // 0x21 '!'
{20, 12, 12, 19, 4, -31}, // 0x22 '"'
{38, 23, 31, 23, 0, -30}, // 0x23 '#'
{128, 19, 37, 24, 2, -33}, // 0x24 '$'
{216, 33, 32, 39, 3, -30}, // 0x25 '%'
{348, 32, 33, 37, 2, -31}, // 0x26 '&'
{480, 4, 12, 9, 3, -31}, // 0x27 '''
{486, 12, 40, 16, 2, -31}, // 0x28 '('
{546, 12, 40, 16, 2, -30}, // 0x29 ')'
{606, 16, 19, 24, 4, -30}, // 0x2A '*'
{644, 23, 23, 27, 2, -22}, // 0x2B '+'
{711, 6, 11, 12, 2, -4}, // 0x2C ','
{720, 11, 2, 16, 2, -10}, // 0x2D '-'
{723, 5, 5, 12, 3, -3}, // 0x2E '.'
{727, 14, 32, 14, 0, -30}, // 0x2F '/'
{783, 22, 33, 23, 1, -31}, // 0x30 '0'
{874, 13, 32, 24, 5, -31}, // 0x31 '1'
{926, 21, 31, 23, 1, -30}, // 0x32 '2'
{1008, 18, 32, 23, 2, -30}, // 0x33 '3'
{1080, 21, 31, 24, 1, -30}, // 0x34 '4'
{1162, 19, 33, 24, 2, -31}, // 0x35 '5'
{1241, 21, 33, 23, 2, -31}, // 0x36 '6'
{1328, 20, 31, 24, 1, -30}, // 0x37 '7'
{1406, 18, 33, 23, 3, -31}, // 0x38 '8'
{1481, 21, 33, 24, 1, -31}, // 0x39 '9'
{1568, 5, 22, 12, 4, -20}, // 0x3A ':'
{1582, 6, 27, 12, 3, -20}, // 0x3B ';'
{1603, 24, 25, 27, 1, -24}, // 0x3C '<'
{1678, 24, 11, 27, 1, -16}, // 0x3D '='
{1711, 24, 25, 27, 2, -23}, // 0x3E '>'
{1786, 17, 32, 21, 3, -31}, // 0x3F '?'
{1854, 32, 33, 41, 4, -31}, // 0x40 '@'
{1986, 32, 32, 34, 1, -31}, // 0x41 'A'
{2114, 27, 31, 30, 0, -30}, // 0x42 'B'
{2219, 28, 33, 31, 2, -31}, // 0x43 'C'
{2335, 31, 31, 34, 1, -30}, // 0x44 'D'
{2456, 27, 31, 29, 2, -30}, // 0x45 'E'
{2561, 24, 31, 27, 2, -30}, // 0x46 'F'
{2654, 31, 33, 35, 2, -31}, // 0x47 'G'
{2782, 30, 31, 34, 2, -30}, // 0x48 'H'
{2899, 13, 31, 15, 1, -30}, // 0x49 'I'
{2950, 17, 32, 18, 0, -30}, // 0x4A 'J'
{3018, 32, 31, 33, 1, -30}, // 0x4B 'K'
{3142, 26, 31, 29, 2, -30}, // 0x4C 'L'
{3243, 39, 31, 41, 1, -30}, // 0x4D 'M'
{3395, 32, 32, 34, 1, -30}, // 0x4E 'N'
{3523, 30, 33, 34, 2, -31}, // 0x4F 'O'
{3647, 23, 31, 27, 2, -30}, // 0x50 'P'
{3737, 31, 40, 34, 2, -31}, // 0x51 'Q'
{3892, 28, 31, 31, 2, -30}, // 0x52 'R'
{4001, 21, 33, 25, 2, -31}, // 0x53 'S'
{4088, 27, 31, 28, 1, -30}, // 0x54 'T'
{4193, 32, 32, 34, 1, -30}, // 0x55 'U'
{4321, 32, 32, 33, 0, -30}, // 0x56 'V'
{4449, 44, 32, 45, 0, -30}, // 0x57 'W'
{4625, 33, 31, 34, 0, -30}, // 0x58 'X'
{4753, 32, 31, 33, 0, -30}, // 0x59 'Y'
{4877, 27, 31, 29, 1, -30}, // 0x5A 'Z'
{4982, 9, 38, 16, 4, -30}, // 0x5B '['
{5025, 14, 32, 14, 0, -30}, // 0x5C '\'
{5081, 9, 38, 16, 3, -30}, // 0x5D ']'
{5124, 20, 17, 22, 1, -30}, // 0x5E '^'
{5167, 24, 2, 23, 0, 5}, // 0x5F '_'
{5173, 10, 8, 12, 1, -31}, // 0x60 '`'
{5183, 18, 21, 20, 1, -20}, // 0x61 'a'
{5231, 21, 32, 24, 1, -31}, // 0x62 'b'
{5315, 19, 21, 21, 1, -20}, // 0x63 'c'
{5365, 22, 32, 23, 1, -31}, // 0x64 'd'
{5453, 18, 21, 21, 1, -20}, // 0x65 'e'
{5501, 17, 33, 18, 0, -32}, // 0x66 'f'
{5572, 21, 31, 22, 1, -20}, // 0x67 'g'
{5654, 22, 32, 23, 0, -31}, // 0x68 'h'
{5742, 11, 32, 13, 0, -31}, // 0x69 'i'
{5786, 12, 42, 16, 0, -31}, // 0x6A 'j'
{5849, 23, 32, 24, 1, -31}, // 0x6B 'k'
{5941, 11, 32, 12, 0, -31}, // 0x6C 'l'
{5985, 35, 21, 37, 1, -20}, // 0x6D 'm'
{6077, 22, 21, 23, 0, -20}, // 0x6E 'n'
{6135, 22, 21, 23, 1, -20}, // 0x6F 'o'
{6193, 21, 31, 24, 1, -20}, // 0x70 'p'
{6275, 21, 31, 23, 1, -20}, // 0x71 'q'
{6357, 15, 21, 16, 1, -20}, // 0x72 'r'
{6397, 13, 21, 17, 2, -20}, // 0x73 's'
{6432, 12, 26, 13, 1, -25}, // 0x74 't'
{6471, 22, 21, 23, 1, -20}, // 0x75 'u'
{6529, 22, 22, 22, 0, -20}, // 0x76 'v'
{6590, 32, 22, 32, 0, -20}, // 0x77 'w'
{6678, 22, 21, 23, 0, -20}, // 0x78 'x'
{6736, 22, 31, 22, 0, -20}, // 0x79 'y'
{6822, 18, 21, 20, 1, -20}, // 0x7A 'z'
{6870, 11, 41, 23, 5, -31}, // 0x7B '{'
{6927, 3, 32, 9, 3, -30}, // 0x7C '|'
{6939, 11, 41, 23, 7, -31}, // 0x7D '}'
{6996, 22, 5, 23, 1, -13}}; // 0x7E '~'
const GFXfont FreeSerif24pt7b PROGMEM = {(uint8_t *)FreeSerif24pt7bBitmaps,
(GFXglyph *)FreeSerif24pt7bGlyphs,
0x20, 0x7E, 56};
// Approx. 7682 bytes
| 36,467 |
2,133 | /****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#pragma once
#include <QObject>
#include <QByteArray>
#include <QImage>
#include "QGCLoggingCategory.h"
#include "QGCMAVLink.h"
Q_DECLARE_LOGGING_CATEGORY(ImageProtocolManagerLog)
// Supports the Mavlink image transmission protocol (https://mavlink.io/en/services/image_transmission.html).
// Mainly used by optical flow cameras.
class ImageProtocolManager : public QObject
{
Q_OBJECT
public:
ImageProtocolManager(void);
void mavlinkMessageReceived (const mavlink_message_t& message);
QImage getImage (void);
signals:
void imageReady(void);
private:
mavlink_data_transmission_handshake_t _imageHandshake;
QByteArray _imageBytes;
};
| 369 |
3,457 | /*
Copyright (c) 2005-2020 Intel Corporation
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.
*/
#define TBB_PREVIEW_FLOW_GRAPH_NODES 1
#define TBB_PREVIEW_FLOW_GRAPH_FEATURES 1
#include "tbb/tbb_config.h"
#if __TBB_PREVIEW_STREAMING_NODE
#if _MSC_VER
#pragma warning (disable: 4503) // Suppress "decorated name length exceeded, name was truncated" warning
#pragma warning (disable: 4702) // Suppress "unreachable code" warning
#endif
#include <functional>
#include <iostream>
#include "harness.h"
#include "harness_assert.h"
#include "tbb/concurrent_queue.h"
#include "tbb/flow_graph.h"
#include "tbb/tbb_thread.h"
using namespace tbb::flow;
//--------------------------------------------------------------------------------
//--------------------------------TEST HELPERS------------------------------------
//--------------------------------------------------------------------------------
template <typename ...A>
struct tuples_equal : std::false_type { };
template <typename ...A>
struct tuples_equal<std::tuple<A...>, std::tuple<>> : std::false_type { };
template <typename ...B>
struct tuples_equal<std::tuple<>, std::tuple<B...>> : std::false_type { };
template <>
struct tuples_equal<std::tuple<>, std::tuple<>> : std::true_type { };
template <typename A1, typename ...Aother, typename B1, typename ...Bother>
struct tuples_equal<std::tuple<A1, Aother...>, std::tuple<B1, Bother...>>
{
static const bool value = std::is_same<A1, B1>::value && tuples_equal<std::tuple<Aother...>, std::tuple<Bother...>>::value;
};
template<typename...A>
struct first_variadic {
template<typename...B>
static void is_equal_to_second()
{
ASSERT((tuples_equal< std::tuple<A...>, std::tuple<B...> >::value), "Unexpected variadic types");
}
};
//--------------------------------------------------------------------------------
template<typename T>
class factory_msg : public async_msg<T> {
public:
factory_msg() {}
factory_msg(const T& input_data) : m_data(input_data) {}
const T& data() const { return m_data; }
void update_data(T value) { m_data = value; }
private:
T m_data;
};
//--------------------------------------------------------------------------------
class base_streaming_factory : NoCopy {
public:
typedef int device_type;
typedef int kernel_type;
template<typename T> using async_msg_type = factory_msg<T>;
base_streaming_factory() : devices_list(1) {}
std::vector<device_type> devices() {
return devices_list;
}
template <typename ...Args>
void send_result_forward(Args&... args) {
deviceResult = doDeviceWork();
send_result(args...);
}
void clear_factory() {
arguments_list.clear();
}
void process_arg_list() {}
template <typename T, typename ...Rest>
void process_arg_list(T& arg, Rest&... args) {
process_one_arg(arg);
process_arg_list(args...);
}
private:
int doDeviceWork() {
int result = 0;
for (size_t i = 0; i < arguments_list.size(); i++)
result += arguments_list[i];
return result;
}
// Pass calculation result to the next node
template <typename ...Args>
void set_result(Args...) {}
template <typename T>
void set_result(async_msg_type<T>& msg) {
msg.set(deviceResult);
}
// Variadic functions for result processing
// and sending them to all async_msgs
void send_result() {}
template <typename T, typename ...Rest>
void send_result(T& arg, Rest&... args) {
set_result(arg);
send_result(args...);
}
// Retrieve values from async_msg objects
// and store them in vector
template <typename T>
void process_one_arg(async_msg_type<T>& msg) {
arguments_list.push_back(msg.data());
}
template <typename T>
void process_one_arg(const async_msg_type<T>& msg) {
arguments_list.push_back(msg.data());
}
std::vector<device_type> devices_list;
std::vector<int> arguments_list;
int deviceResult;
};
template<typename ...ExpectedArgs>
class test_streaming_factory : public base_streaming_factory {
public:
template <typename ...Args>
void send_data(device_type /*device*/, Args&... /*args*/) {}
template <typename ...Args>
void send_kernel(device_type /*device*/, const kernel_type& /*kernel*/, Args&... args) {
check_arguments(args...);
process_arg_list(args...);
send_result_forward(args...);
clear_factory();
}
template <typename FinalizeFn, typename ...Args>
void finalize(device_type /*device*/, FinalizeFn fn, Args&... args) {
check_arguments(args...);
fn();
}
template<typename ...Args>
void check_arguments(Args&... /*args*/) {
first_variadic< Args... >::template is_equal_to_second< ExpectedArgs... >();
}
};
//--------------------------------------------------------------------------------
template<typename Factory>
class device_selector {
public:
device_selector() : my_state(DEFAULT_INITIALIZED) {}
device_selector(const device_selector&) : my_state(COPY_INITIALIZED) {}
device_selector(device_selector&&) : my_state(COPY_INITIALIZED) {}
~device_selector() { my_state = DELETED; }
typename Factory::device_type operator()(Factory &f) {
ASSERT(my_state == COPY_INITIALIZED, NULL);
ASSERT(!f.devices().empty(), NULL);
return *(f.devices().begin());
}
private:
enum state {
DEFAULT_INITIALIZED,
COPY_INITIALIZED,
DELETED
};
state my_state;
};
//--------------------------------------------------------------------------------
void TestWithoutSetArgs() {
graph g;
typedef test_streaming_factory< factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
// test finalize function
split_n.try_put(args_tuple);
g.wait_for_all();
make_edge(output_port<0>(streaming_n), function_n);
expected_result = 30;
split_n.try_put(args_tuple);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSetArgsOnly() {
graph g;
typedef test_streaming_factory< const factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
streaming_n.set_args(100);
split_n.try_put(args_tuple);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSetPortRefOnly() {
graph g;
typedef test_streaming_factory< factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
streaming_n.set_args(port_ref<0, 1>());
// test finalize function
split_n.try_put(args_tuple);
g.wait_for_all();
make_edge(output_port<0>(streaming_n), function_n);
expected_result = 30;
split_n.try_put(args_tuple);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSetArgsAndPortRef1() {
graph g;
typedef test_streaming_factory< const factory_msg<int>, factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
streaming_n.set_args(100, port_ref<0, 1>());
// test finalize function
split_n.try_put(args_tuple);
g.wait_for_all();
make_edge(output_port<0>(streaming_n), function_n);
expected_result = 130;
split_n.try_put(args_tuple);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSetArgsAndPortRef2() {
graph g;
typedef test_streaming_factory< const factory_msg<int>, factory_msg<int>,
const factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
streaming_n.set_args(100, port_ref<0>(), 200, port_ref<1>());
// test finalize function
split_n.try_put(args_tuple);
g.wait_for_all();
make_edge(output_port<0>(streaming_n), function_n);
expected_result = 330;
split_n.try_put(args_tuple);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
template <typename ...ExpectedArgs>
class send_data_factory : public base_streaming_factory {
public:
send_data_factory() : send_data_counter(0) {}
template <typename ...Args>
void send_data(device_type /*device*/, Args&... /*args*/) {
switch (send_data_counter) {
case 0:
first_variadic< Args... >::template is_equal_to_second< ExpectedArgs... >();
break;
case 1:
first_variadic< Args... >::template is_equal_to_second< factory_msg<int> >();
break;
case 2:
first_variadic< Args... >::template is_equal_to_second< factory_msg<int> >();
break;
default:
break;
}
send_data_counter++;
}
template <typename ...Args>
void send_kernel(device_type /*device*/, const kernel_type& /*kernel*/, Args&... /*args*/) {
ASSERT(send_data_counter == 3, "send_data() was called not enough times");
send_data_counter = 0;
}
template <typename FinalizeFn, typename ...Args>
void finalize(device_type /*device*/, FinalizeFn fn, Args&... /*args*/) {
fn();
}
private:
int send_data_counter;
};
void TestSendData_withoutSetArgs() {
graph g;
typedef send_data_factory< tbb::flow::interface11::internal::port_ref_impl<0, 1> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
input_port<0>(streaming_n).try_put(10);
input_port<1>(streaming_n).try_put(20);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSendData_setArgsOnly() {
graph g;
typedef send_data_factory< factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
streaming_n.set_args(100);
input_port<0>(streaming_n).try_put(10);
input_port<1>(streaming_n).try_put(20);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSendData_portRefOnly() {
graph g;
typedef send_data_factory< tbb::flow::interface11::internal::port_ref_impl<0,1> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
streaming_n.set_args(port_ref<0,1>());
input_port<0>(streaming_n).try_put(10);
input_port<1>(streaming_n).try_put(20);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSendData_setArgsAndPortRef1() {
graph g;
typedef send_data_factory< factory_msg<int>, tbb::flow::interface11::internal::port_ref_impl<0, 1> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
streaming_n.set_args(100, port_ref<0,1>());
input_port<0>(streaming_n).try_put(10);
input_port<1>(streaming_n).try_put(20);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestSendData_setArgsAndPortRef2() {
graph g;
typedef send_data_factory< factory_msg<int>, tbb::flow::interface11::internal::port_ref_impl<0,0>,
factory_msg<int>, tbb::flow::interface11::internal::port_ref_impl<1,1> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
streaming_n.set_args(100, port_ref<0>(), 200, port_ref<1>());
input_port<0>(streaming_n).try_put(10);
input_port<1>(streaming_n).try_put(20);
g.wait_for_all();
}
//--------------------------------------------------------------------------------
void TestArgumentsPassing() {
REMARK("TestArgumentsPassing: ");
TestWithoutSetArgs();
TestSetArgsOnly();
TestSetPortRefOnly();
TestSetArgsAndPortRef1();
TestSetArgsAndPortRef2();
TestSendData_withoutSetArgs();
TestSendData_setArgsOnly();
TestSendData_portRefOnly();
TestSendData_setArgsAndPortRef1();
TestSendData_setArgsAndPortRef2();
REMARK("done\n");
}
//--------------------------------------------------------------------------------
template<typename... ExpectedArgs>
class range_streaming_factory : public base_streaming_factory {
public:
typedef std::array<int, 2> range_type;
template <typename ...Args>
void send_data(device_type /*device*/, Args&... /*args*/) {
}
template <typename ...Args>
void send_kernel(device_type /*device*/, const kernel_type& /*kernel*/, const range_type& work_size, Args&... args) {
ASSERT(work_size[0] == 1024, "Range was set incorrectly");
ASSERT(work_size[1] == 720, "Range was set incorrectly");
first_variadic< Args... >::template is_equal_to_second< ExpectedArgs... >();
process_arg_list(args...);
send_result_forward(args...);
clear_factory();
}
template <typename FinalizeFn, typename ...Args>
void finalize(device_type /*device*/, FinalizeFn fn, Args&... /*args*/) {
first_variadic< Args... >::template is_equal_to_second< ExpectedArgs... >();
fn();
}
};
void TestSetRange() {
REMARK("TestSetRange: ");
graph g;
typedef range_streaming_factory< const factory_msg<int>, factory_msg<int>,
const factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
make_edge(output_port<0>(split_n), input_port<0>(streaming_n));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n));
const int first_arg = 10;
const int second_arg = 20;
std::tuple<int, int> args_tuple = std::make_tuple(first_arg, second_arg);
streaming_n.set_args(100, port_ref<0>(), 200, port_ref<1>());
// test version for GCC <= 4.7.2 (unsupported conversion from initializer_list to std::array)
#if __GNUC__ < 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ <= 7 || (__GNUC_MINOR__ == 7 && __GNUC_PATCHLEVEL__ <= 2)))
std::array<int, 2> device_range;
device_range[0] = 1024;
device_range[1] = 720;
streaming_n.set_range(device_range);
#else
std::array<int, 2> device_range = { 1024,720 };
streaming_n.set_range(device_range);
#endif
split_n.try_put(args_tuple);
g.wait_for_all();
make_edge(output_port<0>(streaming_n), function_n);
expected_result = 330;
split_n.try_put(args_tuple);
g.wait_for_all();
REMARK("done\n");
}
//-------------------------------------------------------------------------------------------------------------------------------------------
template <typename T>
class user_async_msg : public tbb::flow::async_msg<T>
{
public:
user_async_msg() {}
user_async_msg(T value) : m_data(value) {}
void finalize() const __TBB_override;
private:
T m_data;
};
class user_async_activity { // Async activity singleton
public:
static user_async_activity* instance() {
if (s_Activity == NULL) {
s_Activity = new user_async_activity();
}
return s_Activity;
}
static void destroy() {
ASSERT(s_Activity != NULL, "destroyed twice");
s_Activity->myThread.join();
delete s_Activity;
s_Activity = NULL;
}
template <typename FinalizeFn>
static void finish(FinalizeFn fn) {
ASSERT(user_async_activity::s_Activity != NULL, "activity must be alive");
user_async_activity::s_Activity->finishTaskQueue(fn);
}
static void finish(const user_async_msg<int>& msg) {
ASSERT(user_async_activity::s_Activity != NULL, "activity must be alive");
user_async_activity::s_Activity->finishTaskQueue(msg);
}
static int getResult() {
ASSERT(user_async_activity::s_Activity != NULL, "activity must be alive");
return user_async_activity::s_Activity->myQueueSum;
}
void addWork(int addValue, int timeout = 0) {
myQueue.push(my_task(addValue, timeout));
}
template <typename FinalizeFn>
void finishTaskQueue(FinalizeFn fn) {
myFinalizer = fn;
myQueue.push(my_task(0, 0, true));
}
void finishTaskQueue(const user_async_msg<int>& msg) {
myMsg = msg;
myQueue.push(my_task(0, 0, true));
}
private:
struct my_task {
my_task(int addValue = 0, int timeout = 0, bool finishFlag = false)
: myAddValue(addValue), myTimeout(timeout), myFinishFlag(finishFlag) {}
int myAddValue;
int myTimeout;
bool myFinishFlag;
};
static void threadFunc(user_async_activity* activity) {
for (;;) {
my_task work;
activity->myQueue.pop(work);
Harness::Sleep(work.myTimeout);
if (work.myFinishFlag) {
break;
}
activity->myQueueSum += work.myAddValue;
}
// Send result back to the graph
if (activity->myFinalizer) {
activity->myFinalizer();
}
activity->myMsg.set(activity->myQueueSum);
}
user_async_activity() : myQueueSum(0), myThread(&user_async_activity::threadFunc, this) {}
tbb::concurrent_bounded_queue<my_task> myQueue;
int myQueueSum;
user_async_msg<int> myMsg;
std::function<void(void)> myFinalizer;
tbb::tbb_thread myThread;
static user_async_activity* s_Activity;
};
user_async_activity* user_async_activity::s_Activity = NULL;
template <typename T>
void user_async_msg<T>::finalize() const {
user_async_activity::finish(*this);
}
class data_streaming_factory {
public:
typedef int device_type;
typedef int kernel_type;
template<typename T> using async_msg_type = user_async_msg<T>;
data_streaming_factory() : devices_list(1) {}
template <typename ...Args>
void send_data(device_type /*device*/, Args&... /*args*/) {}
template <typename ...Args>
void send_kernel(device_type /*device*/, const kernel_type& /*kernel*/, Args&... args) {
process_arg_list(args...);
}
template <typename FinalizeFn, typename ...Args>
void finalize(device_type /*device*/, FinalizeFn fn, Args&... /*args*/) {
user_async_activity::finish(fn);
}
// Retrieve values from async_msg objects
// and store them in vector
void process_arg_list() {}
template <typename T, typename ...Rest>
void process_arg_list(T& arg, Rest&... args) {
process_one_arg(arg);
process_arg_list(args...);
}
template <typename T>
void process_one_arg(async_msg_type<T>& /*msg*/) {
user_async_activity::instance()->addWork(1, 10);
}
template <typename ...Args>
void process_one_arg(Args&... /*args*/) {}
std::vector<device_type> devices() {
return devices_list;
}
private:
std::vector<device_type> devices_list;
};
void TestChaining() {
REMARK("TestChaining: ");
graph g;
typedef streaming_node< tuple<int>, queueing, data_streaming_factory > streaming_node_type;
typedef std::vector< streaming_node_type > nodes_vector_type;
data_streaming_factory factory;
device_selector<data_streaming_factory> device_selector;
data_streaming_factory::kernel_type kernel(0);
const int STREAMING_GRAPH_CHAIN_LENGTH = 1000;
nodes_vector_type nodes_vector;
for (int i = 0; i < STREAMING_GRAPH_CHAIN_LENGTH; i++) {
nodes_vector.emplace_back(g, kernel, device_selector, factory);
}
function_node< int, int > source_n(g, unlimited, [](const int& value) -> int {
return value;
});
function_node< int > destination_n(g, unlimited, [&](const int& result) {
ASSERT(result == STREAMING_GRAPH_CHAIN_LENGTH, "calculation chain result is wrong");
});
make_edge(source_n, input_port<0>(nodes_vector.front()));
for (size_t i = 0; i < nodes_vector.size() - 1; i++) {
make_edge(output_port<0>(nodes_vector[i]), input_port<0>(nodes_vector[i + 1]));
nodes_vector[i].set_args(port_ref<0>());
}
nodes_vector.back().set_args(port_ref<0>());
make_edge(output_port<0>(nodes_vector.back()), destination_n);
source_n.try_put(0);
g.wait_for_all();
REMARK("result = %d; expected = %d\n", user_async_activity::getResult(), STREAMING_GRAPH_CHAIN_LENGTH);
ASSERT(user_async_activity::getResult() == STREAMING_GRAPH_CHAIN_LENGTH, "calculation chain result is wrong");
user_async_activity::destroy();
REMARK("done\n");
}
//--------------------------------------------------------------------------------
void TestCopyConstructor() {
REMARK("TestCopyConstructor: ");
graph g;
typedef test_streaming_factory< factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
// Testing copy constructor
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n_copied(streaming_n);
make_edge(output_port<0>(split_n), input_port<0>(streaming_n_copied));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n_copied));
make_edge(output_port<0>(streaming_n_copied), function_n);
std::tuple<int, int> args_tuple = std::make_tuple(10, 20);
expected_result = 30;
split_n.try_put(args_tuple);
g.wait_for_all();
REMARK("done\n");
}
void TestMoveConstructor() {
REMARK("TestMoveConstructor: ");
graph g;
typedef test_streaming_factory< factory_msg<int>, factory_msg<int> > device_factory;
device_factory factory;
device_selector<device_factory> device_selector;
device_factory::kernel_type kernel(0);
int expected_result;
split_node < tuple<int, int> > split_n(g);
function_node< int > function_n(g, unlimited, [&expected_result](const int& result) {
ASSERT(expected_result == result, "Validation has failed");
});
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n(g, kernel, device_selector, factory);
// Testing move constructor
streaming_node< tuple<int, int>, queueing, device_factory > streaming_n_moved(std::move(streaming_n));
make_edge(output_port<0>(split_n), input_port<0>(streaming_n_moved));
make_edge(output_port<1>(split_n), input_port<1>(streaming_n_moved));
make_edge(output_port<0>(streaming_n_moved), function_n);
std::tuple<int, int> args_tuple = std::make_tuple(10, 20);
expected_result = 30;
split_n.try_put(args_tuple);
g.wait_for_all();
REMARK("done\n");
}
void TestConstructor() {
TestCopyConstructor();
TestMoveConstructor();
}
//--------------------------------------------------------------------------------
int TestMain() {
TestArgumentsPassing();
TestSetRange();
TestChaining();
TestConstructor();
return Harness::Done;
}
#else
#define HARNESS_SKIP_TEST 1
#include "harness.h"
#endif
| 10,945 |
458 | /**
* Copyright 2019 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hyscale.deployer.services.client;
import io.hyscale.commons.constants.K8SRuntimeConstants;
import io.hyscale.commons.exception.HyscaleException;
import io.hyscale.commons.utils.HyscaleStringUtil;
import io.hyscale.deployer.core.model.CustomResourceKind;
import io.hyscale.deployer.services.model.CustomListObject;
import io.hyscale.deployer.services.model.CustomObject;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.generic.GenericKubernetesApi;
import java.util.List;
public abstract class GenericK8sClient {
private ApiClient apiClient;
protected String namespace;
protected GenericKubernetesApi<CustomObject, CustomListObject> genericClient;
protected GenericK8sClient(ApiClient apiClient) {
this.apiClient = apiClient;
this.namespace = K8SRuntimeConstants.DEFAULT_NAMESPACE;
}
public GenericK8sClient withNamespace(String namespace) {
this.namespace = namespace;
return this;
}
public GenericK8sClient forKind(CustomResourceKind resourceKind) {
String apiVersion = resourceKind.getApiVersion();
this.genericClient = new GenericKubernetesApi<>(
CustomObject.class, CustomListObject.class, getApiGroup(apiVersion),
getApiVersion(apiVersion), HyscaleStringUtil.getPlural(resourceKind.getKind().toLowerCase()), apiClient);
return this;
}
public abstract void create(CustomObject resource) throws HyscaleException;
public abstract void update(CustomObject resource) throws HyscaleException;
public abstract boolean patch(CustomObject resource) throws HyscaleException;
public abstract boolean delete(CustomObject resource);
public abstract CustomObject get(CustomObject resource);
public abstract CustomObject getResourceByName(String name);
public abstract List<CustomObject> getAll();
public abstract List<CustomObject> getBySelector(String selector);
private String getApiGroup(String apiVersion) {
if (apiVersion == null || apiVersion.equalsIgnoreCase("")) {
return apiVersion;
}
String[] groups = apiVersion.split("/");
return groups.length == 2 ? groups[0] : "";
}
private static String getApiVersion(String apiVersion) {
if (apiVersion == null || apiVersion.equalsIgnoreCase("")) {
return apiVersion;
}
String[] groups = apiVersion.split("/");
return groups.length == 2 ? groups[1] : groups[0];
}
}
| 1,036 |
314 | <filename>Multiplex/IDEHeaders/IDEHeaders/IDEKit/DVTTileViewDelegate-Protocol.h<gh_stars>100-1000
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@class DVTTileView, NSEvent, NSString;
@protocol DVTTileViewDelegate <NSObject>
- (void)tileView:(DVTTileView *)arg1 didChangeContextClickedObjectFrom:(id)arg2;
- (NSString *)tileView:(DVTTileView *)arg1 typeCompletionStringForContentObject:(id)arg2;
@optional
- (void)userDidPressEscapeInTileView:(DVTTileView *)arg1;
- (void)userDidPressSpaceBarInTileView:(DVTTileView *)arg1;
- (void)tileView:(DVTTileView *)arg1 didProcessKeyEvent:(NSEvent *)arg2;
- (void)tileView:(DVTTileView *)arg1 willProcessKeyEvent:(NSEvent *)arg2;
- (void (^)(NSEvent *, BOOL))tileView:(DVTTileView *)arg1 willProcessClick:(NSEvent *)arg2;
- (NSString *)tileView:(DVTTileView *)arg1 titleForContentObject:(id)arg2;
@end
| 366 |
2,023 | import os
import sys
__author__ = '<NAME> <<EMAIL>>'
__source__ = 'http://code.activestate.com/recipes/577281-xnview-backup-files-remove-utility/'
root_dn = sys.argv[1]
delete_files = list()
for root, dirs, files in os.walk(root_dn):
for f in files:
ii = f.split('.')
if len(ii) > 2:
prev_part = ii[-2].lower()
last_part = ii[-1].lower()
if last_part in ['jpg', 'jpeg'] and prev_part == 'xnbak':
ii.pop(-2)
rotated_name = '.'.join(ii)
rotated_path = os.path.join(root, rotated_name)
if os.path.isfile(rotated_path):
f_path = os.path.join(root, f)
# delete bak file
delete_files.append(f_path)
for f_path in delete_files:
try:
print f_path
os.unlink(f_path)
except OSError:
print >>sys.stderr, 'ERROR DELETE: %s' % f_path
| 501 |
935 | <filename>spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/stream/ResourceUtilsTests.java
/*
* Copyright 2018 the original author or authors.
*
* 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
*
* https://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.
*/
package org.springframework.cloud.dataflow.server.stream;
import java.net.MalformedURLException;
import org.junit.Test;
import org.springframework.cloud.dataflow.registry.support.AppResourceCommon;
import org.springframework.cloud.deployer.resource.docker.DockerResource;
import org.springframework.cloud.deployer.resource.maven.MavenProperties;
import org.springframework.cloud.deployer.resource.maven.MavenResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public class ResourceUtilsTests {
private AppResourceCommon appResourceService = new AppResourceCommon(new MavenProperties(), null);
@Test
public void testMavenResourceProcessing() {
MavenResource mavenResource = new MavenResource.Builder()
.artifactId("timestamp-task")
.groupId("org.springframework.cloud.task.app")
.version("1.0.0.RELEASE")
.build();
String resourceWithoutVersion = appResourceService.getResourceWithoutVersion(mavenResource);
assertThat(resourceWithoutVersion).isEqualTo("maven://org.springframework.cloud.task.app:timestamp-task:jar");
assertThat(appResourceService.getResourceVersion(mavenResource)).isEqualTo("1.0.0.RELEASE");
}
@Test
public void testDockerResourceProcessing() {
DockerResource dockerResource = new DockerResource("springcloudstream/file-source-kafka-10:1.2.0.RELEASE");
assertThat(appResourceService.getResourceWithoutVersion(dockerResource)).isEqualTo("docker:springcloudstream/file-source-kafka-10");
assertThat(appResourceService.getResourceVersion(dockerResource)).isEqualTo("1.2.0.RELEASE");
}
@Test
public void testDockerResourceProcessingWithHostIP() {
DockerResource dockerResource = new DockerResource("192.168.99.100:80/myrepo/rabbitsink:current");
assertThat(appResourceService.getResourceWithoutVersion(dockerResource)).isEqualTo("docker:192.168.99.100:80/myrepo/rabbitsink");
assertThat(appResourceService.getResourceVersion(dockerResource)).isEqualTo("current");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidDockerResourceProcessing() {
DockerResource dockerResource = new DockerResource("springcloudstream:file-source-kafka-10:1.2.0.RELEASE");
appResourceService.getResourceWithoutVersion(dockerResource);
}
@Test
public void testFileResourceProcessing() throws MalformedURLException {
Resource resource = new UrlResource("file:/springcloudstream/file-source-kafka-10-1.2.0.RELEASE.jar");
assertThat(appResourceService.getResourceWithoutVersion(resource)).isEqualTo("file:/springcloudstream/file-source-kafka-10");
assertThat(appResourceService.getResourceVersion(resource)).isEqualTo("1.2.0.RELEASE");
resource = new UrlResource("file:/springcloudstream/file-source-kafka-10-1.2.0.BUILD-SNAPSHOT.jar");
assertThat(appResourceService.getResourceWithoutVersion(resource)).isEqualTo("file:/springcloudstream/file-source-kafka-10");
assertThat(appResourceService.getResourceVersion(resource)).isEqualTo("1.2.0.BUILD-SNAPSHOT");
resource = new UrlResource("https://springcloudstream/file-source-kafka-10-1.2.0.RELEASE.jar");
assertThat(appResourceService.getResourceWithoutVersion(resource)).isEqualTo("https://springcloudstream/file-source-kafka-10");
assertThat(appResourceService.getResourceVersion(resource)).isEqualTo("1.2.0.RELEASE");
}
@Test(expected = IllegalArgumentException.class)
public void testFileResourceWithoutVersion() throws MalformedURLException {
Resource resource = new UrlResource("https://springcloudstream/filesourcekafkacrap.jar");
assertThat(appResourceService.getResourceWithoutVersion(resource)).isEqualTo("https://springcloudstream/filesourcekafkacrap.jar");
}
}
| 1,407 |
2,105 | import os
import shutil
fileDir = os.path.dirname(os.path.abspath(__file__))
backendDir = os.path.dirname(fileDir)
publishDir = os.path.join(os.path.dirname(backendDir), "publish")
def copy_backend_to_publish(src, dst):
for item in os.listdir(src):
source = os.path.join(src, item)
destination = os.path.join(dst, item)
if os.path.isdir(source) and item != "scripts":
shutil.copytree(source, destination)
elif os.path.isfile(source):
shutil.copyfile(source, destination)
def clean_publish():
for item in os.listdir(publishDir):
source = os.path.join(publishDir, item)
if os.path.isdir(source) and item != "build":
shutil.rmtree(source)
elif os.path.isfile(source):
os.remove(source)
clean_publish()
copy_backend_to_publish(backendDir, publishDir)
| 384 |
5,169 | <filename>Specs/b/1/c/PayUIndia-OlaMoney/1.0.0/PayUIndia-OlaMoney.podspec.json
{
"name": "PayUIndia-OlaMoney",
"version": "1.0.0",
"license": "MIT",
"homepage": "https://github.com/payu-intrepos/payu-olamoney-ios",
"authors": {
"PayUbiz": "<EMAIL>"
},
"summary": "A lightweight SDK which supports payments via OlaMoney (Postpaid + Wallet)",
"description": "A lightweight SDK which supports payments via OlaMoney (Postpaid + Wallet)",
"source": {
"git": "https://github.com/payu-intrepos/payu-olamoney-ios.git",
"tag": "PayUIndia-OlaMoney_1.0.0"
},
"platforms": {
"ios": "10.0"
},
"vendored_frameworks": "Framework/PayUOlaMoneySDK.framework",
"dependencies": {
"PayUIndia-Logger": [
"1.0.1"
],
"PayUIndia-Networking": [
"1.0.1"
]
}
}
| 353 |
1,073 | <reponame>oubotong/Armariris<filename>tools/clang/test/SemaTemplate/nested-name-spec-template.cpp
// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
namespace N {
namespace M {
template<typename T> struct Promote;
template<> struct Promote<short> {
typedef int type;
};
template<> struct Promote<int> {
typedef int type;
};
template<> struct Promote<float> {
typedef double type;
};
Promote<short>::type *ret_intptr(int* ip) { return ip; }
Promote<int>::type *ret_intptr2(int* ip) { return ip; }
}
M::Promote<int>::type *ret_intptr3(int* ip) { return ip; }
M::template Promote<int>::type *ret_intptr4(int* ip) { return ip; }
#if __cplusplus <= 199711L
// expected-warning@-2 {{'template' keyword outside of a template}}
#endif
M::template Promote<int> pi;
#if __cplusplus <= 199711L
// expected-warning@-2 {{'template' keyword outside of a template}}
#endif
}
N::M::Promote<int>::type *ret_intptr5(int* ip) { return ip; }
::N::M::Promote<int>::type *ret_intptr6(int* ip) { return ip; }
N::M::template; // expected-error{{expected unqualified-id}}
N::M::template Promote; // expected-error{{expected unqualified-id}}
namespace N {
template<typename T> struct A;
template<>
struct A<int> {
struct X;
};
struct B;
}
struct ::N::A<int>::X {
int foo;
};
template<typename T>
struct TestA {
typedef typename N::template B<T>::type type; // expected-error{{'B' following the 'template' keyword does not refer to a template}} \
// expected-error{{expected member name}}
};
// Reduced from a Boost failure.
namespace test1 {
template <class T> struct pair {
T x;
T y;
static T pair<T>::* const mem_array[2];
};
template <class T>
T pair<T>::* const pair<T>::mem_array[2] = { &pair<T>::x, &pair<T>::y };
}
typedef int T;
namespace N1 {
template<typename T> T f0();
}
template<typename T> T N1::f0() { }
namespace PR7385 {
template< typename > struct has_xxx0
{
template< typename > struct has_xxx0_introspect
{
template< typename > struct has_xxx0_substitute ;
template< typename V >
int int00( has_xxx0_substitute < typename V::template xxx< > > = 0 );
};
static const int value = has_xxx0_introspect<int>::value; // expected-error{{no member named 'value'}}
typedef int type;
};
has_xxx0<int>::type t; // expected-note{{instantiation of}}
}
namespace PR7725 {
template<class ignored> struct TypedefProvider;
template<typename T>
struct TemplateClass : public TypedefProvider<T>
{
void PrintSelf() {
TemplateClass::Test::PrintSelf();
}
};
}
namespace PR9226 {
template<typename a>
void nt() // expected-note{{function template 'nt' declared here}}
{ nt<>:: } // expected-error{{qualified name refers into a specialization of function template 'nt'}} \
// expected-error{{expected unqualified-id}}
template<typename T>
void f(T*); // expected-note{{function template 'f' declared here}}
template<typename T>
void f(T*, T*); // expected-note{{function template 'f' declared here}}
void g() {
f<int>:: // expected-error{{qualified name refers into a specialization of function template 'f'}}
} // expected-error{{expected unqualified-id}}
struct X {
template<typename T> void f(); // expected-note{{function template 'f' declared here}}
};
template<typename T, typename U>
struct Y {
typedef typename T::template f<U> type; // expected-error{{template name refers to non-type template 'X::f'}}
};
Y<X, int> yxi; // expected-note{{in instantiation of template class 'PR9226::Y<PR9226::X, int>' requested here}}
}
namespace PR9449 {
template <typename T>
struct s; // expected-note{{template is declared here}}
template <typename T>
void f() {
int s<T>::template n<T>::* f; // expected-error{{implicit instantiation of undefined template 'PR9449::s<int>'}} \
// expected-error{{following the 'template' keyword}}
}
template void f<int>(); // expected-note{{in instantiation of}}
}
| 1,595 |
1,144 | package de.metas.procurement.base.rfq.model.interceptor;
import de.metas.common.procurement.sync.protocol.dto.SyncRfQCloseEvent;
import de.metas.procurement.base.IPMM_RfQ_BL;
import de.metas.procurement.base.IPMM_RfQ_DAO;
import de.metas.procurement.base.IWebuiPush;
import de.metas.procurement.base.impl.SyncObjectsFactory;
import de.metas.procurement.base.rfq.model.I_C_RfQ;
import de.metas.procurement.base.rfq.model.I_C_RfQResponseLine;
import de.metas.rfq.event.RfQEventListenerAdapter;
import de.metas.rfq.model.I_C_RfQResponse;
import de.metas.util.Services;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.ad.trx.api.ITrxListenerManager.TrxEventTiming;
import org.adempiere.ad.trx.api.ITrxManager;
import org.adempiere.exceptions.FillMandatoryException;
import org.adempiere.model.InterfaceWrapperHelper;
import java.util.ArrayList;
import java.util.List;
/*
* #%L
* de.metas.procurement.base
* %%
* Copyright (C) 2016 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public final class PMMRfQEventListener extends RfQEventListenerAdapter
{
public static final transient PMMRfQEventListener instance = new PMMRfQEventListener();
private PMMRfQEventListener()
{
super();
}
private final boolean isProcurement(final de.metas.rfq.model.I_C_RfQ rfq)
{
return Services.get(IPMM_RfQ_BL.class).isProcurement(rfq);
}
private final boolean isProcurement(final de.metas.rfq.model.I_C_RfQResponse rfqResponse)
{
return Services.get(IPMM_RfQ_BL.class).isProcurement(rfqResponse);
}
@Override
public void onBeforeComplete(final de.metas.rfq.model.I_C_RfQ rfq)
{
if (!isProcurement(rfq))
{
return;
}
final I_C_RfQ pmmRfq = InterfaceWrapperHelper.create(rfq, I_C_RfQ.class);
validatePMM_RfQ(pmmRfq);
}
private void validatePMM_RfQ(final I_C_RfQ pmmRfq)
{
//
// Make sure mandatory fields are filled
final List<String> notFilledMandatoryColumns = new ArrayList<>();
if (pmmRfq.getC_Flatrate_Conditions_ID() <= 0)
{
notFilledMandatoryColumns.add(I_C_RfQ.COLUMNNAME_C_Flatrate_Conditions_ID);
}
if (pmmRfq.getDateWorkStart() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateWorkStart);
}
if (pmmRfq.getDateWorkComplete() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateWorkComplete);
}
if (pmmRfq.getDateResponse() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateResponse);
}
//
if (!notFilledMandatoryColumns.isEmpty())
{
throw new FillMandatoryException(false, notFilledMandatoryColumns);
}
}
@Override
public void onAfterComplete(I_C_RfQResponse rfqResponse)
{
if (!isProcurement(rfqResponse))
{
return;
}
//
// Create and collect RfQ close events (winner unknown)
final List<SyncRfQCloseEvent> syncRfQCloseEvents = new ArrayList<>();
final SyncObjectsFactory syncObjectsFactory = SyncObjectsFactory.newFactory();
final IPMM_RfQ_DAO pmmRfqDAO = Services.get(IPMM_RfQ_DAO.class);
for (final I_C_RfQResponseLine rfqResponseLine : pmmRfqDAO.retrieveResponseLines(rfqResponse))
{
// Create and collect the RfQ close event
final boolean winnerKnown = false;
final SyncRfQCloseEvent syncRfQCloseEvent = syncObjectsFactory.createSyncRfQCloseEvent(rfqResponseLine, winnerKnown);
if (syncRfQCloseEvent != null)
{
syncRfQCloseEvents.add(syncRfQCloseEvent);
}
}
//
// Push to WebUI: RfQ close events
if (!syncRfQCloseEvents.isEmpty())
{
Services.get(ITrxManager.class)
.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited)
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerWeakly(false) // register "hard", because that's how it was before
.invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed
.registerHandlingMethod(innerTrx -> {
final IWebuiPush webuiPush = Services.get(IWebuiPush.class);
webuiPush.pushRfQCloseEvents(syncRfQCloseEvents);
});
}
};
@Override
public void onAfterClose(final I_C_RfQResponse rfqResponse)
{
if (!isProcurement(rfqResponse))
{
return;
}
Services.get(IPMM_RfQ_BL.class).createDraftContractsForSelectedWinners(rfqResponse);
}
}
| 1,944 |
630 | /*
* Copyright 2015 LinkedIn Corp.
*
* 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.
*/
package com.linkedin.featurefu.expr;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingFormatArgumentException;
/**
*
* Unit test for math expression parsing, evaluating and printing
*
* Author: <NAME> <http://www.linkedin.com/in/lijuntang>
*/
public class ExprTest {
@Test
public void simple() {
Assert.assertTrue(Expression.evaluate("(!= 2 3)") == 1);
Assert.assertTrue(Expression.evaluate("(* 2 3)") == 6);
Assert.assertTrue(Expression.evaluate("(ln1plus 2)") == Math.log(1 + 2));
Assert.assertTrue(Expression.evaluate("(if (>= 4 5) 1 2)") == 2);
Assert.assertTrue(Expression.evaluate("(if (in 3 4 5) 2 1)") == 1);
Assert.assertTrue(Expression.evaluate("(- 1)") == -1);
Assert.assertTrue(Expression.evaluate("(cos 1)") == Math.cos(1));
double r = Expression.evaluate("(rand-in 5 10)");
Assert.assertTrue(r >= 5 && r <= 10);
r = Expression.evaluate("(rand)");
Assert.assertTrue(r >= 0 && r <= 1);
Assert.assertTrue(Expression.evaluate("(+ 0.5 (* (/ 15 1000) (ln (- 55 12))))") == 0.5 + 15.0 / 1000.0 * Math.log(55.0 - 12.0));
//big boss, time to show power
Assert.assertTrue(Expression.evaluate("(* (if (&& (== 0 12) (&& 3 (&& (&& (>= 4 5) (<= 4 6)) (&& (>= 7 5 ) (<= 7 4))))) 0 (if (&& (== 3 0) (<= 55 3)) 0 (if (&& (== 3 0) (|| (|| (&& 2 (&& 3 1) ) 1) (&& 6 3))) 0 (if (<= 55 12) (/ (* 0.5 55) 12)(+ 0.5 (*(/ 15 1000) (ln (- 55 12)))))))) 1000)") == 1000 * (0.5 + 15.0 / 1000.0 * Math.log(55.0 - 12.0)));
}
@Test
public void variables(){
VariableRegistry variableRegistry=new VariableRegistry();
//parse expression with variables, use variableRegistry to register variables
Expr expression = Expression.parse("(sigmoid (+ (* a x) b))", variableRegistry);
//retrieve variables from variableRegistry by name
Variable x = variableRegistry.findVariable("x");
Variable a = variableRegistry.findVariable("a");
Variable b = variableRegistry.findVariable("b");
//set variable values
x.setValue(1);
a.setValue(2);
b.setValue(3);
//evaluate expression with variables' value
Assert.assertTrue(expression.evaluate() == 1.0/(1+Math.exp(-a.getValue() * x.getValue() - b.getValue() )) );
//re-set variable values
x.setValue(4);
Assert.assertTrue(x.getValue()==4);
a.setValue(5);
Assert.assertTrue(a.getValue() == 5);
b.setValue(6);
Assert.assertTrue(b.getValue() == 6);
//re-eval expression without re-parsing
Assert.assertTrue(expression.evaluate() == 1.0/(1+Math.exp(-a.getValue() * x.getValue() - b.getValue() )) );
//another way to re-set variable values, using a <name,value> map
Map<String,Double> varMap = new HashMap<String,Double>();
varMap.put("x",0.2);
varMap.put("a",0.6);
varMap.put("b",0.8);
//call refresh to re-set values all at once
variableRegistry.refresh(varMap);
Assert.assertTrue(x.getValue()==0.2);
Assert.assertTrue(a.getValue()==0.6);
Assert.assertTrue(b.getValue()==0.8);
//re-evaluate expression
Assert.assertTrue(expression.evaluate() == 1.0 / (1 + Math.exp(-a.getValue() * x.getValue() - b.getValue())));
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void operatorNotSupported() {
Expression.evaluate("(atan 1)"); //some triangle functions are not supported due to no foreseeable use cases
}
@Test(expectedExceptions = MissingFormatArgumentException.class)
public void operantNotSupported() {
Expression.evaluate("(+ 1+1)");
}
@Test
public void testPrettyPrint(){
VariableRegistry variableRegistry=new VariableRegistry();
Expr expr = Expression.parse("(+ 0.5 (* (/ 15 1000) (ln (- 55 12))))", variableRegistry);
Assert.assertEquals(expr.toString(), "(0.5+((15.0/1000.0)*ln((55.0-12.0))))");
Assert.assertEquals(Expression.prettyTree(expr), "└── +\n" +
" ├── 0.5\n" +
" └── *\n" +
" ├── /\n" +
" | ├── 15.0\n" +
" | └── 1000.0\n" +
" └── ln\n" +
" └── -\n" +
" ├── 55.0\n" +
" └── 12.0\n");
}
}
| 2,576 |
560 | /*
* Copyright (c) 2016 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.followship.ui;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.zhanghai.android.douya.R;
import me.zhanghai.android.douya.util.FragmentUtils;
import me.zhanghai.android.douya.util.TransitionUtils;
public abstract class FollowshipListActivityFragment extends Fragment {
private static final String KEY_PREFIX = FollowshipListActivityFragment.class.getName() + '.';
private static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid";
@BindView(R.id.toolbar)
Toolbar mToolbar;
private String mUserIdOrUid;
protected FollowshipListActivityFragment setArguments(String userIdOrUid) {
FragmentUtils.getArgumentsBuilder(this)
.putString(EXTRA_USER_ID_OR_UID, userIdOrUid);
return this;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
mUserIdOrUid = arguments.getString(EXTRA_USER_ID_OR_UID);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.followship_list_activity_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(mToolbar);
TransitionUtils.setupTransitionOnActivityCreated(this);
if (savedInstanceState == null) {
FragmentUtils.add(onCreateListFragment(), this,
R.id.followship_list_fragment);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected String getUserIdOrUid() {
return mUserIdOrUid;
}
abstract protected FollowshipUserListFragment onCreateListFragment();
}
| 1,138 |
1,041 | <reponame>GiannisMP/ebean<filename>ebean-core/src/main/java/io/ebeaninternal/server/querydefn/OrmQuerySecondary.java<gh_stars>1000+
package io.ebeaninternal.server.querydefn;
import io.ebeaninternal.api.SpiQuerySecondary;
import java.util.List;
/**
* The secondary query paths for 'query joins' and 'lazy loading'.
*/
final class OrmQuerySecondary implements SpiQuerySecondary {
private final List<OrmQueryProperties> queryJoins;
private final List<OrmQueryProperties> lazyJoins;
/**
* Construct with the 'query join' and 'lazy join' path properties.
*/
OrmQuerySecondary(List<OrmQueryProperties> queryJoins, List<OrmQueryProperties> lazyJoins) {
this.queryJoins = queryJoins;
this.lazyJoins = lazyJoins;
}
/**
* Return a list of path/properties that are query join loaded.
*/
@Override
public List<OrmQueryProperties> getQueryJoins() {
return queryJoins;
}
/**
* Return the list of path/properties that are lazy loaded.
*/
@Override
public List<OrmQueryProperties> getLazyJoins() {
return lazyJoins;
}
}
| 370 |
936 | //
// DSFancyLoaderView.h
// Design Shots
//
// Created by <NAME> on 19/12/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RJCircularLoaderView : UIView
- (void)reveal;
@property (nonatomic) CGFloat progress;
@end
| 104 |
5,156 | <gh_stars>1000+
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include "util.h"
static char ch = 'E';
static long saved_sp;
static ssize_t my_write(int fd, void* buf, size_t size) {
ssize_t ret;
/* Do a write syscall with no valid stack. */
#ifdef __x86_64__
asm("mov %%rsp,%5\n\t"
"xor %%rsp,%%rsp\n\t"
"syscall\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t"
"mov %5,%%rsp\n\t"
: "=a"(ret)
: "a"(SYS_write), "D"(fd), "S"(buf), "d"(size), "m"(saved_sp));
#elif __i386__
asm("mov %%esp,%5\n\t"
"xor %%esp,%%esp\n\t"
"int $0x80\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t"
"mov %5,%%esp\n\t"
: "=a"(ret)
: "a"(SYS_write), "b"(fd), "c"(buf), "d"(size), "m"(saved_sp));
#elif __aarch64__
register long x8 __asm__("x8") = SYS_write;
register long x0 __asm__("x0") = (long)fd;
register long x1 __asm__("x1") = (long)buf;
register long x2 __asm__("x2") = (long)size;
register long x6 __asm__("x6") = 0;
asm("mov x6, sp\n\t"
"str x6,%1\n\t"
"eor x6,x6,x6\n\t"
"mov sp,x6\n\t"
"svc #0\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t"
"ldr x6,%1\n\t"
"mov sp,x6\n\t"
: "+r"(x0), "+m"(saved_sp), "+r"(x6) :
"r"(x1), "r"(x2), "r"(x8));
ret = x0;
#else
#error Unknown architecture
#endif
return ret;
}
int main(void) {
test_assert(1 == my_write(STDOUT_FILENO, &ch, 1));
atomic_puts("EXIT-SUCCESS");
return 0;
}
| 863 |
758 | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.fenzo;
import java.util.List;
import java.util.Set;
/**
* Result of resource assignments for a host (VM). When you call your task scheduler's
* {@link TaskScheduler#scheduleOnce(java.util.List,java.util.List) scheduleOnce()} method to schedule a set of
* tasks, that method returns a {@link SchedulingResult}. That object includes the method
* {@link SchedulingResult#getResultMap() getResultMap()} which returns a map of host names to
* {@code VMAssignmentResult} objects. Those objects in turn have the {@link #getLeasesUsed()} and
* {@link #getTasksAssigned()} methods, which return information about the resource offers that participated in
* the assignments and which tasks were assigned on those hosts, in the form of {@link VirtualMachineLease}
* objects and {@link TaskAssignmentResult} objects respectively. This approach will give you insight into which
* tasks have been assigned to which hosts in the current scheduling round (but not about which tasks are
* already running on those hosts).
*/
public class VMAssignmentResult {
private final String hostname;
private final List<VirtualMachineLease> leasesUsed;
private final Set<TaskAssignmentResult> tasksAssigned;
public VMAssignmentResult(String hostname, List<VirtualMachineLease> leasesUsed, Set<TaskAssignmentResult> tasksAssigned) {
this.hostname = hostname;
this.leasesUsed = leasesUsed;
this.tasksAssigned = tasksAssigned;
}
/**
* Get the name of the host whose assignment results are available.
*
* @return the name of the host
*/
public String getHostname() {
return hostname;
}
/**
* Get the list of leases (resource offers) used in creating the resource assignments for tasks.
*
* @return a List of leases
*/
public List<VirtualMachineLease> getLeasesUsed() {
return leasesUsed;
}
/**
* Get the set of tasks that are assigned resources from this host.
*
* @return a Set of task assignment results
*/
public Set<TaskAssignmentResult> getTasksAssigned() {
return tasksAssigned;
}
@Override
public String toString() {
return "VMAssignmentResult{" +
"hostname='" + hostname + '\'' +
", leasesUsed=" + leasesUsed +
", tasksAssigned=" + tasksAssigned +
'}';
}
}
| 953 |
2,151 | <filename>components/download/downloader/in_progress/in_progress_cache_impl.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/download/downloader/in_progress/in_progress_cache_impl.h"
#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/important_file_writer.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/download/downloader/in_progress/in_progress_conversions.h"
namespace download {
const base::FilePath::CharType kDownloadMetadataStoreFilename[] =
FILE_PATH_LITERAL("in_progress_download_metadata_store");
namespace {
// Helper functions for |entries_| related operations.
int GetIndexFromEntries(const metadata_pb::DownloadEntries& entries,
const std::string& guid) {
int size_of_entries = entries.entries_size();
for (int i = 0; i < size_of_entries; i++) {
if (entries.entries(i).guid() == guid)
return i;
}
return -1;
}
void AddOrReplaceEntryInEntries(metadata_pb::DownloadEntries& entries,
const DownloadEntry& entry) {
metadata_pb::DownloadEntry metadata_entry =
InProgressConversions::DownloadEntryToProto(entry);
int entry_index = GetIndexFromEntries(entries, metadata_entry.guid());
metadata_pb::DownloadEntry* entry_ptr =
(entry_index < 0) ? entries.add_entries()
: entries.mutable_entries(entry_index);
*entry_ptr = metadata_entry;
}
base::Optional<DownloadEntry> GetEntryFromEntries(
const metadata_pb::DownloadEntries& entries,
const std::string& guid) {
int entry_index = GetIndexFromEntries(entries, guid);
if (entry_index < 0)
return base::nullopt;
return InProgressConversions::DownloadEntryFromProto(
entries.entries(entry_index));
}
void RemoveEntryFromEntries(metadata_pb::DownloadEntries& entries,
const std::string& guid) {
int entry_index = GetIndexFromEntries(entries, guid);
if (entry_index >= 0)
entries.mutable_entries()->DeleteSubrange(entry_index, 1);
}
// Helper functions for file read/write operations.
std::vector<char> ReadEntriesFromFile(base::FilePath file_path) {
if (file_path.empty())
return std::vector<char>();
// Check validity of file.
base::File entries_file(file_path,
base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!entries_file.IsValid()) {
// The file just doesn't exist yet (potentially because no entries have been
// written yet) so we can't read from it.
return std::vector<char>();
}
// Get file info.
base::File::Info info;
if (!entries_file.GetInfo(&info)) {
LOG(ERROR) << "Could not read download entries from file "
<< "because get info failed.";
return std::vector<char>();
}
if (info.is_directory) {
LOG(ERROR) << "Could not read download entries from file "
<< "because file is a directory.";
return std::vector<char>();
}
// Read and parse file.
if (info.size < 0) {
LOG(ERROR) << "Could not read download entries from file "
<< "because the file size was unexpected.";
return std::vector<char>();
}
auto file_data = std::vector<char>(info.size);
if (entries_file.Read(0, file_data.data(), info.size) < 0) {
LOG(ERROR) << "Could not read download entries from file "
<< "because there was a read failure.";
return std::vector<char>();
}
return file_data;
}
std::string EntriesToString(const metadata_pb::DownloadEntries& entries) {
std::string entries_string;
if (!entries.SerializeToString(&entries_string)) {
// TODO(crbug.com/778425): Have more robust error-handling for serialization
// error.
LOG(ERROR) << "Could not write download entries to file "
<< "because of a serialization issue.";
return std::string();
}
return entries_string;
}
void WriteEntriesToFile(const std::string& entries, base::FilePath file_path) {
if (file_path.empty())
return;
if (!base::ImportantFileWriter::WriteFileAtomically(file_path, entries)) {
LOG(ERROR) << "Could not write download entries to file: "
<< file_path.value();
}
}
} // namespace
InProgressCacheImpl::InProgressCacheImpl(
const base::FilePath& cache_file_path,
const scoped_refptr<base::SequencedTaskRunner>& task_runner)
: file_path_(cache_file_path),
initialization_status_(CACHE_UNINITIALIZED),
task_runner_(task_runner),
weak_ptr_factory_(this) {}
InProgressCacheImpl::~InProgressCacheImpl() = default;
void InProgressCacheImpl::Initialize(base::OnceClosure callback) {
// If it's already initialized, just run the callback.
if (initialization_status_ == CACHE_INITIALIZED) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
std::move(callback));
return;
}
// If uninitialized, initialize |entries_| by reading from file.
if (initialization_status_ == CACHE_UNINITIALIZED) {
base::PostTaskAndReplyWithResult(
task_runner_.get(), FROM_HERE,
base::BindOnce(&ReadEntriesFromFile, file_path_),
base::BindOnce(&InProgressCacheImpl::OnInitialized,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
}
void InProgressCacheImpl::OnInitialized(base::OnceClosure callback,
const std::vector<char>& entries) {
if (!entries.empty()) {
if (!entries_.ParseFromArray(entries.data(), entries.size())) {
// TODO(crbug.com/778425): Get UMA for errors.
LOG(ERROR) << "Could not read download entries from file "
<< "because there was a parse failure.";
return;
}
}
initialization_status_ = CACHE_INITIALIZED;
std::move(callback).Run();
}
void InProgressCacheImpl::AddOrReplaceEntry(const DownloadEntry& entry) {
if (initialization_status_ != CACHE_INITIALIZED) {
LOG(ERROR) << "Cache is not initialized, cannot AddOrReplaceEntry.";
return;
}
// Update |entries_|.
AddOrReplaceEntryInEntries(entries_, entry);
// Serialize |entries_| and write to file.
std::string entries_string = EntriesToString(entries_);
task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteEntriesToFile,
entries_string, file_path_));
}
base::Optional<DownloadEntry> InProgressCacheImpl::RetrieveEntry(
const std::string& guid) {
if (initialization_status_ != CACHE_INITIALIZED) {
LOG(ERROR) << "Cache is not initialized, cannot RetrieveEntry.";
return base::nullopt;
}
return GetEntryFromEntries(entries_, guid);
}
void InProgressCacheImpl::RemoveEntry(const std::string& guid) {
if (initialization_status_ != CACHE_INITIALIZED) {
LOG(ERROR) << "Cache is not initialized, cannot RemoveEntry.";
return;
}
// Update |entries_|.
RemoveEntryFromEntries(entries_, guid);
// Serialize |entries_| and write to file.
std::string entries_string = EntriesToString(entries_);
task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteEntriesToFile,
entries_string, file_path_));
}
} // namespace download
| 2,811 |
1,461 | <filename>dubbokeeper-ui/src/main/java/com/dubboclub/dk/web/utils/ContextUtils.java
package com.dubboclub.dk.web.utils;
import org.springframework.context.ApplicationContext;
import java.util.Collection;
/**
* Created by bieber on 2015/6/1.
*/
public class ContextUtils {
private static ApplicationContext APPLICATION_CONTEXT;
public static void setContext(ApplicationContext context){
if(APPLICATION_CONTEXT==null){
APPLICATION_CONTEXT = context;
}
}
public static<T extends Object> T getBean(Class<T> type){
checkApplicationContext();
return APPLICATION_CONTEXT.getBean(type);
}
public static<T extends Object> T getBean(String beanId){
checkApplicationContext();
return (T) APPLICATION_CONTEXT.getBean(beanId);
}
public static<T extends Object> Collection<T> getBeans(Class<T> type){
checkApplicationContext();
return APPLICATION_CONTEXT.getBeansOfType(type).values();
}
private static void checkApplicationContext(){
if(APPLICATION_CONTEXT==null){
throw new IllegalAccessError("must set ApplicatonContext first!");
}
}
}
| 443 |
407 | #!/usr/bin/env python
# encoding: utf-8
""" """
from teslafaas.container.webpy.common.BaseHandler import BaseHandler
from teslafaas.container.webpy.common.BaseHandler import PomHandler
from teslafaas.container.webpy.common.decorators import fcached,ActionError,app_route
import time
import web
from ..models.mysql_test_model import MysqlTestModel
@app_route(r'/base/(.*)')
class TestBaseHandler(PomHandler):
def test(self, params):
# 自定义request_id,跟其他系统级联
self.set_ret_request_id(4444)
# 记录日志和获得当前请求用户邮箱前缀和工号
self.logger.info("record some body %s %s request" % (self.user_name, self.user_empid))
return params
def echo(self, params):
self.logger.info("params=%s, body=%s" % (params, web.data()))
return "echo"
def test_argument(self, params):
## 请求中不带 aaa 会自动抛出标准的 400 错误
self.get_argument('aaa')
def test_error(self, params):
# 返回给前端自定义错误code的信息
raise ActionError("yee", code=333)
def test_mysql(self, params):
return MysqlTestModel().get_db_time()
def test_tesla_sdk(self, params):
## Tesla 通道服务实例,更多SDK使用参考https://yuque.antfin-inc.com/bdsre/userguid
channel = self.factory.get_channel_wrapper()
resp = channel.run_command('echo 123', ip=[self.TEST_IP, ])
# 检查结果是否执行成功
if not resp.is_success():
print '--- channel error: ', resp.message, resp.code, resp.data
data = resp.message
else:
data = resp.data
def test_set_dynamic_code_and_dynamic_message(self, params):
self.set_dynamic_message("dynamic message")
self.set_dynamic_code('200 dynamic code')
return "success"
def test_set_dynamic_code_and_dynamic_message2(self, params):
return "success"
def test_specified_factory(self, params):
# 自定义工厂会被自动初始化
self.factory.hello_factory.say()
class DemoHandler(TestBaseHandler):
pass
| 1,008 |
778 | <gh_stars>100-1000
package org.aion.zero.impl.blockchain;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import java.math.BigInteger;
import org.aion.zero.impl.core.IRewardsCalculator;
import org.aion.zero.impl.types.MiningBlockHeader;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ChainConfigurationTest {
@Mock
MiningBlockHeader header;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
@Ignore // To be re-enabled later
@Test
public void testValidation() {
int n = 210;
int k = 9;
byte[] nonce = {
1, 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
};
// setup mock
// MiningBlockHeader.Builder builder = MiningBlockHeader.Builder.newInstance();
// builder.withDifficulty(BigInteger.valueOf(1).toByteArray());
// builder.withNonce(nonce);
// builder.withTimestamp(12345678910L);
// MiningBlockHeader header = builder.build();
//
// // Static header bytes (portion of header which does not change per equihash
// iteration)
// byte [] staticHeaderBytes = header.getStaticHash();
//
// // Dynamic header bytes
// long timestamp = header.getTimestamp();
//
// // Dynamic header bytes (portion of header which changes each iteration0
// byte[] dynamicHeaderBytes = ByteUtil.longToBytes(timestamp);
//
// BigInteger target = header.getPowBoundaryBI();
//
// //Merge H(static) and dynamic portions into a single byte array
// byte[] inputBytes = new byte[staticHeaderBytes.length +
// dynamicHeaderBytes.length];
// System.arraycopy(staticHeaderBytes, 0, inputBytes, 0 , staticHeaderBytes.length);
// System.arraycopy(dynamicHeaderBytes, 0, inputBytes, staticHeaderBytes.length,
// dynamicHeaderBytes.length);
//
// Equihash equihash = new Equihash(n, k);
//
// int[][] solutions;
//
// // Generate 3 solutions
// solutions = equihash.getSolutionsForNonce(inputBytes, header.getNonce());
//
// // compress solution
// byte[] compressedSolution = EquiUtils.getMinimalFromIndices(solutions[0],
// n/(k+1));
// header.setSolution(compressedSolution);
//
// ChainConfiguration chainConfig = new ChainConfiguration();
// BlockHeaderValidator<MiningBlockHeader> blockHeaderValidator =
// chainConfig.createBlockHeaderValidator();
// blockHeaderValidator.validate(header, log);
}
// assuming 100000 block ramp
@Test
public void testRampUpFunctionBoundaries() {
long upperBound = 259200L;
ChainConfiguration config = new ChainConfiguration();
BigInteger increment =
config.getConstants()
.getBlockReward()
.subtract(config.getConstants().getRampUpStartValue())
.divide(BigInteger.valueOf(upperBound))
.add(config.getConstants().getRampUpStartValue());
// UPPER BOUND
when(header.getNumber()).thenReturn(upperBound);
BigInteger blockReward259200 =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
when(header.getNumber()).thenReturn(upperBound + 1);
BigInteger blockReward259201 =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
// check that at the upper bound of our range (which is not included) blockReward is capped
assertThat(blockReward259200).isEqualTo(new BigInteger("1497989283243258292"));
// check that for the block after, the block reward is still the same
assertThat(blockReward259201).isEqualTo(config.getConstants().getBlockReward());
// check that for an arbitrarily large block, the block reward is still the same
when(header.getNumber()).thenReturn(upperBound + 100000);
BigInteger blockUpper =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
assertThat(blockUpper).isEqualTo(config.getConstants().getBlockReward());
// LOWER BOUNDS
when(header.getNumber()).thenReturn(0l);
BigInteger blockReward0 =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
assertThat(blockReward0).isEqualTo(new BigInteger("748994641621655092"));
// first block (should have gas value of increment)
when(header.getNumber()).thenReturn(1l);
BigInteger blockReward1 =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
assertThat(blockReward1).isEqualTo(increment);
}
@Test
public void testCalculatorReturnsByFork() {
long upperBound = 259200L;
ChainConfiguration config = new ChainConfiguration();
BigInteger increment =
config.getConstants()
.getBlockReward()
.subtract(config.getConstants().getRampUpStartValue())
.divide(BigInteger.valueOf(upperBound))
.add(config.getConstants().getRampUpStartValue());
// UPPER BOUND
when(header.getNumber()).thenReturn(upperBound);
BigInteger blockReward259200 =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(false)
.calculateReward(header.getNumber());
// check that at the upper bound of our range (which is not included) blockReward is capped
assertThat(blockReward259200).isEqualTo(new BigInteger("1497989283243258292"));
BigInteger blockRewardAfterUnityFork =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(true)
.calculateReward(header.getNumber());
assertThat(blockRewardAfterUnityFork).isEqualTo(IRewardsCalculator.fixedRewardsAfterUnity);
BigInteger blockRewardAfterUnityForkPlusOne =
config
.getRewardsCalculatorBeforeSignatureSchemeSwap(true)
.calculateReward(header.getNumber() + 1);
assertThat(blockRewardAfterUnityForkPlusOne).isEqualTo(IRewardsCalculator.fixedRewardsAfterUnity);
BigInteger StakingBlockRewardAfterSignatureSchemeSwapActive =
config.getRewardsCalculatorAfterSignatureSchemeSwap(false).calculateReward(header.getNumber());
assertThat(StakingBlockRewardAfterSignatureSchemeSwapActive).isEqualTo(IRewardsCalculator.fixedRewardsAfterUnity);
BigInteger MiningBlockRewardAfterSignatureSchemeSwapActive =
config.getRewardsCalculatorAfterSignatureSchemeSwap(false).calculateReward(10);
assertThat(MiningBlockRewardAfterSignatureSchemeSwapActive).isEqualTo(IRewardsCalculator.fixedRewardsAfterUnity);
}
}
| 3,271 |
582 | <reponame>eduardobbs/archi<filename>com.archimatetool.editor/src/com/archimatetool/editor/p2/DropinsPluginHandler.java
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.p2;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchListener;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
import com.archimatetool.editor.ArchiPlugin;
import com.archimatetool.editor.Logger;
import com.archimatetool.editor.utils.FileUtils;
import com.archimatetool.editor.utils.PlatformUtils;
import com.archimatetool.editor.utils.ZipUtils;
/**
* @author <NAME>
*/
public class DropinsPluginHandler {
private Shell shell;
/**
* There are 3 possible locations for a dropins folder:
* 1. The user location set in Archi.ini
* 2. The "dropins" folder at the same level as the configuration location
* 3. The "dropins" folder in the app installation location
*
* (2) and (3) might be the same location if osgi.configuration.area is not set in Archi.ini
* Or, in Archi.ini default settings (1) and (2) happen to be the same location
*/
private File userDropinsFolder, installationDropinsFolder, configurationDropinsFolder;
private boolean success;
static final int CONTINUE = 0;
static final int RESTART = 1;
/**
* The name of the magic file that denotes that the *.archiplugin or *.zip archive is an Archi plug-in
* It can also include meta information such as listing plug-ins to delete
*/
static final String MAGIC_ENTRY = "archi-plugin"; //$NON-NLS-1$
/**
* Setting in Archi.ini for user dropins folder
* -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=%user.home%/subfolder/dropins
*/
static final String DROPINS_DIRECTORY = "org.eclipse.equinox.p2.reconciler.dropins.directory"; //$NON-NLS-1$
public DropinsPluginHandler() {
}
/**
* @return All user installed plug-ins in any of the three "dropins" locations
*/
public List<Bundle> getInstalledPlugins() throws IOException {
List<Bundle> list = new ArrayList<Bundle>();
for(Bundle bundle : ArchiPlugin.INSTANCE.getBundle().getBundleContext().getBundles()) {
File file = getDropinsBundleFile(bundle);
if(file != null) {
list.add(bundle);
}
}
return list;
}
/**
* Install plug-ins
*/
public int install(Shell shell) throws IOException {
this.shell = shell;
// Check we have write access
if(!checkCanWriteToFolder(getUserInstallationDropinsFolder())) {
return status();
}
List<File> files = askOpenFiles();
if(files.isEmpty()) {
return status();
}
List<IStatus> stats = new ArrayList<IStatus>();
Exception[] exception = new Exception[1];
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
@Override
public void run() {
for(File file : files) {
try {
IStatus status = installFile(file);
stats.add(status);
}
catch(IOException ex) {
exception[0] = ex;
}
}
}
});
if(exception[0] != null) {
displayErrorDialog(exception[0].getMessage());
return status();
}
String resultMessage = ""; //$NON-NLS-1$
boolean hasError = false;
for(int i = 0; i < stats.size(); i++) {
IStatus status = stats.get(i);
if(status.isOK()) {
success = true;
resultMessage += NLS.bind(Messages.DropinsPluginHandler_2 + "\n", files.get(i).getName()); //$NON-NLS-1$
}
else {
hasError = true;
if(status.getCode() == 666) {
resultMessage += NLS.bind(Messages.DropinsPluginHandler_3 + "\n", files.get(i).getName()); //$NON-NLS-1$
}
else {
resultMessage += NLS.bind(Messages.DropinsPluginHandler_4 + "\n", files.get(i).getName()); //$NON-NLS-1$
}
}
}
if(hasError) {
MessageDialog.openInformation(shell, Messages.DropinsPluginHandler_5, resultMessage);
}
return status();
}
private IStatus installFile(File zipFile) throws IOException {
if(!isPluginZipFile(zipFile)) {
return new Status(IStatus.ERROR, "com.archimatetool.editor", 666, //$NON-NLS-1$
NLS.bind(Messages.DropinsPluginHandler_6, zipFile.getAbsolutePath()), null);
}
Path tmp = Files.createTempDirectory("archi"); //$NON-NLS-1$
File tmpFolder = tmp.toFile();
try {
ZipUtils.unpackZip(zipFile, tmpFolder);
File pluginsFolder = getUserInstallationDropinsFolder();
pluginsFolder.mkdirs();
for(File file : tmpFolder.listFiles()) {
// Handle the magic file
if(MAGIC_ENTRY.equalsIgnoreCase(file.getName())) {
handleMagicFile(file, pluginsFolder);
continue;
}
// Delete old plugin on exit in target plugins folder
deleteOlderPluginOnExit(file, pluginsFolder);
// Copy new ones
if(file.isDirectory()) {
FileUtils.copyFolder(file, new File(pluginsFolder, file.getName()));
}
else {
FileUtils.copyFile(file, new File(pluginsFolder, file.getName()), false);
}
}
}
finally {
FileUtils.deleteFolder(tmpFolder);
}
return new Status(IStatus.OK, "com.archimatetool.editor", 777, NLS.bind(Messages.DropinsPluginHandler_0, zipFile.getPath()), null); //$NON-NLS-1$
}
public int uninstall(Shell shell, List<Bundle> selected) throws IOException {
if(selected.isEmpty()) {
return status();
}
boolean ok = MessageDialog.openQuestion(shell,
Messages.DropinsPluginHandler_7,
Messages.DropinsPluginHandler_8);
if(!ok) {
return status();
}
for(Bundle bundle : selected) {
File file = getDropinsBundleFile(bundle);
if(file != null) {
addFileToDeleteOnExit(file);
}
else {
Logger.logError(NLS.bind(Messages.DropinsPluginHandler_1, bundle.getLocation()));
}
}
success = true;
return status();
}
private int status() {
if(success) {
return RESTART;
}
return CONTINUE;
}
/**
* Handle anything in the Magic file
*/
private void handleMagicFile(File magicFile, File pluginsFolder) throws IOException {
for(String line : Files.readAllLines(magicFile.toPath())) {
// A plug-in to delete
if(line.startsWith("delete:")) { //$NON-NLS-1$
String pluginName = line.substring(7).strip();
for(File pluginFile : pluginsFolder.listFiles()) {
String targetPluginName = getPluginName(pluginFile.getName());
if(targetPluginName.equals(pluginName)) {
addFileToDeleteOnExit(pluginFile);
}
}
}
}
}
/**
* Delete matching older plugin on app exit
*/
private void deleteOlderPluginOnExit(File newPlugin, File pluginsFolder) {
for(File file : findMatchingPlugins(pluginsFolder, newPlugin)) {
addFileToDeleteOnExit(file);
}
}
private File[] findMatchingPlugins(File pluginsFolder, File newPlugin) {
String pluginName = getPluginName(newPlugin.getName());
return pluginsFolder.listFiles((file) -> {
String targetPluginName = getPluginName(file.getName());
return targetPluginName.equals(pluginName) && !newPlugin.getName().equals(file.getName());
});
}
String getPluginName(String string) {
int index = string.indexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
return string;
}
String getPluginVersion(String string) {
int index = string.lastIndexOf(".jar"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
index = string.lastIndexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(index + 1);
}
return string;
}
private boolean checkCanWriteToFolder(File folder) {
folder.mkdirs();
if(!Files.isWritable(folder.toPath())) {
String message = Messages.DropinsPluginHandler_9 + " "; //$NON-NLS-1$
if(PlatformUtils.isWindows()) {
message += Messages.DropinsPluginHandler_10;
}
else {
message += Messages.DropinsPluginHandler_11;
}
displayErrorDialog(message);
return false;
}
return true;
}
boolean isPluginZipFile(File file) throws IOException {
return ZipUtils.isZipFile(file) && ZipUtils.hasZipEntry(file, MAGIC_ENTRY);
}
/**
* @return The dropins folder to use to install a new plug-in
*/
private File getUserInstallationDropinsFolder() throws IOException {
// Get user dropins folder as set in Archi.ini
File dropinsFolder = getUserDropinsFolder();
// If not set, use the "dropins" folder at the same level as the configuration locaton
// This is more likely to have write access than getInstallLocationDropinsFolder()
if(dropinsFolder == null) {
dropinsFolder = getConfigurationLocationDropinsFolder();
}
return dropinsFolder;
}
/**
* @return location of user dropins folder as set in Archi.ini
*/
private File getUserDropinsFolder() {
if(userDropinsFolder == null) {
// If the dropins dir is set in Archi.ini
String dropinsDirProperty = ArchiPlugin.INSTANCE.getBundle().getBundleContext().getProperty(DROPINS_DIRECTORY);
if(dropinsDirProperty != null) {
// Perform a variable substitution if necessary of %% tokens
dropinsDirProperty = substituteVariables(dropinsDirProperty);
userDropinsFolder = new File(dropinsDirProperty);
}
}
return userDropinsFolder;
}
/**
* @return The "dropins" folder at the same level as the configuration location
*/
private File getConfigurationLocationDropinsFolder() throws IOException {
if(configurationDropinsFolder == null) {
URL url = Platform.getConfigurationLocation().getURL();
url = FileLocator.resolve(url);
File parentFolder = new File(url.getPath()).getParentFile();
configurationDropinsFolder = new File(parentFolder, "dropins"); //$NON-NLS-1$
}
return configurationDropinsFolder;
}
/**
* @return The "dropins" folder in the app's installation location
*/
private File getInstallLocationDropinsFolder() throws IOException {
if(installationDropinsFolder == null) {
URL url = Platform.getInstallLocation().getURL();
url = FileLocator.resolve(url);
installationDropinsFolder = new File(url.getPath(), "dropins"); //$NON-NLS-1$
}
return installationDropinsFolder;
}
/**
* This is taken From org.eclipse.equinox.internal.p2.reconciler.dropins.Activator
* When the dropins folder contains %% tokens, treat this as a system property.
* Example - %user.home%
*/
private String substituteVariables(String path) {
if(path == null) {
return path;
}
int beginIndex = path.indexOf('%');
// no variable
if(beginIndex == -1) {
return path;
}
beginIndex++;
int endIndex = path.indexOf('%', beginIndex);
// no matching end % to indicate variable
if(endIndex == -1) {
return path;
}
// get the variable name and do a lookup
String var = path.substring(beginIndex, endIndex);
if(var.length() == 0 || var.indexOf(File.pathSeparatorChar) != -1) {
return path;
}
var = ArchiPlugin.INSTANCE.getBundle().getBundleContext().getProperty(var);
if(var == null) {
return path;
}
return path.substring(0, beginIndex - 1) + var + path.substring(endIndex + 1);
}
/**
* If the bundle is in one of the "dropins" folders return its file (jar or folder), else return null
*/
File getDropinsBundleFile(Bundle bundle) throws IOException {
File bundleFile = FileLocator.getBundleFile(bundle);
File parentFolder = bundleFile.getParentFile();
return (parentFolder.equals(getUserDropinsFolder())
|| parentFolder.equals(getConfigurationLocationDropinsFolder())
|| parentFolder.equals(getInstallLocationDropinsFolder())) ? bundleFile : null;
}
private List<File> askOpenFiles() {
FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
dialog.setFilterExtensions(new String[] { "*.archiplugin", "*.zip", "*.*" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String path = dialog.open();
List<File> files = new ArrayList<File>();
if(path != null) {
// Issue on OpenJDK if path is like C: or D: - no slash is added when creating File
String filterPath = dialog.getFilterPath() + File.separator;;
for(String name : dialog.getFileNames()) {
File file = new File(filterPath, name);
if(file.exists()) {
files.add(file);
}
}
}
return files;
}
private void displayErrorDialog(String message) {
MessageDialog.openError(shell,
Messages.DropinsPluginHandler_12,
message);
}
/*
* Plug-in File cleanup deletion handling.
* Because Mac doesn't call File#deleteOnExit() or a Shutdown hook on a Restart we have to do it this way.
* When a plug-in file or folder is marked for deletion it is added to the list of files to delete.
*/
private static Set<File> filesToDelete;
private void addFileToDeleteOnExit(File file) {
// Do this only once because filesToDelete is static
if(filesToDelete == null) {
filesToDelete = new HashSet<>();
// Mac does not call shutdown hooks on a Restart so delete files on Workbench shutdown
if(PlatformUtils.isMac() && PlatformUI.isWorkbenchRunning()) {
PlatformUI.getWorkbench().addWorkbenchListener(new IWorkbenchListener() {
@Override
public boolean preShutdown(IWorkbench workbench, boolean forced) {
return true;
}
@Override
public void postShutdown(IWorkbench workbench) {
deleteFiles();
}
});
}
// Else add a shutdown hook to delete files after Java has exited
else {
Runtime.getRuntime().addShutdownHook(new Thread(() -> deleteFiles()));
}
}
// Add to static list
// Will not be added more than once
filesToDelete.add(file);
}
private void deleteFiles() {
try {
for(File file : filesToDelete) {
if(file.isDirectory()) {
recursiveDelete(file);
}
else {
file.delete();
}
}
}
catch(Exception ex) {
Logger.logError("Error deleting file", ex); //$NON-NLS-1$
}
}
private void recursiveDelete(File file) throws IOException {
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if(exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
| 8,697 |
852 | # The following comments couldn't be translated into the new config version:
# Configuration file for PoolInputTest
import FWCore.ParameterSet.Config as cms
process = cms.Process("TESTRECO")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(-1)
)
process.Analysis = cms.EDAnalyzer("OtherThingAnalyzer",
thingWasDropped = cms.untracked.bool(True)
)
process.source = cms.Source("PoolSource",
setRunNumber = cms.untracked.uint32(621),
fileNames = cms.untracked.vstring('file:PoolInputDropTest.root')
)
process.p = cms.Path(process.Analysis)
| 229 |
335 | /*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <qle/pricingengines/lgmconvolutionsolver.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
namespace QuantExt {
//! Numerical convolution solver for the LGM model
/*! Reference: Hagan, Methodology for callable swaps and Bermudan
exercise into swaptions
*/
LgmConvolutionSolver::LgmConvolutionSolver(const boost::shared_ptr<LinearGaussMarkovModel>& model, const Real sy,
const Size ny, const Real sx, const Size nx)
: model_(model), nx_(nx) {
// precompute weights
// number of x, y grid points > 0
mx_ = static_cast<Size>(floor(sx * static_cast<Real>(nx)) + 0.5);
my_ = static_cast<Size>(floor(sy * static_cast<Real>(ny)) + 0.5);
// y-grid spacing
h_ = 1.0 / static_cast<Real>(ny);
// weights for convolution in the rollback step
CumulativeNormalDistribution N;
NormalDistribution G;
y_.resize(2 * my_ + 1); // x-coordinate / standard deviation of x
w_.resize(2 * my_ + 1); // probability weight around y-grid point i
for (int i = 0; i <= 2 * my_; i++) {
y_[i] = h_ * (i - my_);
if (i == 0 || i == 2 * my_)
w_[i] = (1. + y_[0] / h_) * N(y_[0] + h_) - y_[0] / h_ * N(y_[0]) + (G(y_[0] + h_) - G(y_[0])) / h_;
else
w_[i] = (1. + y_[i] / h_) * N(y_[i] + h_) - 2. * y_[i] / h_ * N(y_[i]) -
(1. - y_[i] / h_) * N(y_[i] - h_) // opposite sign in the paper
+ (G(y_[i] + h_) - 2. * G(y_[i]) + G(y_[i] - h_)) / h_;
// w_[i] might be negative due to numerical errors
if (w_[i] < 0.0) {
QL_REQUIRE(w_[i] > -1.0E-10, "LgmConvolutionSolver: negative w (" << w_[i] << ") at i=" << i);
w_[i] = 0.0;
}
}
}
std::vector<Real> LgmConvolutionSolver::stateGrid(const Real t) const {
if (close_enough(t, 0.0))
return std::vector<Real>(2 * mx_ + 1, 0.0);
std::vector<Real> x(2 * mx_ + 1);
Real dx = std::sqrt(model_->parametrization()->zeta(t)) / static_cast<Real>(nx_);
for (int k = 0; k <= 2 * mx_; ++k) {
x[k] = dx * (k - mx_);
}
return x;
}
} // namespace QuantExt
| 1,263 |
391 | /*
*
* Copyright (C) 2020 iQIYI (www.iqiyi.com)
*
* 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.
*
*/
package com.qiyi.lens.ui.devicepanel.blockInfos;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.qiyi.lens.ui.BasePanel;
import com.qiyi.lens.ui.FloatingPanel;
import com.qiyi.lens.ui.dns.DNSSetting;
import com.qiyi.lens.ui.dns.DNSSettingPanel;
import com.qiyi.lens.ui.dns.HttpRequestPanel;
import com.qiyi.lens.utils.DataPool;
import com.qiyi.lens.utils.event.DataCallBack;
import com.qiyi.lens.utils.event.EventBus;
import com.qiyi.lenssdk.R;
/**
* 网络分析
*/
public class NetworkInfo extends AbsBlockInfo implements DataCallBack {
private static final String TAG_DNS_SETTING = "dns_setting";
private static final String TAG_NETWORK_MORE = "network_more";
private TextView mNetworkTest;
private TextView mFilterCount;
private DataCallBack dnsSettingChanged = new DataCallBack() {
@Override
public void onDataArrived(Object data, int type) {
boolean bl = (boolean) data;
mNetworkTest.setVisibility(bl ? View.VISIBLE : View.GONE);
}
};
public NetworkInfo(FloatingPanel panel) {
super(panel);
}
public void bind(View view) {
EventBus.registerEvent(this, DataPool.DATA_TYPE_NET_FILTER_SIZE);
EventBus.registerEvent(dnsSettingChanged, DataPool.EVENT_DNS_SET_CHANGE);
}
public void unBind() {
EventBus.unRegisterEvent(this, DataPool.DATA_TYPE_NET_FILTER_SIZE);
EventBus.unRegisterEvent(dnsSettingChanged, DataPool.EVENT_DNS_SET_CHANGE);
}
@Override
public View createView(ViewGroup parent) {
View root = inflateView(parent, R.layout.lens_block_network_info);
mNetworkTest = root.findViewById(R.id.tv_network_test);
View mMoreBtn = root.findViewById(R.id.network_more);
mMoreBtn.setTag(TAG_NETWORK_MORE);
Button mDnsSetting = root.findViewById(R.id.network_dns_setting);
mDnsSetting.setTag(TAG_DNS_SETTING);
mFilterCount = root.findViewById(R.id.tv_dns_info);
if (DNSSetting.isFilterEnabled(parent.getContext())) {
mFilterCount.setText("正在抓包");
} else {
mFilterCount.setText("未开启抓包");
}
mMoreBtn.setOnClickListener(this);
mDnsSetting.setOnClickListener(this);
if (!DNSSetting.isDNSEnabled(parent.getContext())) {
mNetworkTest.setVisibility(View.GONE);
}
return root;
}
@Override
public void onDataArrived(Object data, int type) {
BasePanel panel = getPanel();
if (panel != null) {
refresh.setData((int) data);
panel.getMainHandler().removeCallbacks(refresh);
panel.getMainHandler().postDelayed(refresh, 500);
}
}
private DataRefresh refresh = new DataRefresh();
class DataRefresh implements Runnable {
int data;
public void setData(int d) {
data = d;
}
@Override
public void run() {
int size = data;
mFilterCount.setText("抓到" + size + "条请求");
mFilterCount.invalidate();
}
}
@Override
public void onClick(View view) {
if (view.getTag() != null && view.getTag() instanceof String) {
String tag = (String) view.getTag();
FloatingPanel basePanel = getPanel();
switch (tag) {
case TAG_DNS_SETTING:
if (basePanel != null) {
DNSSettingPanel panel = new DNSSettingPanel(basePanel);
panel.show();
}
break;
case TAG_NETWORK_MORE:
HttpRequestPanel panel = new HttpRequestPanel(basePanel);
panel.show();
break;
}
}
}
}
| 1,961 |
5,169 | <reponame>Gantios/Specs
{
"name": "onnxruntime-mobile-c",
"version": "1.8.0",
"authors": {
"<NAME>": "<EMAIL>"
},
"license": {
"type": "MIT",
"file": "LICENSE"
},
"homepage": "https://github.com/microsoft/onnxruntime",
"source": {
"http": "https://onnxruntimepackages.blob.core.windows.net/ortmobilestore/onnxruntime-mobile-c-1.8.0.zip"
},
"summary": "ONNX Runtime Mobile C/C++ Pod",
"platforms": {
"ios": "11.0"
},
"vendored_frameworks": "onnxruntime.framework",
"weak_frameworks": "CoreML",
"source_files": "onnxruntime.framework/Headers/*.h",
"pod_target_xcconfig": {
"EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64"
},
"user_target_xcconfig": {
"EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64"
},
"description": "A preview pod for ONNX Runtime Mobile C/C++ library. Pods for Objective-C and Swift coming soon."
}
| 378 |
2,104 | #include <src/mutator.h>
#include "test.pb.h"
class MyMutator : public protobuf_mutator::Mutator {
};
| 41 |
392 | /*******************************************************************************
* Copyright (c) 2015 - 2018
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package jsettlers.mapcreator.tools.objects;
import java.util.Locale;
import jsettlers.logic.map.loading.data.objects.DecorationMapDataObject;
import jsettlers.logic.map.loading.data.objects.MapDataObject;
import jsettlers.logic.map.loading.data.objects.StoneMapDataObject;
import jsettlers.logic.map.loading.data.objects.MapTreeObject;
import jsettlers.common.position.ShortPoint2D;
import jsettlers.mapcreator.data.MapData;
import jsettlers.mapcreator.localization.EditorLabels;
import jsettlers.mapcreator.tools.AbstractTool;
import jsettlers.mapcreator.tools.shapes.EShapeType;
import jsettlers.mapcreator.tools.shapes.ShapeType;
public class PlaceMapObjectTool extends AbstractTool {
private final MapDataObject object;
public PlaceMapObjectTool(MapDataObject object) {
super(null, null);
shapeTypes.add(EShapeType.POINT);
shapeTypes.add(EShapeType.GRID_CIRCLE);
this.object = object;
if (object == null) {
// initialized in subclass
return;
}
if (object instanceof StoneMapDataObject) {
this.translatedName = String.format(Locale.ENGLISH, EditorLabels.getLabel("tool.stone"), ((StoneMapDataObject) object).getCapacity());
} else if (object instanceof MapTreeObject) {
this.translatedName = EditorLabels.getLabel("tool.tree");
} else if (object instanceof DecorationMapDataObject) {
this.translatedName = String.format(Locale.ENGLISH, EditorLabels.getLabel("tool.place"), EditorLabels.getLabel("tool.object." + ((DecorationMapDataObject) object).getType()));
} else {
this.translatedName = String.format(Locale.ENGLISH, EditorLabels.getLabel("tool.place"), object.getClass().getSimpleName());
}
}
@Override
public void apply(MapData map, ShapeType shape, ShortPoint2D start, ShortPoint2D end, double uidx) {
byte[][] placeAt = new byte[map.getWidth()][map.getHeight()];
shape.setAffectedStatus(placeAt, start, end);
for (int x = 0; x < map.getWidth(); x++) {
for (int y = 0; y < map.getHeight(); y++) {
if (placeAt[x][y] > Byte.MAX_VALUE / 2) {
map.placeObject(getObject(), x, y);
}
}
}
}
public MapDataObject getObject() {
return object;
}
}
| 1,025 |
1,144 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via <EMAIL> or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for R_Status
* @author Adempiere (generated)
* @version Release 3.5.4a - $Id$ */
public class X_R_Status extends PO implements I_R_Status, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_R_Status (Properties ctx, int R_Status_ID, String trxName)
{
super (ctx, R_Status_ID, trxName);
/** if (R_Status_ID == 0)
{
setIsClosed (false);
// N
setIsDefault (false);
setIsFinalClose (false);
// N
setIsOpen (false);
setIsWebCanUpdate (false);
setName (null);
setR_StatusCategory_ID (0);
setR_Status_ID (0);
setSeqNo (0);
setValue (null);
} */
}
/** Load Constructor */
public X_R_Status (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_Status[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Closed Status.
@param IsClosed
The status is closed
*/
public void setIsClosed (boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, Boolean.valueOf(IsClosed));
}
/** Get Closed Status.
@return The status is closed
*/
public boolean isClosed ()
{
Object oo = get_Value(COLUMNNAME_IsClosed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Final Close.
@param IsFinalClose
Entries with Final Close cannot be re-opened
*/
public void setIsFinalClose (boolean IsFinalClose)
{
set_Value (COLUMNNAME_IsFinalClose, Boolean.valueOf(IsFinalClose));
}
/** Get Final Close.
@return Entries with Final Close cannot be re-opened
*/
public boolean isFinalClose ()
{
Object oo = get_Value(COLUMNNAME_IsFinalClose);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Status.
@param IsOpen
The status is closed
*/
public void setIsOpen (boolean IsOpen)
{
set_Value (COLUMNNAME_IsOpen, Boolean.valueOf(IsOpen));
}
/** Get Open Status.
@return The status is closed
*/
public boolean isOpen ()
{
Object oo = get_Value(COLUMNNAME_IsOpen);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Web Can Update.
@param IsWebCanUpdate
Entry can be updated from the Web
*/
public void setIsWebCanUpdate (boolean IsWebCanUpdate)
{
set_Value (COLUMNNAME_IsWebCanUpdate, Boolean.valueOf(IsWebCanUpdate));
}
/** Get Web Can Update.
@return Entry can be updated from the Web
*/
public boolean isWebCanUpdate ()
{
Object oo = get_Value(COLUMNNAME_IsWebCanUpdate);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
public I_R_Status getNext_Status() throws RuntimeException
{
return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name)
.getPO(getNext_Status_ID(), get_TrxName()); }
/** Set Next Status.
@param Next_Status_ID
Move to next status automatically after timeout
*/
public void setNext_Status_ID (int Next_Status_ID)
{
if (Next_Status_ID < 1)
set_Value (COLUMNNAME_Next_Status_ID, null);
else
set_Value (COLUMNNAME_Next_Status_ID, Integer.valueOf(Next_Status_ID));
}
/** Get Next Status.
@return Move to next status automatically after timeout
*/
public int getNext_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Next_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_StatusCategory getR_StatusCategory() throws RuntimeException
{
return (I_R_StatusCategory)MTable.get(getCtx(), I_R_StatusCategory.Table_Name)
.getPO(getR_StatusCategory_ID(), get_TrxName()); }
/** Set Status Category.
@param R_StatusCategory_ID
Request Status Category
*/
public void setR_StatusCategory_ID (int R_StatusCategory_ID)
{
if (R_StatusCategory_ID < 1)
set_Value (COLUMNNAME_R_StatusCategory_ID, null);
else
set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID));
}
/** Get Status Category.
@return Request Status Category
*/
public int getR_StatusCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Status.
@param R_Status_ID
Request Status
*/
public void setR_Status_ID (int R_Status_ID)
{
if (R_Status_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Status_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID));
}
/** Get Status.
@return Request Status
*/
public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
/** Set Timeout in Days.
@param TimeoutDays
Timeout in Days to change Status automatically
*/
public void setTimeoutDays (int TimeoutDays)
{
set_Value (COLUMNNAME_TimeoutDays, Integer.valueOf(TimeoutDays));
}
/** Get Timeout in Days.
@return Timeout in Days to change Status automatically
*/
public int getTimeoutDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_TimeoutDays);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_Status getUpdate_Status() throws RuntimeException
{
return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name)
.getPO(getUpdate_Status_ID(), get_TrxName()); }
/** Set Update Status.
@param Update_Status_ID
Automatically change the status after entry from web
*/
public void setUpdate_Status_ID (int Update_Status_ID)
{
if (Update_Status_ID < 1)
set_Value (COLUMNNAME_Update_Status_ID, null);
else
set_Value (COLUMNNAME_Update_Status_ID, Integer.valueOf(Update_Status_ID));
}
/** Get Update Status.
@return Automatically change the status after entry from web
*/
public int getUpdate_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Update_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | 3,964 |
831 | <gh_stars>100-1000
/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.
*/
package com.android.tools.idea;
import com.android.testutils.JarTestSuiteRunner;
import com.android.tools.idea.gradle.project.sync.perf.AbstractGradleSyncPerfTestCase;
import com.android.tools.idea.gradle.project.sync.perf.TestProjectPaths;
import com.android.tools.tests.GradleDaemonsRule;
import com.android.tools.tests.IdeaTestSuiteBase;
import com.android.tools.tests.LeakCheckerRule;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
@RunWith(JarTestSuiteRunner.class)
@JarTestSuiteRunner.ExcludeClasses({
SyncPerfTestSuite.class, // a suite mustn't contain itself
AbstractGradleSyncPerfTestCase.class, // Abstract class
})
public class SyncPerfTestSuite extends IdeaTestSuiteBase {
@ClassRule public static final LeakCheckerRule checker = new LeakCheckerRule();
@ClassRule public static final GradleDaemonsRule gradle = new GradleDaemonsRule();
static {
setUpSourceZip("prebuilts/studio/buildbenchmarks/dolphin.3627ef8a/src.zip",
// We unzip the source code into the same directory containing other test data.
"tools/adt/idea/sync-perf-tests/testData/" + TestProjectPaths.DOLPHIN_PROJECT_ROOT,
new DiffSpec("prebuilts/studio/buildbenchmarks/dolphin.3627ef8a/setupForSyncTest.diff", 2));
setUpSourceZip("prebuilts/studio/buildbenchmarks/android-studio-gradle-test.3600041f/src.zip",
"tools/adt/idea/sync-perf-tests/testData/" + TestProjectPaths.BASE100,
new DiffSpec("prebuilts/studio/buildbenchmarks/android-studio-gradle-test.3600041f/setupForSyncTest.diff", 2));
unzipIntoOfflineMavenRepo("prebuilts/studio/buildbenchmarks/dolphin.3627ef8a/repo.zip");
unzipIntoOfflineMavenRepo("prebuilts/studio/buildbenchmarks/android-studio-gradle-test.3600041f/repo.zip");
unzipIntoOfflineMavenRepo("tools/adt/idea/sync-perf-tests/test_deps.zip");
unzipIntoOfflineMavenRepo("tools/base/build-system/previous-versions/3.5.0.zip");
unzipIntoOfflineMavenRepo("tools/base/build-system/studio_repo.zip");
}
}
| 978 |
713 | package org.infinispan.query.dsl.impl;
/**
* @author <EMAIL>
* @since 6.0
*/
interface Visitable {
<ReturnType> ReturnType accept(Visitor<ReturnType> visitor);
}
| 61 |
608 | package com.huxq17.example.floatball;
import android.app.Application;
import com.buyi.huxq17.serviceagency.ServiceAgency;
import com.buyi.huxq17.serviceagency.exception.AgencyException;
import com.huxq17.floatball.libarary.LocationService;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//需要记录并在再次打开app的时候恢复位置
//在LocationService的实现类里用的是SharedPreferences来记录位置,需要Context
//如果你的实现方式不需要Context,则可以不需要这个步骤,可以去掉这行代码
try {
ServiceAgency.getService(LocationService.class).start(this);
}catch (AgencyException e){
//ignore
}
}
}
| 383 |
9,402 | <reponame>pyracanda/runtime<filename>src/mono/mono/metadata/sgen-toggleref.c
/**
* \file
* toggleref support for sgen
*
* Author:
* <NAME> (<EMAIL>)
*
* Copyright 2011 Xamarin, Inc.
* Copyright (C) 2012 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#ifdef HAVE_SGEN_GC
#include "sgen/sgen-gc.h"
#include "sgen-toggleref.h"
#include "sgen/sgen-client.h"
#ifndef DISABLE_SGEN_TOGGLEREF
/*only one of the two can be non null at a given time*/
typedef struct {
GCObject *strong_ref;
GCObject *weak_ref;
} MonoGCToggleRef;
static MonoToggleRefStatus (*toggleref_callback) (MonoObject *obj);
static MonoGCToggleRef *toggleref_array;
static int toggleref_array_size;
static int toggleref_array_capacity;
void
sgen_process_togglerefs (void)
{
int i, w;
int toggle_ref_counts [3] = { 0, 0, 0 };
SGEN_LOG (4, "Proccessing ToggleRefs %d", toggleref_array_size);
for (i = w = 0; i < toggleref_array_size; ++i) {
int res;
MonoGCToggleRef r = toggleref_array [i];
MonoObject *obj;
if (r.strong_ref)
obj = r.strong_ref;
else if (r.weak_ref)
obj = r.weak_ref;
else
continue;
res = toggleref_callback (obj);
++toggle_ref_counts [res];
switch (res) {
case MONO_TOGGLE_REF_DROP:
break;
case MONO_TOGGLE_REF_STRONG:
toggleref_array [w].strong_ref = obj;
toggleref_array [w].weak_ref = NULL;
++w;
break;
case MONO_TOGGLE_REF_WEAK:
toggleref_array [w].strong_ref = NULL;
toggleref_array [w].weak_ref = obj;
++w;
break;
default:
g_assert_not_reached ();
}
}
toggleref_array_size = w;
SGEN_LOG (4, "Done Proccessing ToggleRefs dropped %d strong %d weak %d final size %d",
toggle_ref_counts [MONO_TOGGLE_REF_DROP],
toggle_ref_counts [MONO_TOGGLE_REF_STRONG],
toggle_ref_counts [MONO_TOGGLE_REF_WEAK],
w);
}
void sgen_client_mark_togglerefs (char *start, char *end, ScanCopyContext ctx)
{
CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
SgenGrayQueue *queue = ctx.queue;
int i;
SGEN_LOG (4, "Marking ToggleRefs %d", toggleref_array_size);
for (i = 0; i < toggleref_array_size; ++i) {
if (toggleref_array [i].strong_ref) {
GCObject *object = toggleref_array [i].strong_ref;
if ((char*)object >= start && (char*)object < end) {
SGEN_LOG (6, "\tcopying strong slot %d", i);
copy_func (&toggleref_array [i].strong_ref, queue);
}
}
}
sgen_drain_gray_stack (ctx);
}
void
sgen_foreach_toggleref_root (void (*callback)(MonoObject*, gpointer), gpointer data)
{
int i;
for (i = 0; i < toggleref_array_size; ++i) {
if (toggleref_array [i].strong_ref)
callback (toggleref_array [i].strong_ref, data);
}
}
void sgen_client_clear_togglerefs (char *start, char *end, ScanCopyContext ctx)
{
CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
SgenGrayQueue *queue = ctx.queue;
int i;
SGEN_LOG (4, "Clearing ToggleRefs %d", toggleref_array_size);
for (i = 0; i < toggleref_array_size; ++i) {
if (toggleref_array [i].weak_ref) {
GCObject *object = toggleref_array [i].weak_ref;
if ((char*)object >= start && (char*)object < end) {
if (sgen_gc_is_object_ready_for_finalization (object)) {
SGEN_LOG (6, "\tcleaning weak slot %d", i);
toggleref_array [i].weak_ref = NULL; /* We defer compaction to only happen on the callback step. */
} else {
SGEN_LOG (6, "\tkeeping weak slot %d", i);
copy_func (&toggleref_array [i].weak_ref, queue);
}
}
}
}
sgen_drain_gray_stack (ctx);
}
static void
ensure_toggleref_capacity (int capacity)
{
if (!toggleref_array) {
toggleref_array_capacity = 32;
toggleref_array = (MonoGCToggleRef *)sgen_alloc_internal_dynamic (
toggleref_array_capacity * sizeof (MonoGCToggleRef),
INTERNAL_MEM_TOGGLEREF_DATA,
TRUE);
}
if (toggleref_array_size + capacity >= toggleref_array_capacity) {
MonoGCToggleRef *tmp;
int old_capacity = toggleref_array_capacity;
while (toggleref_array_capacity < toggleref_array_size + capacity)
toggleref_array_capacity *= 2;
tmp = (MonoGCToggleRef *)sgen_alloc_internal_dynamic (
toggleref_array_capacity * sizeof (MonoGCToggleRef),
INTERNAL_MEM_TOGGLEREF_DATA,
TRUE);
memcpy (tmp, toggleref_array, toggleref_array_size * sizeof (MonoGCToggleRef));
sgen_free_internal_dynamic (toggleref_array, old_capacity * sizeof (MonoGCToggleRef), INTERNAL_MEM_TOGGLEREF_DATA);
toggleref_array = tmp;
}
}
/**
* mono_gc_toggleref_add:
* @object object to register for toggleref processing
* @strong_ref if true the object is registered with a strong ref, a weak one otherwise
*
* Register a given object for toggleref processing. It will be stored internally and the toggleref callback will be called
* on it until it returns MONO_TOGGLE_REF_DROP or is collected.
*/
void
mono_gc_toggleref_add (MonoObject *object, mono_bool strong_ref)
{
if (!toggleref_callback)
return;
MONO_ENTER_GC_UNSAFE;
SGEN_LOG (4, "Adding toggleref %p %d", object, strong_ref);
sgen_gc_lock ();
ensure_toggleref_capacity (1);
toggleref_array [toggleref_array_size].strong_ref = strong_ref ? object : NULL;
toggleref_array [toggleref_array_size].weak_ref = strong_ref ? NULL : object;
++toggleref_array_size;
sgen_gc_unlock ();
MONO_EXIT_GC_UNSAFE;
}
/**
* mono_gc_toggleref_register_callback:
* \param callback callback used to determine the new state of the given object.
*
* The callback must decide the status of a given object. It must return one of the values in the \c MONO_TOGGLE_REF_ enum.
* This function is called with the world running but with the GC locked. This means that you can do everything that doesn't
* require GC interaction. This includes, but not limited to, allocating objects, (de)registering for finalization, manipulating
* gchandles, storing to reference fields or interacting with other threads that might perform such operations.
*/
void
mono_gc_toggleref_register_callback (MonoToggleRefStatus (*proccess_toggleref) (MonoObject *obj))
{
toggleref_callback = proccess_toggleref;
}
static MonoToggleRefStatus
test_toggleref_callback (MonoObject *obj)
{
MonoToggleRefStatus status = MONO_TOGGLE_REF_DROP;
MONO_STATIC_POINTER_INIT (MonoClassField, mono_toggleref_test_field)
mono_toggleref_test_field = mono_class_get_field_from_name_full (mono_object_class (obj), "__test", NULL);
g_assert (mono_toggleref_test_field);
MONO_STATIC_POINTER_INIT_END (MonoClassField, mono_toggleref_test_field)
/* In coop mode, important to not call a helper that will pin obj! */
mono_field_get_value_internal (obj, mono_toggleref_test_field, &status);
printf ("toggleref-cb obj %d\n", status);
return status;
}
void
sgen_register_test_toggleref_callback (void)
{
toggleref_callback = test_toggleref_callback;
}
#else
void
mono_gc_toggleref_register_callback (MonoToggleRefStatus (*proccess_toggleref) (MonoObject *obj))
{
}
void
mono_gc_toggleref_add (MonoObject *object, mono_bool strong_ref)
{
}
#endif
#endif
| 2,695 |
1,665 | <reponame>codeclimate-testing/bish
#ifndef __BISH_UTIL_H__
#define __BISH_UTIL_H__
#include <limits.h>
#include <string>
#include <sstream>
#include <vector>
// Convert the given string to the template type.
template <typename T>
inline T convert_string(const std::string &s) {
T t;
std::istringstream(s) >> t;
return t;
}
// Convert int to string
inline std::string as_string(int i) {
return dynamic_cast<std::ostringstream &>((std::ostringstream() << i )).str();
}
inline std::string as_string(const std::string &s) {
return s;
}
// Return true if the given path is a valid file.
bool is_file(const std::string &path);
// Return the absolute path to the standard library.
std::string get_stdlib_path();
// Return the absolute path from the given path.
std::string abspath(const std::string &path);
// Return the basename (last component) of a path.
std::string basename(const std::string &path);
// Return the directory name of a path.
std::string dirname(const std::string &path);
// Return the string with any suffix beginning with "marker" removed.
// E.g. remove_suffix("test.bish", ".") returns "test"
std::string remove_suffix(const std::string &s, const std::string &marker);
// Strip leading and trailing whitespace.
std::string strip(const std::string &s);
// Return the name of a module from a pathname.
// E.g. module_name_from_path("/a/b/test.bish") returns "test"
std::string module_name_from_path(const std::string &path);
// Return the given line number from the given file.
std::string read_line_from_file(const std::string &path, unsigned lineno);
#endif
| 512 |
852 | import FWCore.ParameterSet.Config as cms
process = cms.Process("makeSD")
process.configurationMetadata = cms.untracked.PSet(
version = cms.untracked.string('$Revision: 1.1 $'),
annotation = cms.untracked.string('SD and central skims'),
name = cms.untracked.string('$Source: /cvs_server/repositories/CMSSW/CMSSW/Configuration/Skimming/test/SDmaker_6SD_3CS_PDMinBias_1e28_reprocess370_cfg.py,v $')
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1000)
)
process.load("Configuration.StandardSequences.MagneticField_38T_cff")
process.load("Configuration.StandardSequences.GeometryExtended_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load('Configuration.EventContent.EventContent_cff')
process.GlobalTag.globaltag = "GR_R_37X_V6A::All"
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/data/Commissioning10/MinimumBias/RAW-RECO/v8/000/132/601/F85204EE-EB40-DF11-8F71-001A64789D1C.root'
),
secondaryFileNames = cms.untracked.vstring(
'/store/data/Commissioning09/Cosmics/RAW/v3/000/105/755/F6887FD0-9371-DE11-B69E-00304879FBB2.root'
)
)
process.source.inputCommands = cms.untracked.vstring("keep *", "drop *_MEtoEDMConverter_*_*")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 100
import HLTrigger.HLTfilters.hltHighLevelDev_cfi
### JetMETTau SD
process.JetMETTau_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.JetMETTau_1e28.HLTPaths = (
"HLT_Jet15U",
"HLT_DiJetAve15U_8E29",
"HLT_FwdJet20U",
"HLT_Jet30U",
"HLT_Jet50U",
"HLT_DiJetAve30U_8E29",
"HLT_QuadJet15U",
"HLT_MET45",
"HLT_MET100",
"HLT_HT100U",
"HLT_SingleLooseIsoTau20",
"HLT_DoubleLooseIsoTau15",
"HLT_DoubleJet15U_ForwardBackward",
"HLT_BTagMu_Jet10U",
"HLT_BTagIP_Jet50U",
"HLT_StoppedHSCP_8E29"
)
process.JetMETTau_1e28.HLTPathsPrescales = cms.vuint32(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
process.JetMETTau_1e28.HLTOverallPrescale = cms.uint32(1)
process.JetMETTau_1e28.throw = False
process.JetMETTau_1e28.andOr = True
process.filterSdJetMETTau_1e28 = cms.Path(process.JetMETTau_1e28)
### JetMETTauMonitor SD
process.JetMETTauMonitor_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.JetMETTauMonitor_1e28.HLTPaths = (
"HLT_L1Jet6U",
"HLT_L1MET20",
"HLT_L1SingleCenJet",
"HLT_L1SingleForJet",
"HLT_L1SingleTauJet",
"HLT_L1Jet10U",
"HLT_L1Jet10U_NoBPTX",
"HLT_L1Jet6U_NoBPTX",
"HLT_L1SingleCenJet_NoBPTX",
"HLT_L1SingleForJet_NoBPTX",
"HLT_L1SingleTauJet_NoBPTX"
)
process.JetMETTauMonitor_1e28.HLTPathsPrescales = cms.vuint32(1,1,1,1,1,1,1,1,1,1,1)
process.JetMETTauMonitor_1e28.HLTOverallPrescale = cms.uint32(1)
process.JetMETTauMonitor_1e28.throw = False
process.JetMETTauMonitor_1e28.andOr = True
process.filterSdJetMETTauMonitor_1e28 = cms.Path(process.JetMETTauMonitor_1e28)
### MuMonitor SD
process.MuMonitor_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.MuMonitor_1e28.HLTPaths = (
"HLT_L1MuOpen",
"HLT_L1Mu"
)
process.MuMonitor_1e28.HLTPathsPrescales = cms.vuint32(1,1)
process.MuMonitor_1e28.HLTOverallPrescale = cms.uint32(1)
process.MuMonitor_1e28.throw = False
process.MuMonitor_1e28.andOr = True
process.filterSdMuMonitor_1e28 = cms.Path(process.MuMonitor_1e28)
### Mu SD
process.Mu_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.Mu_1e28.HLTPaths = (
"HLT_L2Mu0",
"HLT_L2Mu3",
#"HLT_L2Mu5",
"HLT_L1Mu20",
"HLT_L2Mu9",
"HLT_L2Mu11",
"HLT_L1Mu14_L1SingleEG10",
"HLT_L1Mu14_L1SingleJet6U",
"HLT_L1Mu14_L1ETM30",
"HLT_L2DoubleMu0",
"HLT_L1DoubleMuOpen",
"HLT_DoubleMu0",
"HLT_DoubleMu3",
"HLT_Mu3",
"HLT_Mu5",
"HLT_Mu9",
"HLT_IsoMu3",
"HLT_Mu0_L1MuOpen",
"HLT_Mu0_Track0_Jpsi",
"HLT_Mu3_L1MuOpen",
"HLT_Mu3_Track0_Jpsi",
"HLT_Mu5_L1MuOpen",
"HLT_Mu5_Track0_Jpsi",
"HLT_Mu0_L2Mu0",
"HLT_Mu3_L2Mu0",
"HLT_Mu5_L2Mu0"
)
process.Mu_1e28.HLTPathsPrescales = cms.vuint32(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
process.Mu_1e28.HLTOverallPrescale = cms.uint32(1)
process.Mu_1e28.throw = False
process.Mu_1e28.andOr = True
process.filterSdMu_1e28 = cms.Path(process.Mu_1e28)
### EGMonitor SD
process.EGMonitor_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.EGMonitor_1e28.HLTPaths = (
"HLT_L1SingleEG2",
"HLT_L1SingleEG5",
"HLT_L1SingleEG8",
"HLT_L1DoubleEG5",
"HLT_EgammaSuperClusterOnly_L1R",
"HLT_L1SingleEG20_NoBPTX",
"HLT_L1SingleEG2_NoBPTX",
"HLT_L1SingleEG5_NoBPTX"
)
process.EGMonitor_1e28.HLTPathsPrescales = cms.vuint32(1,1,1,1,1,1,1,1)
process.EGMonitor_1e28.HLTOverallPrescale = cms.uint32(1)
process.EGMonitor_1e28.throw = False
process.EGMonitor_1e28.andOr = True
process.filterSdEGMonitor_1e28 = cms.Path(process.EGMonitor_1e28)
### EG SD
process.EG_1e28 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.EG_1e28.HLTPaths = (
"HLT_Photon10_L1R",
"HLT_Photon15_L1R",
"HLT_Photon15_LooseEcalIso_L1R",
"HLT_Photon20_L1R",
"HLT_Photon30_L1R_8E29",
"HLT_DoublePhoton4_Jpsi_L1R",
"HLT_DoublePhoton4_Upsilon_L1R",
"HLT_DoublePhoton4_eeRes_L1R",
"HLT_DoublePhoton5_eeRes_L1R", #added to match the /cdaq/physics/firstCollisions10/v2.0/HLT_7TeV/V5 table
"HLT_DoublePhoton5_Jpsi_L1R",
"HLT_DoublePhoton5_Upsilon_L1R",
"HLT_DoublePhoton5_L1R",
"HLT_DoublePhoton10_L1R",
"HLT_DoubleEle5_SW_L1R",
"HLT_Ele20_LW_L1R",
"HLT_Ele15_SiStrip_L1R",
"HLT_Ele15_SC10_LW_L1R",
"HLT_Ele15_LW_L1R",
"HLT_Ele10_LW_EleId_L1R",
"HLT_Ele10_LW_L1R",
"HLT_Photon15_TrackIso_L1R"
)
process.EG_1e28.HLTPathsPrescales = cms.vuint32(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
process.EG_1e28.HLTOverallPrescale = cms.uint32(1)
process.EG_1e28.throw = False
process.EG_1e28.andOr = True
process.filterSdEG_1e28 = cms.Path(process.EG_1e28)
### JetMET AOD CS
process.DiJetAve_1e29 = HLTrigger.HLTfilters.hltHighLevelDev_cfi.hltHighLevelDev.clone(andOr = True)
process.DiJetAve_1e29.HLTPaths = ("HLT_DiJetAve15U_8E29","HLT_DiJetAve30U_8E29")
process.DiJetAve_1e29.HLTPathsPrescales = cms.vuint32(1,1)
process.DiJetAve_1e29.HLTOverallPrescale = cms.uint32(1)
process.DiJetAve_1e29.andOr = True
process.filterCsDiJetAve_1e29 = cms.Path(process.DiJetAve_1e29)
### Onia skim CS
process.goodMuons = cms.EDFilter("MuonRefSelector",
src = cms.InputTag("muons"),
cut = cms.string("isGlobalMuon || (isTrackerMuon && numberOfMatches('SegmentAndTrackArbitration')>0)"),
)
process.diMuons = cms.EDProducer("CandViewShallowCloneCombiner",
decay = cms.string("goodMuons goodMuons"),
checkCharge = cms.bool(False),
cut = cms.string("mass > 2"),
)
process.diMuonFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag("diMuons"),
minNumber = cms.uint32(1),
)
process.Skim_diMuons = cms.Path(
process.goodMuons *
process.diMuons *
process.diMuonFilter
)
### Tau skim CS
process.load("CondCore.DBCommon.CondDBSetup_cfi")
process.load("TrackingTools/TransientTrack/TransientTrackBuilder_cfi")
process.load("L1TriggerConfig.L1GtConfigProducers.L1GtTriggerMaskTechTrigConfig_cff")
process.load("HLTrigger/HLTfilters/hltLevel1GTSeed_cfi")
process.hltLevel1GTSeed.L1TechTriggerSeeding = cms.bool(True)
process.hltLevel1GTSeed.L1SeedsLogicalExpression = cms.string('(0 AND (40 OR 41) AND NOT (36 OR 37 OR 38 OR 39))')
process.scrapping = cms.EDFilter("FilterOutScraping",
applyfilter = cms.untracked.bool(True),
debugOn = cms.untracked.bool(False),
numtrack = cms.untracked.uint32(10),
thresh = cms.untracked.double(0.25)
)
process.PFTausSelected = cms.EDFilter("PFTauSelector",
src = cms.InputTag("shrinkingConePFTauProducer"),
discriminators = cms.VPSet(
cms.PSet( discriminator=cms.InputTag("shrinkingConePFTauDiscriminationByIsolation"),
selectionCut=cms.double(0.5)
),
),
cut = cms.string('et > 15. && abs(eta) < 2.5')
)
process.PFTauSkimmed = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag('PFTausSelected'),
minNumber = cms.uint32(1)
)
process.tauFilter = cms.Path(
process.hltLevel1GTSeed *
process.scrapping *
process.PFTausSelected *
process.PFTauSkimmed
)
process.outputSdJetMETTau = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdJetMETTau_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_JetMETTau')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_JetMETTau_1e28.root')
)
process.outputSdJetMETTauMonitor = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdJetMETTauMonitor_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_JetMETTauMonitor')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_JetMETTauMonitor_1e28.root')
)
process.outputSdMuMonitor = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdMuMonitor_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_MuMonitor')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_MuMonitor_1e28.root')
)
process.outputSdMu = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdMu_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_Mu')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_Mu_1e28.root')
)
process.outputSdEGMonitor = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdEGMonitor_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_EGMonitor')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_EGMonitor_1e28.root')
)
process.outputSdEG = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterSdEG_1e28')),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('SD_EG')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('SD_EG_1e28.root')
)
process.outputCsDiJet = cms.OutputModule("PoolOutputModule",
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('USER'),
filterName = cms.untracked.string('CS_DiJetAve')),
outputCommands = cms.untracked.vstring(
'drop *',
#------- CaloJet collections ------
'keep recoCaloJets_kt4CaloJets_*_*',
'keep recoCaloJets_kt6CaloJets_*_*',
'keep recoCaloJets_ak5CaloJets_*_*',
'keep recoCaloJets_ak7CaloJets_*_*',
'keep recoCaloJets_iterativeCone5CaloJets_*_*',
#------- CaloJet ID ---------------
'keep *_kt4JetID_*_*',
'keep *_kt6JetID_*_*',
'keep *_ak5JetID_*_*',
'keep *_ak7JetID_*_*',
'keep *_ic5JetID_*_*',
#------- PFJet collections ------
'keep recoPFJets_kt4PFJets_*_*',
'keep recoPFJets_kt6PFJets_*_*',
'keep recoPFJets_ak5PFJets_*_*',
'keep recoPFJets_ak7PFJets_*_*',
'keep recoPFJets_iterativeCone5PFJets_*_*',
#------- JPTJet collections ------
'keep *_JetPlusTrackZSPCorJetAntiKt5_*_*',
#'keep *_ak4JPTJets_*_*',
#'keep *_iterativeCone5JPTJets_*_*',
#------- Trigger collections ------
'keep edmTriggerResults_TriggerResults_*_*',
'keep *_hltTriggerSummaryAOD_*_*',
'keep L1GlobalTriggerObjectMapRecord_*_*_*',
'keep L1GlobalTriggerReadoutRecord_*_*_*',
#------- Tracks collection --------
'keep recoTracks_generalTracks_*_*',
#------- CaloTower collection -----
'keep *_towerMaker_*_*',
#------- Various collections ------
'keep *_EventAuxilary_*_*',
'keep *_offlinePrimaryVertices_*_*',
'keep *_hcalnoise_*_*',
#------- MET collections ----------
'keep *_metHO_*_*',
'keep *_metNoHF_*_*',
'keep *_metNoHFHO_*_*',
'keep *_met_*_*'),
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filterCsDiJetAve_1e29')),
fileName = cms.untracked.string('CS_JetAOD_DiJetAve_1e28.root')
)
process.outputCsOnia = cms.OutputModule("PoolOutputModule",
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RECO'),
filterName = cms.untracked.string('CS_Onia')),
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('Skim_diMuons')),
outputCommands = process.RECOEventContent.outputCommands,
fileName = cms.untracked.string('CS_Onia_1e28.root')
)
process.outputCsTau = cms.OutputModule("PoolOutputModule",
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RAW-RECO'),
filterName = cms.untracked.string('CS_Tau')),
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('tauFilter')),
outputCommands = process.FEVTEventContent.outputCommands,
fileName = cms.untracked.string('CS_Tau_1e28.root')
)
process.this_is_the_end = cms.EndPath(
process.outputSdJetMETTau +
process.outputSdJetMETTauMonitor +
process.outputSdMuMonitor +
process.outputSdMu +
process.outputSdEGMonitor +
process.outputSdEG +
process.outputCsDiJet +
process.outputCsOnia +
process.outputCsTau
)
| 8,540 |
1,350 | <reponame>billwert/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.security.fluent.models.DeviceInner;
/** An instance of this class provides access to all the operations defined in DevicesClient. */
public interface DevicesClient {
/**
* Get device.
*
* @param resourceId The identifier of the resource.
* @param deviceId Identifier of the device.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return device.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DeviceInner get(String resourceId, String deviceId);
/**
* Get device.
*
* @param resourceId The identifier of the resource.
* @param deviceId Identifier of the device.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return device.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<DeviceInner> getWithResponse(String resourceId, String deviceId, Context context);
}
| 561 |
1,590 | {
"parameters": {
"api-version": "2017-08-01-preview",
"subscriptionId": "20ff7fc3-e762-44dd-bd96-b71116dcdc23",
"workspaceSettingName": "default",
"workspaceSetting": {
"id": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/workspaceSettings/default",
"name": "default",
"type": "Microsoft.Security/workspaceSettings",
"properties": {
"workspaceId": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/myRg/providers/Microsoft.OperationalInsights/workspaces/myWorkspace",
"scope": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23"
}
}
},
"responses": {
"200": {
"body": {
"id": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/workspaceSettings/default",
"name": "default",
"type": "Microsoft.Security/workspaceSettings",
"properties": {
"workspaceId": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/myRg/providers/Microsoft.OperationalInsights/workspaces/myWorkspace",
"scope": "/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23"
}
}
}
}
}
| 559 |
12,651 | <filename>test/loader/test_cluster.py
import pytest
import torch
from torch_geometric.data import Data
from torch_geometric.loader import ClusterData, ClusterLoader
from torch_geometric.utils import to_dense_adj
try:
torch.ops.torch_sparse.partition
with_metis = True
except RuntimeError:
with_metis = False
@pytest.mark.skipif(not with_metis, reason='Not compiled with METIS support')
def test_cluster_gcn():
adj = torch.tensor([
[1, 1, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
])
x = torch.Tensor([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
edge_index = adj.nonzero(as_tuple=False).t()
edge_attr = torch.arange(edge_index.size(1))
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr)
data.num_nodes = 6
cluster_data = ClusterData(data, num_parts=2, log=False)
assert cluster_data.partptr.tolist() == [0, 3, 6]
assert cluster_data.perm.tolist() == [0, 2, 4, 1, 3, 5]
assert cluster_data.data.x.tolist() == [
[0, 0],
[2, 2],
[4, 4],
[1, 1],
[3, 3],
[5, 5],
]
assert cluster_data.data.adj.to_dense().tolist() == [
[0, 2, 3, 1, 0, 0],
[8, 9, 10, 0, 0, 0],
[14, 15, 16, 0, 0, 0],
[4, 0, 0, 5, 6, 7],
[0, 0, 0, 11, 12, 13],
[0, 0, 0, 17, 18, 19],
]
data = cluster_data[0]
assert data.num_nodes == 3
assert data.x.tolist() == [[0, 0], [2, 2], [4, 4]]
assert data.edge_index.tolist() == [[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]]
assert data.edge_attr.tolist() == [0, 2, 3, 8, 9, 10, 14, 15, 16]
data = cluster_data[1]
assert data.num_nodes == 3
assert data.x.tolist() == [[1, 1], [3, 3], [5, 5]]
assert data.edge_index.tolist() == [[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]]
assert data.edge_attr.tolist() == [5, 6, 7, 11, 12, 13, 17, 18, 19]
loader = ClusterLoader(cluster_data, batch_size=1)
iterator = iter(loader)
data = next(iterator)
assert data.x.tolist() == [[0, 0], [2, 2], [4, 4]]
assert data.edge_index.tolist() == [[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]]
assert data.edge_attr.tolist() == [0, 2, 3, 8, 9, 10, 14, 15, 16]
data = next(iterator)
assert data.x.tolist() == [[1, 1], [3, 3], [5, 5]]
assert data.edge_index.tolist() == [[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]]
assert data.edge_attr.tolist() == [5, 6, 7, 11, 12, 13, 17, 18, 19]
loader = ClusterLoader(cluster_data, batch_size=2, shuffle=False)
data = next(iter(loader))
assert data.num_nodes == 6
assert data.x.tolist() == [
[0, 0],
[2, 2],
[4, 4],
[1, 1],
[3, 3],
[5, 5],
]
assert to_dense_adj(data.edge_index).squeeze().tolist() == [
[1, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
]
| 1,780 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation.directconnectivity.TcpServerMock;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TcpServerFactory {
private final static ExecutorService executor = Executors.newFixedThreadPool(10);
private final static Logger logger = LoggerFactory.getLogger(TcpServerFactory.class);
public static TcpServer startNewRntbdServer(int port) throws ExecutionException, InterruptedException {
TcpServer server = new TcpServer(port);
Promise<Boolean> promise = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE);
executor.execute(() -> {
try {
server.start(promise);
} catch (InterruptedException e) {
logger.error("Failed to start server {}", e);
}
});
// only return server when server has started successfully.
promise.get();
return server;
}
public static void shutdownRntbdServer(TcpServer server) throws ExecutionException, InterruptedException {
Promise<Boolean> promise = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE);
executor.execute(() -> server.shutdown(promise));
// only return when server has shutdown.
promise.get();
return;
}
}
| 592 |
652 | /*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* 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.
*/
package com.stratio.cassandra.lucene.schema.mapping;
import com.stratio.cassandra.lucene.IndexException;
import com.stratio.cassandra.lucene.column.Columns;
import com.stratio.cassandra.lucene.schema.mapping.builder.GeoPointMapperBuilder;
import org.apache.lucene.index.IndexableField;
import org.junit.Test;
import java.util.List;
import java.util.UUID;
import static com.stratio.cassandra.lucene.schema.SchemaBuilders.geoPointMapper;
import static org.junit.Assert.*;
public class GeoPointMapperTest extends AbstractMapperTest {
@Test
public void testConstructorWithDefaultArgs() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
assertEquals("Field name is not properly set", "field", mapper.field);
assertEquals("Validated is not set to default value", Mapper.DEFAULT_VALIDATED, mapper.validated);
assertEquals("Latitude is not properly set", "lat", mapper.latitude);
assertEquals("Longitude is not properly set", "lon", mapper.longitude);
assertEquals("Mapped columns are not properly set", 2, mapper.mappedColumns.size());
assertTrue("Mapped columns are not properly set", mapper.mappedColumns.contains("lat"));
assertTrue("Mapped columns are not properly set", mapper.mappedColumns.contains("lon"));
assertEquals("Max levels is not properly set", GeoPointMapper.DEFAULT_MAX_LEVELS, mapper.maxLevels);
assertNotNull("Spatial strategy is not properly set", mapper.strategy);
}
@Test
public void testConstructorWithAllArgs() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").validated(true).maxLevels(5).build("field");
assertEquals("Field name is not properly set", "field", mapper.field);
assertTrue("Validated is not properly set", mapper.validated);
assertEquals("Latitude is not properly set", "lat", mapper.latitude);
assertEquals("Longitude is not properly set", "lon", mapper.longitude);
assertEquals("Max levels is not properly set", 5, mapper.maxLevels);
assertNotNull("Spatial strategy is not properly set", mapper.strategy);
}
@Test
public void testConstructorWithNullMaxLevels() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").maxLevels(null).build("field");
assertEquals("Max levels is not properly set", GeoPointMapper.DEFAULT_MAX_LEVELS, mapper.maxLevels);
}
@Test(expected = IndexException.class)
public void testConstructorWithZeroLevels() {
geoPointMapper("lat", "lon").maxLevels(0).build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithNegativeLevels() {
geoPointMapper("lat", "lon").maxLevels(-1).build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithTooManyLevels() {
geoPointMapper("lat", "lon").maxLevels(25).build("field");
}
@Test
public void testJsonSerialization() {
GeoPointMapperBuilder builder = geoPointMapper("lat", "lon").maxLevels(5);
testJson(builder, "{type:\"geo_point\",latitude:\"lat\",longitude:\"lon\",max_levels:5}");
}
@Test
public void testJsonSerializationDefaults() {
GeoPointMapperBuilder builder = geoPointMapper("lat", "lon");
testJson(builder, "{type:\"geo_point\",latitude:\"lat\",longitude:\"lon\"}");
}
@Test(expected = IndexException.class)
public void testConstructorWithNullLatitude() {
geoPointMapper(null, "lon").build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithEmptyLatitude() {
geoPointMapper("", "lon").build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithBlankLatitude() {
geoPointMapper(" ", "lon").build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithNullLongitude() {
geoPointMapper(null, "lon").build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithEmptyLongitude() {
geoPointMapper("", "lon").build("field");
}
@Test(expected = IndexException.class)
public void testConstructorWithBlankLongitude() {
geoPointMapper(" ", "lon").build("field");
}
@Test
public void testGetLatitudeFromNullColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat").add("lon", 0);
assertNull("Latitude is not properly parsed", mapper.readLatitude(columns));
}
@Test
public void testGetLatitudeFromIntColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 5).add("lon", 0);
assertEquals("Latitude is not properly parsed", 5d, mapper.readLatitude(columns), 0);
}
@Test
public void testGetLatitudeFromLongColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 5L).add("lon", 0);
assertEquals("Latitude is not properly parsed", 5d, mapper.readLatitude(columns), 0);
}
@Test
public void testGetLatitudeFromFloatColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 5.3f).add("lon", 0);
assertEquals("Latitude is not properly parsed", 5.3f, mapper.readLatitude(columns), 0);
}
@Test
public void testGetLatitudeFromDoubleColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 5.3D).add("lon", 0);
assertEquals("Latitude is not properly parsed", 5.3d, mapper.readLatitude(columns), 0);
}
@Test
public void testGetLatitudeFromStringColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", "5.3").add("lon", 0);
assertEquals("Latitude is not properly parsed", 5.3d, mapper.readLatitude(columns), 0);
}
@Test
public void testGetLatitudeFromShortColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", new Short("5")).add("lon", 0);
assertEquals("Latitude is not properly parsed", 5d, mapper.readLatitude(columns), 0);
}
@Test(expected = IndexException.class)
public void testGetLatitudeFromUnparseableStringColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", "abc").add("lon", 0);
mapper.readLatitude(columns);
}
@Test
public void testGetLatitudeWithNullColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
assertNull("Latitude is not properly parsed", mapper.readLatitude(Columns.empty()));
}
@Test(expected = IndexException.class)
public void testGetLatitudeWithTooSmallColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", "-91").add("lon", 0);
mapper.readLatitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLatitudeWithTooBigColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", "91").add("lon", 0);
mapper.readLatitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLatitudeWithTooSmallShortColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", new Short("-91")).add("lon", 0);
mapper.readLatitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLatitudeWithTooBigShortColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", new Short("91")).add("lon", 0);
mapper.readLatitude(columns);
}
@Test
public void testGetLongitudeFromNullColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 5).add("lon");
assertNull("Longitude is not properly parsed", mapper.readLongitude(columns));
}
@Test
public void testGetLongitudeFromIntColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", 5);
assertEquals("Longitude is not properly parsed", 5d, mapper.readLongitude(columns), 0);
}
@Test
public void testGetLongitudeFromLongColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", 5L);
assertEquals("Longitude is not properly parsed", 5d, mapper.readLongitude(columns), 0);
}
@Test
public void testGetLongitudeFromFloatColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", 5.3f);
assertEquals("Longitude is not properly parsed", 5.3f, mapper.readLongitude(columns), 0);
}
@Test
public void testGetLongitudeFromDoubleColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", 5.3D);
assertEquals("Longitude is not properly parsed", 5.3d, mapper.readLongitude(columns), 0);
}
@Test
public void testGetLongitudeFromStringColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", "5.3");
assertEquals("Longitude is not properly parsed", 5.3d, mapper.readLongitude(columns), 0);
}
@Test
public void testGetLongitudeFromShortColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", new Short("5"));
assertEquals("Longitude is not properly parsed", 5d, mapper.readLongitude(columns), 0);
}
@Test(expected = IndexException.class)
public void testGetLongitudeFromUnparseableStringColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", "abc");
mapper.readLongitude(columns);
}
@Test
public void testGetLongitudeWithNullColumn() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
assertNull("Longitude is not properly parsed", mapper.readLongitude(Columns.empty()));
}
@Test(expected = IndexException.class)
public void testGetLongitudeWithWrongColumnType() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", UUID.randomUUID());
assertEquals("Longitude is not properly parsed", 5.3d, mapper.readLongitude(columns), 0);
}
@Test(expected = IndexException.class)
public void testGetLongitudeWithTooSmallColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", "-181");
mapper.readLongitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLongitudeWithTooBigColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", "181");
mapper.readLongitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLongitudeWithTooSmallShortColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", new Short("-181"));
mapper.readLongitude(columns);
}
@Test(expected = IndexException.class)
public void testGetLongitudeWithTooBigShortColumnValue() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
Columns columns = Columns.empty().add("lat", 0).add("lon", new Short("181"));
mapper.readLongitude(columns);
}
@Test(expected = IndexException.class)
public void testSortField() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
mapper.sortField("field", false);
}
@Test
public void testAddFields() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").maxLevels(10).build("field");
Columns columns = Columns.empty().add("lat", 20).add("lon", "30");
List<IndexableField> fields = mapper.indexableFields(columns);
assertEquals("Fields are not properly created", 2, fields.size());
}
@Test
public void testAddFieldsWithNullColumns() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").maxLevels(10).build("field");
Columns columns = Columns.empty();
List<IndexableField> fields = mapper.indexableFields(columns);
assertEquals("Fields are not properly created", 0, fields.size());
}
@Test(expected = IndexException.class)
public void testAddFieldsWithNullLatitude() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").maxLevels(10).build("field");
Columns columns = Columns.empty().add("lon", "30");
mapper.indexableFields(columns);
}
@Test(expected = IndexException.class)
public void testAddFieldsWithNullLongitude() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").maxLevels(10).build("field");
Columns columns = Columns.empty().add("lat", 20);
mapper.indexableFields(columns);
}
@Test
public void testExtractAnalyzers() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").build("field");
assertNull("Analyzer must be null", mapper.analyzer);
}
@Test
public void testToString() {
GeoPointMapper mapper = geoPointMapper("lat", "lon").validated(true).maxLevels(7).build("field");
String exp = "GeoPointMapper{field=field, validated=true, latitude=lat, longitude=lon, maxLevels=7}";
assertEquals("Method #toString is wrong", exp, mapper.toString());
}
}
| 5,646 |
3,266 | <filename>quantum gravity/convwave/src/jupyter/plottools.py
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# -----------------------------------------------------------------------------
# FUNCTION DEFINITIONS
# -----------------------------------------------------------------------------
def force_aspect(ax, aspect=1.0):
"""
Stolen from here: https://stackoverflow.com/a/7968690/4100721
Sometimes works to produce plots with the desired aspect ratio.
"""
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
# -----------------------------------------------------------------------------
def plot_spectrogram_label(spectrogram, true_label, pred_label,
grayzones=None, vmin=None, vmax=None):
"""
Take a spectrogram, the true label, and the predicted label, and combine
them into a plot for manual inspection. If grayzones are provided, then
these will be included in the plot.
Args:
spectrogram: 2D numpy array containing the spectrogram
true_label: 1D numpy array containing the true labels for injections
pred_label: 1D numpy array containing the predicted labels
grayzones: 1D numpy array containing the parts that are ignored by
the loss function during training
vmin: Minimum value of the spectrogram
vmax: Maximum valie of the spectrogram
"""
# Fix the size of figure as a whole
plt.gcf().set_size_inches(18, 6, forward=True)
# Define a grid to fix the height ratios of the subplots
gs = gridspec.GridSpec(2, 1, height_ratios=[10, 1])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1], sharex=ax1)
# Plot the spectrogram
ax1.imshow(spectrogram, origin="lower", cmap="Greys_r",
interpolation="none", vmin=vmin, vmax=vmax)
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.xaxis.set_ticks_position('none')
ax1.yaxis.set_ticks_position('none')
force_aspect(ax1, aspect=3.5)
# Plot the vector indicating where there was an injection
ax2.plot(true_label, lw=2, c='C2', label='True')
ax2.plot(pred_label, lw=2, c='C3', label='Pred')
ax2.set_xticklabels([])
ax2.set_yticklabels([])
ax2.xaxis.set_ticks_position('none')
ax2.yaxis.set_ticks_position('none')
# Plot the gray zones
start = None
in_zone = False
for i in range(len(grayzones)):
if not in_zone:
if grayzones[i] == 0:
start = i
in_zone = True
if in_zone:
if grayzones[i] == 1:
ax2.axvspan(start, i, alpha=0.5, color='Orange')
in_zone = False
ax2.set_xlim(0, len(true_label))
ax2.set_ylim(-0.2, 1.2)
plt.tight_layout()
plt.gcf().subplots_adjust(hspace=0.05)
plt.show()
# -----------------------------------------------------------------------------
def create_weights(label, start_size=4, end_size=2):
"""
Create the weights ('grayzones') for a given label.
Args:
label: A vector labeling the pixels that contain an injection
start_size: Number of pixels to ignore at the start of an injection
end_size: Number of pixels to ignore at the end of an injections
Returns: A vector that is 0 for the pixels that should be ignored and 1
for all other pixels.
"""
a = np.logical_xor(label, np.roll(label, 1))
b = np.cumsum(a) % 2
if start_size == 0:
c = np.zeros(label.shape)
else:
c = np.convolve(a * b, np.hstack((np.zeros(start_size - 1),
np.ones(start_size))),
mode="same")
if end_size == 0:
d = np.zeros(label.shape)
else:
d = np.convolve(a * np.logical_not(b),
np.hstack((np.ones(end_size), np.zeros(end_size - 1))),
mode="same")
return np.logical_not(np.logical_or(c, d)).astype('int')
| 1,709 |
2,114 | <reponame>rahogata/Jest
package io.searchbox.core.search.aggregation;
import com.google.gson.JsonObject;
import java.util.Objects;
import static io.searchbox.core.search.aggregation.AggregationField.VALUE;
/**
* @author cfstout
*/
public class CardinalityAggregation extends MetricAggregation {
public static final String TYPE = "cardinality";
private Long cardinality;
public CardinalityAggregation(String name, JsonObject cardinalityAggregation) {
super(name, cardinalityAggregation);
if(cardinalityAggregation.has(String.valueOf(VALUE)) && !cardinalityAggregation.get(String.valueOf(VALUE)).isJsonNull()) {
cardinality = cardinalityAggregation.get(String.valueOf(VALUE)).getAsLong();
}
}
/**
* @return Cardinality
*/
public Long getCardinality() {
return cardinality;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
CardinalityAggregation rhs = (CardinalityAggregation) obj;
return super.equals(obj) && Objects.equals(cardinality, rhs.cardinality);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), cardinality);
}
}
| 551 |
314 | <reponame>GaoX2015/intro_ds
# -*- coding: UTF-8 -*-
"""
此脚本用于展示二分类问题的不同评估指标
"""
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def transLabel(data):
"""
将文字变量转化为数字变量
"""
data["label_code"] = pd.Categorical(data.label).codes
return data
def trainModel(data, features, labels):
"""
搭建逻辑回归模型,并训练模型
"""
model = LogisticRegression(C=1e4)
model.fit(data[features], data[labels])
return model
def readData(path):
"""
使用pandas读取数据
"""
data = pd.read_csv(path)
cols = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week", "label"]
return data[cols]
def logitRegression(data):
"""
训练模型,并画出模型的ROC曲线
"""
data = transLabel(data)
features = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week"]
labels = "label_code"
trainSet, testSet = train_test_split(data, test_size=0.3, random_state=2310)
model = trainModel(trainSet, features, labels)
# 得到预测的概率
preds = model.predict_proba(testSet[features])[:,1]
re = pd.DataFrame()
re["pred_proba"] = preds
re["label"] = testSet[labels].tolist()
return re
def PrecisionRecallFscore(pred, label, beta=1):
"""
计算预测结果的Precision, Recall以及Fscore
"""
bins = np.array([0, 0.5, 1])
tn, fp, fn, tp = np.histogram2d(label, pred, bins=bins)[0].flatten()
precision = tp / (tp + fp)
recall = tp / (tp + fn)
fscore = (1 + beta ** 2) * precision * recall / (beta ** 2 * precision + recall)
return precision, recall, fscore
def AUC(predProb, label):
"""
计算False positive rate, True positive rate和AUC
"""
# 得到False positive rate和True positive rate
fpr, tpr, _ = metrics.roc_curve(label, predProb)
# 得到AUC
auc = metrics.auc(fpr, tpr)
return fpr, tpr, auc
def visualizePrecRecFscoreByAlphas(re):
"""
展示不同的阈值下,模型的Precision, Recall和F1-score
"""
alphas = np.arange(0.1, 1.01, 0.05)
precs = []
recs = []
fscores = []
for alpha in alphas:
pred = re.apply(lambda x: 1 if x["pred_proba"] > alpha else 0, axis=1)
label = re["label"]
prec, rec, fscore = PrecisionRecallFscore(pred, label)
precs.append(prec)
recs.append(rec)
fscores.append(fscore)
# 为在Matplotlib中显示中文,设置特殊字体
plt.rcParams["font.sans-serif"]=["SimHei"]
# 创建一个图形框
fig = plt.figure(figsize=(6, 6), dpi=80)
# 在图形框里只画一幅图
ax = fig.add_subplot(1, 1, 1)
ax.plot(alphas, precs, "r--", label="Precision")
ax.plot(alphas, recs, "k-.", label="Recall")
ax.plot(alphas, fscores, label="F1-score")
ax.set_xlabel(r"$\alpha$")
ax.set_xlim([0.1, 1])
legend = plt.legend(shadow=True)
plt.show()
def visualizePrecRecFscoreByBetas(re):
"""
展示不同的beta下,模型的Precision, Recall和F1-score
"""
betas = np.arange(0, 10, 0.1)
precs = []
recs = []
fscores = []
pred = re.apply(lambda x: 1 if x["pred_proba"] > 0.5 else 0, axis=1)
label = re["label"]
for beta in betas:
prec, rec, fscore = PrecisionRecallFscore(pred, label, beta)
precs.append(prec)
recs.append(rec)
fscores.append(fscore)
# 为在Matplotlib中显示中文,设置特殊字体
plt.rcParams["font.sans-serif"]=["SimHei"]
# 创建一个图形框
fig = plt.figure(figsize=(6, 6), dpi=80)
# 在图形框里只画一幅图
ax = fig.add_subplot(1, 1, 1)
ax.plot(betas, precs, "r--", label="Precision")
ax.plot(betas, recs, "k-.", label="Recall")
ax.plot(betas, fscores, label="F-score")
ax.set_xlabel(r"$\beta$")
legend = plt.legend(shadow=True)
plt.show()
def visualizeRoc(re):
"""
绘制ROC曲线
"""
fpr, tpr, auc = AUC(re["pred_proba"], re["label"])
# 为在Matplotlib中显示中文,设置特殊字体
plt.rcParams["font.sans-serif"]=["SimHei"]
# 创建一个图形框
fig = plt.figure(figsize=(6, 6), dpi=80)
# 在图形框里只画一幅图
ax = fig.add_subplot(1, 1, 1)
# 在Matplotlib中显示中文,需要使用unicode
# 在Python3中,str不需要decode
if sys.version_info[0] == 3:
ax.set_title("%s" % "ROC曲线")
else:
ax.set_title("%s" % "ROC曲线".decode("utf-8"))
ax.set_xlabel("False positive rate")
ax.set_ylabel("True positive rate")
ax.plot([0, 1], [0, 1], "r--")
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
# 在Python3中,str不需要decode
if sys.version_info[0] == 3:
ax.plot(fpr, tpr, "k", label="%s; %s = %0.2f" % ("ROC曲线",
"曲线下面积(AUC)", auc))
else:
ax.plot(fpr, tpr, "k", label="%s; %s = %0.2f" % ("ROC曲线".decode("utf-8"),
"曲线下面积(AUC)".decode("utf-8"), auc))
ax.fill_between(fpr, tpr, color="grey", alpha=0.6)
legend = plt.legend(shadow=True)
plt.show()
def evaluation(re):
"""
用图像化的形式展示评估指标
"""
visualizePrecRecFscoreByAlphas(re)
visualizePrecRecFscoreByBetas(re)
visualizeRoc(re)
def run(dataPath):
"""
训练模型,并使用Precisiion, Recall, F-score以及AUC评估模型
"""
data = readData(dataPath)
re = logitRegression(data)
evaluation(re)
if __name__ == "__main__":
homePath = os.path.dirname(os.path.abspath(__file__))
# Windows下的存储路径与Linux并不相同
if os.name == "nt":
dataPath = "%s\\data\\adult.data" % homePath
else:
dataPath = "%s/data/adult.data" % homePath
run(dataPath)
| 3,078 |
459 | /**
* @file oglplus/images/sphere_bmap.ipp
* @brief Implementation of images::SphereBumpMap
*
* @author <NAME>
*
* Copyright 2010-2015 <NAME>. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <oglplus/lib/incl_begin.ipp>
#include <oglplus/math/vector.hpp>
#include <oglplus/lib/incl_end.ipp>
#include <cassert>
#include <cmath>
namespace oglplus {
namespace images {
OGLPLUS_LIB_FUNC
SphereBumpMap::SphereBumpMap(
SizeType width,
SizeType height,
SizeType xrep,
SizeType yrep
): Image(
width,
height,
1,
4,
&TypeTag<GLfloat>(),
PixelDataFormat::RGBA,
PixelDataInternalFormat::RGBA16F
)
{
assert(width != 0 && height != 0);
assert(xrep != 0 && yrep != 0);
typedef double number;
number one = number(1);
number invw = number(2*xrep)/number(width);
number invh = number(2*yrep)/number(height);
GLsizei hi = width/xrep;
GLsizei hj = height/yrep;
auto p = this->_begin<GLfloat>();
for(GLsizei j=0; j<height; ++j)
{
number y = number((j % hj) - hj/2)*invh;
for(GLsizei i=0; i<width; ++i)
{
number x = number((i % hi) - hi/2)*invw;
number l = std::sqrt(x*x + y*y);
number d = sqrt(one-l*l);
Vector<number, 3> z(0.0, 0.0, one);
Vector<number, 3> n(-x, -y, d);
Vector<number, 3> v = (l >= one)?
z:
Normalized(z+n);
if(l >= one) d = 0;
assert(p != this->_end<GLfloat>());
*p = GLfloat(v.x()); ++p;
*p = GLfloat(v.y()); ++p;
*p = GLfloat(v.z()); ++p;
*p = GLfloat(d); ++p;
}
}
assert(p == this->_end<GLfloat>());
}
} // images
} // oglplus
| 734 |
480 | <reponame>weicao/galaxysql
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.
*/
package org.apache.calcite.sql;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeFieldImpl;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
/**
* @author chenmo.cm
* @date 2018/6/12 下午12:44
*/
public class SqlShowRule extends SqlShow {
private boolean full;
private SqlNode tableName;
public SqlShowRule(SqlParserPos pos, List<SqlSpecialIdentifier> specialIdentifiers, List<SqlNode> operands,
SqlNode like, SqlNode where, SqlNode orderBy, SqlNode limit, boolean full, SqlNode tableName){
super(pos, specialIdentifiers, operands, like, where, orderBy, limit);
this.full = full;
this.tableName = tableName;
}
public SqlShowRule(SqlParserPos pos, List<SqlSpecialIdentifier> specialIdentifiers, List<SqlNode> operands,
SqlNode like, SqlNode where, SqlNode orderBy, SqlNode limit, boolean full, SqlNode tableName, Integer tableNameIndex){
super(pos, specialIdentifiers, operands, like, where, orderBy, limit, tableNameIndex);
this.full = full;
this.tableName = tableName;
}
public static SqlShowRule create(SqlParserPos pos, boolean full, SqlNode tableName, SqlNode where, SqlNode orderBy,
SqlNode limit) {
List<SqlSpecialIdentifier> specialIdentifiers = new LinkedList<>();
if (full) {
specialIdentifiers.add(SqlSpecialIdentifier.FULL);
}
specialIdentifiers.add(SqlSpecialIdentifier.RULE);
List<SqlNode> operands = new ArrayList<>();
if (null != tableName) {
specialIdentifiers.add(SqlSpecialIdentifier.FROM);
operands.add(tableName);
return new SqlShowRule(pos,
specialIdentifiers,
operands,
null,
where,
orderBy,
limit,
full,
tableName,
specialIdentifiers.size() + operands.size() - 1);
}
return new SqlShowRule(pos, specialIdentifiers, operands, null, where, orderBy, limit, full, tableName);
}
public boolean isFull() {
return full;
}
public void setFull(boolean full) {
this.full = full;
}
public SqlNode getTableName() {
return tableName;
}
public void setTableName(SqlNode tableName) {
this.tableName = tableName;
}
@Override
protected boolean showWhere() {
return false;
}
@Override
public SqlOperator getOperator() {
return new SqlShowRuleOperator(full);
}
@Override
public SqlKind getShowKind() {
return SqlKind.SHOW_RULE;
}
public static class SqlShowRuleOperator extends SqlSpecialOperator {
private final boolean full;
public SqlShowRuleOperator(boolean full){
super("SHOW_RULE", SqlKind.SHOW_RULE);
this.full = full;
}
@Override
public RelDataType deriveType(SqlValidator validator, SqlValidatorScope scope, SqlCall call) {
final RelDataTypeFactory typeFactory = validator.getTypeFactory();
List<RelDataTypeFieldImpl> columns = new LinkedList<>();
if (!this.full) {
columns.add(new RelDataTypeFieldImpl("Id", 0, typeFactory.createSqlType(SqlTypeName.INTEGER)));
columns.add(new RelDataTypeFieldImpl("TABLE_NAME", 1, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("BROADCAST", 2, typeFactory.createSqlType(SqlTypeName.BOOLEAN)));
columns.add(new RelDataTypeFieldImpl("DB_PARTITION_KEY",
3,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("DB_PARTITION_POLICY",
4,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("DB_PARTITION_COUNT",
5,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("TB_PARTITION_KEY",
6,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("TB_PARTITION_POLICY",
7,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("TB_PARTITION_COUNT",
8,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
} else {
columns.add(new RelDataTypeFieldImpl("Id", 0, typeFactory.createSqlType(SqlTypeName.INTEGER)));
columns.add(new RelDataTypeFieldImpl("TABLE_NAME", 1, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("BROADCAST", 2, typeFactory.createSqlType(SqlTypeName.BOOLEAN)));
columns.add(new RelDataTypeFieldImpl("JOIN_GROUP", 3, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("ALLOW_FULL_TABLE_SCAN",
4,
typeFactory.createSqlType(SqlTypeName.BOOLEAN)));
columns.add(new RelDataTypeFieldImpl("DB_NAME_PATTERN",
5,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("DB_RULES_STR", 6, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("TB_NAME_PATTERN",
7,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("TB_RULES_STR", 8, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("PARTITION_KEYS",
9,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("DEFAULT_DB_INDEX",
10,
typeFactory.createSqlType(SqlTypeName.VARCHAR)));
}
return typeFactory.createStructType(columns);
}
}
}
| 3,302 |
503 | <reponame>Hugo759/ArrayVisualizer
package array.visualizer.utils;
import array.visualizer.ArrayController;
import static array.visualizer.ArrayVisualizer.*;
/**
*
* @author S630690
*/
public class Swaps {
public static void swap(final ArrayController ac, int i, int j) {
ac.marked.set(1, i);
ac.marked.set(2, j);
ac.aa+=2;
//if(Math.random()*8<1.0)
//sleep(1);
// TODO Auto-generated method stub
int temp = ac.array[i];
ac.array[i] = ac.array[j];
ac.array[j] = temp;
}
public static void swap(final ArrayController ac, int i, int j, double pause) {
ac.marked.set(1, i);
ac.marked.set(2, j);
ac.aa+=2;
sleep(pause);
// TODO Auto-generated method stub
int temp = ac.array[i];
ac.array[i] = ac.array[j];
ac.array[j] = temp;
}
public static void swapnm(final ArrayController ac, int i, int j, double pause) {
sleep(pause);
ac.aa+=2;
int temp = ac.array[i];
ac.array[i] = ac.array[j];
ac.array[j] = temp;
}
public static void swapUpTo(final ArrayController ac, int pos, int to, double pause){
if(to - pos > 0)
for(int i = pos; i < to; i++)
swap(ac, i, i+1, pause);
else
for(int i = pos; i > to; i--)
swap(ac, i, i-1, pause);
}
public static void swapUpToNM(final ArrayController ac, int pos, int to, double pause){
if(to - pos > 0)
for(int i = pos; i < to; i++)
swapnm(ac, i, i+1, pause);
else
for(int i = pos; i > to; i--)
swapnm(ac, i, i-1, pause);
}
public static void swapUp(final ArrayController ac, int pos, double pause) {
for(int i = pos; i < ac.length; i++)
swap(ac, i, i+1, pause);
}
}
| 959 |
3,702 | /* -------------------------------------------------------------------------
*
* objectaccess.c
* functions for object_access_hook on various events
*
* Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
/*
* Hook on object accesses. This is intended as infrastructure for security
* and logging plugins.
*/
object_access_hook_type object_access_hook = NULL;
/*
* RunObjectPostCreateHook
*
* It is entrypoint of OAT_POST_CREATE event
*/
void
RunObjectPostCreateHook(Oid classId, Oid objectId, int subId,
bool is_internal)
{
ObjectAccessPostCreate pc_arg;
/* caller should check, but just in case... */
Assert(object_access_hook != NULL);
memset(&pc_arg, 0, sizeof(ObjectAccessPostCreate));
pc_arg.is_internal = is_internal;
(*object_access_hook) (OAT_POST_CREATE,
classId, objectId, subId,
(void *) &pc_arg);
}
/*
* RunObjectDropHook
*
* It is entrypoint of OAT_DROP event
*/
void
RunObjectDropHook(Oid classId, Oid objectId, int subId,
int dropflags)
{
ObjectAccessDrop drop_arg;
/* caller should check, but just in case... */
Assert(object_access_hook != NULL);
memset(&drop_arg, 0, sizeof(ObjectAccessDrop));
drop_arg.dropflags = dropflags;
(*object_access_hook) (OAT_DROP,
classId, objectId, subId,
(void *) &drop_arg);
}
/*
* RunObjectPostAlterHook
*
* It is entrypoint of OAT_POST_ALTER event
*/
void
RunObjectPostAlterHook(Oid classId, Oid objectId, int subId,
Oid auxiliaryId, bool is_internal)
{
ObjectAccessPostAlter pa_arg;
/* caller should check, but just in case... */
Assert(object_access_hook != NULL);
memset(&pa_arg, 0, sizeof(ObjectAccessPostAlter));
pa_arg.auxiliary_id = auxiliaryId;
pa_arg.is_internal = is_internal;
(*object_access_hook) (OAT_POST_ALTER,
classId, objectId, subId,
(void *) &pa_arg);
}
/*
* RunNamespaceSearchHook
*
* It is entrypoint of OAT_NAMESPACE_SEARCH event
*/
bool
RunNamespaceSearchHook(Oid objectId, bool ereport_on_violation)
{
ObjectAccessNamespaceSearch ns_arg;
/* caller should check, but just in case... */
Assert(object_access_hook != NULL);
memset(&ns_arg, 0, sizeof(ObjectAccessNamespaceSearch));
ns_arg.ereport_on_violation = ereport_on_violation;
ns_arg.result = true;
(*object_access_hook) (OAT_NAMESPACE_SEARCH,
NamespaceRelationId, objectId, 0,
(void *) &ns_arg);
return ns_arg.result;
}
/*
* RunFunctionExecuteHook
*
* It is entrypoint of OAT_FUNCTION_EXECUTE event
*/
void
RunFunctionExecuteHook(Oid objectId)
{
/* caller should check, but just in case... */
Assert(object_access_hook != NULL);
(*object_access_hook) (OAT_FUNCTION_EXECUTE,
ProcedureRelationId, objectId, 0,
NULL);
}
| 1,093 |
1,503 | <gh_stars>1000+
import sys
import warnings
from enum import Enum
import numpy as np
import pytest
from testfixtures import LogCapture
from greykite.common.constants import LOGGER_NAME
from greykite.common.constants import TIME_COL
from greykite.common.constants import VALUE_COL
from greykite.common.data_loader import DataLoader
from greykite.common.evaluation import EvaluationMetricEnum
from greykite.common.python_utils import assert_equal
from greykite.common.testing_utils import generate_df_for_tests
from greykite.common.testing_utils import generate_df_with_reg_for_tests
from greykite.framework.templates.autogen.forecast_config import ComputationParam
from greykite.framework.templates.autogen.forecast_config import EvaluationMetricParam
from greykite.framework.templates.autogen.forecast_config import EvaluationPeriodParam
from greykite.framework.templates.autogen.forecast_config import ForecastConfig
from greykite.framework.templates.autogen.forecast_config import MetadataParam
from greykite.framework.templates.autogen.forecast_config import ModelComponentsParam
from greykite.framework.templates.forecaster import Forecaster
from greykite.framework.templates.model_templates import ModelTemplate
from greykite.framework.templates.model_templates import ModelTemplateEnum
from greykite.framework.templates.prophet_template import ProphetTemplate
from greykite.framework.templates.silverkite_template import SilverkiteTemplate
from greykite.framework.templates.simple_silverkite_template import SimpleSilverkiteTemplate
from greykite.framework.templates.simple_silverkite_template_config import SILVERKITE_COMPONENT_KEYWORDS
from greykite.framework.templates.simple_silverkite_template_config import SimpleSilverkiteTemplateOptions
from greykite.framework.utils.framework_testing_utils import assert_basic_pipeline_equal
from greykite.framework.utils.framework_testing_utils import assert_forecast_pipeline_result_equal
from greykite.framework.utils.framework_testing_utils import check_forecast_pipeline_result
from greykite.framework.utils.result_summary import summarize_grid_search_results
try:
import fbprophet # noqa
except ModuleNotFoundError:
pass
@pytest.fixture
def df_config():
data = generate_df_with_reg_for_tests(
freq="W-MON",
periods=140,
remove_extra_cols=True,
mask_test_actuals=True)
reg_cols = ["regressor1", "regressor2", "regressor_categ"]
keep_cols = [TIME_COL, VALUE_COL] + reg_cols
df = data["df"][keep_cols]
model_template = "SILVERKITE"
evaluation_metric = EvaluationMetricParam(
cv_selection_metric=EvaluationMetricEnum.MeanAbsoluteError.name,
agg_periods=7,
agg_func=np.max,
null_model_params={
"strategy": "quantile",
"constant": None,
"quantile": 0.5
}
)
evaluation_period = EvaluationPeriodParam(
test_horizon=10,
periods_between_train_test=5,
cv_horizon=4,
cv_min_train_periods=80,
cv_expanding_window=False,
cv_periods_between_splits=20,
cv_periods_between_train_test=3,
cv_max_splits=3
)
model_components = ModelComponentsParam(
regressors={
"regressor_cols": reg_cols
},
custom={
"fit_algorithm_dict": {
"fit_algorithm": "ridge",
"fit_algorithm_params": {"cv": 2}
}
}
)
computation = ComputationParam(
verbose=2
)
forecast_horizon = 27
coverage = 0.90
config = ForecastConfig(
model_template=model_template,
computation_param=computation,
coverage=coverage,
evaluation_metric_param=evaluation_metric,
evaluation_period_param=evaluation_period,
forecast_horizon=forecast_horizon,
model_components_param=model_components
)
return {
"df": df,
"config": config,
"model_template": model_template,
"reg_cols": reg_cols,
}
class MySimpleSilverkiteTemplate(SimpleSilverkiteTemplate):
"""Same as `SimpleSilverkiteTemplate`, but with different
default model template.
"""
DEFAULT_MODEL_TEMPLATE = "SILVERKITE_WEEKLY"
class MyModelTemplateEnum(Enum):
"""Custom version of TemplateEnum for test cases"""
MYSILVERKITE = ModelTemplate(
template_class=MySimpleSilverkiteTemplate,
description="My own version of Silverkite.")
SILVERKITE = ModelTemplate(
template_class=SimpleSilverkiteTemplate,
description="My own version of Silverkite.")
class MissingSimpleSilverkiteTemplateEnum(Enum):
"""Custom version of TemplateEnum for test cases.
SimpleSilverkiteTemplate is not included.
"""
SK = ModelTemplate(
template_class=SilverkiteTemplate,
description="Silverkite template.")
PROPHET = ModelTemplate(
template_class=ProphetTemplate,
description="Prophet template.")
def test_init():
"""Tests constructor"""
forecaster = Forecaster()
assert forecaster.model_template_enum == ModelTemplateEnum
assert forecaster.default_model_template_name == "SILVERKITE"
forecaster = Forecaster(
model_template_enum=MyModelTemplateEnum,
default_model_template_name="MYSILVERKITE"
)
assert forecaster.model_template_enum == MyModelTemplateEnum
assert forecaster.default_model_template_name == "MYSILVERKITE"
def test_get_config_with_default_model_template_and_components():
"""Tests `__get_config_with_default_model_template_and_components`"""
forecaster = Forecaster()
config = forecaster._Forecaster__get_config_with_default_model_template_and_components()
assert config == ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
model_components_param=ModelComponentsParam()
)
# Overrides `default_model_template_name`, unnests `model_components_param`.
forecaster = Forecaster(default_model_template_name="SK")
config = ForecastConfig(
model_components_param=[ModelComponentsParam()]
)
config = forecaster._Forecaster__get_config_with_default_model_template_and_components(config)
assert config == ForecastConfig(
model_template=ModelTemplateEnum.SK.name,
model_components_param=ModelComponentsParam()
)
# Overrides `model_template_enum` and `default_model_template_name`
forecaster = Forecaster(
model_template_enum=MyModelTemplateEnum,
default_model_template_name="MYSILVERKITE"
)
config = forecaster._Forecaster__get_config_with_default_model_template_and_components()
assert config == ForecastConfig(
model_template=MyModelTemplateEnum.MYSILVERKITE.name,
model_components_param=ModelComponentsParam()
)
def test_get_template_class():
"""Tests `__get_template_class`"""
forecaster = Forecaster()
assert forecaster._Forecaster__get_template_class() == SimpleSilverkiteTemplate
assert forecaster._Forecaster__get_template_class(
config=ForecastConfig(model_template=ModelTemplateEnum.SILVERKITE_WEEKLY.name)) == SimpleSilverkiteTemplate
if "fbprophet" in sys.modules:
assert forecaster._Forecaster__get_template_class(
config=ForecastConfig(model_template=ModelTemplateEnum.PROPHET.name)) == ProphetTemplate
assert forecaster._Forecaster__get_template_class(
config=ForecastConfig(model_template=ModelTemplateEnum.SK.name)) == SilverkiteTemplate
# list `model_template`
model_template = [
ModelTemplateEnum.SILVERKITE.name,
ModelTemplateEnum.SILVERKITE_DAILY_90.name,
SimpleSilverkiteTemplateOptions()]
forecaster = Forecaster()
assert forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template)) == SimpleSilverkiteTemplate
# `model_template` name is wrong
model_template = "SOME_TEMPLATE"
with pytest.raises(ValueError, match=f"Model Template '{model_template}' is not recognized! "
f"Must be one of: SILVERKITE, SILVERKITE_WITH_AR, "
f"SILVERKITE_DAILY_1_CONFIG_1, SILVERKITE_DAILY_1_CONFIG_2, SILVERKITE_DAILY_1_CONFIG_3, "
f"SILVERKITE_DAILY_1, SILVERKITE_DAILY_90, "
f"SILVERKITE_WEEKLY, SILVERKITE_HOURLY_1, SILVERKITE_HOURLY_24, "
f"SILVERKITE_HOURLY_168, SILVERKITE_HOURLY_336, SILVERKITE_EMPTY"):
forecaster = Forecaster()
forecaster._Forecaster__get_template_class(
config=ForecastConfig(model_template=model_template))
# List of `model_template` that include names not compatible with `SimpleSilverkiteTemplate`.
model_template = [
ModelTemplateEnum.SK.name,
ModelTemplateEnum.SILVERKITE.name,
ModelTemplateEnum.SILVERKITE_DAILY_90.name,
SimpleSilverkiteTemplateOptions()]
with pytest.raises(ValueError, match="All model templates must use the same template class"):
forecaster = Forecaster()
forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template))
# list of `model_template` not supported by template class
model_template = [ModelTemplateEnum.SK.name, ModelTemplateEnum.SK.name]
with pytest.raises(ValueError, match="The template class <class "
"'greykite.framework.templates.silverkite_template.SilverkiteTemplate'> "
"does not allow `model_template` to be a list"):
forecaster = Forecaster()
forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template))
# List of `model_components_param` not compatible with `model_template`.
model_template = ModelTemplateEnum.SK.name
config = ForecastConfig(
model_template=model_template,
model_components_param=[ModelComponentsParam(), ModelComponentsParam()]
)
with pytest.raises(ValueError, match=f"Model template {model_template} does not support a list of `ModelComponentsParam`."):
forecaster = Forecaster()
forecaster._Forecaster__get_template_class(config=config)
# List of a single `model_components_param` is acceptable for a model template
# that does not accept multiple `model_components_param`.
forecaster = Forecaster()
config = ForecastConfig(
model_template=model_template,
model_components_param=[ModelComponentsParam()]
)
forecaster._Forecaster__get_template_class(config=config)
# List of multiple `model_components_param` is accepted by SILVERKITE
config = ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
model_components_param=[ModelComponentsParam(), ModelComponentsParam()]
)
forecaster._Forecaster__get_template_class(config=config)
# Error for unrecognized model template when there is no simple silverkite template
model_template = "UNKNOWN"
with pytest.raises(ValueError, match=rf"Model Template '{model_template}' is not recognized! "
rf"Must be one of: SK, PROPHET\."):
forecaster = Forecaster(
model_template_enum=MissingSimpleSilverkiteTemplateEnum,
default_model_template_name="SK",
)
forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template))
# Custom `model_template_enum`
forecaster = Forecaster(
model_template_enum=MyModelTemplateEnum,
default_model_template_name="MYSILVERKITE",
)
assert forecaster._Forecaster__get_template_class() == MySimpleSilverkiteTemplate
if "fbprophet" in sys.modules:
model_template = ModelTemplateEnum.PROPHET.name # `model_template` name is wrong
with pytest.raises(ValueError, match=f"Model Template '{model_template}' is not recognized! "
f"Must be one of: MYSILVERKITE, SILVERKITE or satisfy the `SimpleSilverkiteTemplate` rules."):
forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template))
model_template = SimpleSilverkiteTemplateOptions() # dataclass
with LogCapture(LOGGER_NAME) as log_capture:
forecaster._Forecaster__get_template_class(config=ForecastConfig(model_template=model_template))
log_capture.check(
(LOGGER_NAME,
'DEBUG',
'Model template SimpleSilverkiteTemplateOptions(freq=<SILVERKITE_FREQ.DAILY: '
"'DAILY'>, seas=<SILVERKITE_SEAS.LT: 'LT'>, gr=<SILVERKITE_GR.LINEAR: "
"'LINEAR'>, cp=<SILVERKITE_CP.NONE: 'NONE'>, hol=<SILVERKITE_HOL.NONE: "
"'NONE'>, feaset=<SILVERKITE_FEASET.OFF: 'OFF'>, "
"algo=<SILVERKITE_ALGO.LINEAR: 'LINEAR'>, ar=<SILVERKITE_AR.OFF: 'OFF'>, "
"dsi=<SILVERKITE_DSI.AUTO: 'AUTO'>, wsi=<SILVERKITE_WSI.AUTO: 'AUTO'>) is "
'not found in the template enum. Checking if model template is suitable for '
'`SimpleSilverkiteTemplate`.'),
(LOGGER_NAME,
'DEBUG',
'Multiple template classes could be used for the model template '
"SimpleSilverkiteTemplateOptions(freq=<SILVERKITE_FREQ.DAILY: 'DAILY'>, "
"seas=<SILVERKITE_SEAS.LT: 'LT'>, gr=<SILVERKITE_GR.LINEAR: 'LINEAR'>, "
"cp=<SILVERKITE_CP.NONE: 'NONE'>, hol=<SILVERKITE_HOL.NONE: 'NONE'>, "
"feaset=<SILVERKITE_FEASET.OFF: 'OFF'>, algo=<SILVERKITE_ALGO.LINEAR: "
"'LINEAR'>, ar=<SILVERKITE_AR.OFF: 'OFF'>, dsi=<SILVERKITE_DSI.AUTO: "
"'AUTO'>, wsi=<SILVERKITE_WSI.AUTO: 'AUTO'>): [<class "
"'test_forecaster.MySimpleSilverkiteTemplate'>, <class "
"'greykite.framework.templates.simple_silverkite_template.SimpleSilverkiteTemplate'>]"),
(LOGGER_NAME,
'DEBUG',
'Using template class <class '
"'test_forecaster.MySimpleSilverkiteTemplate'> "
'for the model template '
"SimpleSilverkiteTemplateOptions(freq=<SILVERKITE_FREQ.DAILY: 'DAILY'>, "
"seas=<SILVERKITE_SEAS.LT: 'LT'>, gr=<SILVERKITE_GR.LINEAR: 'LINEAR'>, "
"cp=<SILVERKITE_CP.NONE: 'NONE'>, hol=<SILVERKITE_HOL.NONE: 'NONE'>, "
"feaset=<SILVERKITE_FEASET.OFF: 'OFF'>, algo=<SILVERKITE_ALGO.LINEAR: "
"'LINEAR'>, ar=<SILVERKITE_AR.OFF: 'OFF'>, dsi=<SILVERKITE_DSI.AUTO: "
"'AUTO'>, wsi=<SILVERKITE_WSI.AUTO: 'AUTO'>)"))
def test_apply_forecast_config(df_config):
"""Tests `apply_forecast_config`"""
df = df_config["df"]
config = df_config["config"]
model_template = df_config["model_template"]
reg_cols = df_config["reg_cols"]
# The same class can be re-used. `df` and `config` are taken from the function call
# to `apply_forecast_config`. Only `model_template_enum` and
# `default_model_template_name` are persistent in the state.
forecaster = Forecaster()
# no config
with warnings.catch_warnings():
warnings.simplefilter("ignore")
pipeline_params = forecaster.apply_forecast_config(
df=df)
template_class = SimpleSilverkiteTemplate # based on `default_model_template_name`
expected_pipeline_params = template_class().apply_template_for_pipeline_params(
df=df)
assert_basic_pipeline_equal(pipeline_params.pop("pipeline"), expected_pipeline_params.pop("pipeline"))
assert_equal(pipeline_params, expected_pipeline_params)
assert forecaster.config is not None
assert forecaster.template_class == template_class
assert isinstance(forecaster.template, forecaster.template_class)
assert forecaster.pipeline_params is not None
# custom config
with warnings.catch_warnings():
warnings.simplefilter("ignore")
pipeline_params = forecaster.apply_forecast_config(
df=df,
config=config)
template_class = ModelTemplateEnum[model_template].value.template_class # SimpleSilverkiteTemplate
expected_pipeline_params = template_class().apply_template_for_pipeline_params(
df,
config)
expected_pipeline = expected_pipeline_params.pop("pipeline")
assert_basic_pipeline_equal(pipeline_params.pop("pipeline"), expected_pipeline)
assert_equal(pipeline_params, expected_pipeline_params)
# Custom `model_template_enum`. Same result, because
# `MySimpleSilverkiteTemplate` has the same apply_template_for_pipeline_params
# as `SimpleSilverkiteTemplate`.
forecaster = Forecaster(model_template_enum=MyModelTemplateEnum)
pipeline_params = forecaster.apply_forecast_config(df=df, config=config)
assert_basic_pipeline_equal(pipeline_params.pop("pipeline"), expected_pipeline)
assert_equal(pipeline_params, expected_pipeline_params)
if "fbprophet" in sys.modules:
# `model_component` of config is incompatible with model_template
forecaster = Forecaster()
config = ForecastConfig(
model_template=ModelTemplateEnum.PROPHET.name,
model_components_param=ModelComponentsParam(
regressors={
"regressor_cols": reg_cols
}
)
)
with pytest.raises(ValueError) as record:
forecaster.apply_forecast_config(df=df, config=config)
assert "Unexpected key(s) found: {\'regressor_cols\'}. The valid keys are: " \
"dict_keys([\'add_regressor_dict\'])" in str(record)
# metadata of config is incompatible with df
df = df.rename(columns={TIME_COL: "some_time_col", VALUE_COL: "some_value_col"})
with pytest.raises(ValueError, match="ts column is not in input data"):
forecaster.apply_forecast_config(df=df, config=config)
def test_run_forecast_config():
"""Tests `run_forecast_config`"""
data = generate_df_for_tests(freq="H", periods=14*24)
df = data["df"]
# Checks if exception is raised
with pytest.raises(ValueError, match="is not recognized"):
forecaster = Forecaster()
forecaster.run_forecast_config(df=df, config=ForecastConfig(model_template="unknown_template"))
with pytest.raises(ValueError, match="is not recognized"):
forecaster = Forecaster()
forecaster.run_forecast_json(df=df, json_str="""{ "model_template": "unknown_template" }""")
# All run_forecast_config* functions return the same result for the default config,
# call forecast_pipeline, and return a result with the proper format.
np.random.seed(123)
forecaster = Forecaster()
default_result = forecaster.run_forecast_config(df=df)
score_func = EvaluationMetricEnum.MeanAbsolutePercentError.name
check_forecast_pipeline_result(
default_result,
coverage=None,
strategy=None,
score_func=score_func,
greater_is_better=False)
assert_equal(forecaster.forecast_result, default_result)
np.random.seed(123)
forecaster = Forecaster()
json_result = forecaster.run_forecast_json(df=df)
check_forecast_pipeline_result(
json_result,
coverage=None,
strategy=None,
score_func=score_func,
greater_is_better=False)
assert_forecast_pipeline_result_equal(json_result, default_result, rel=0.02)
def test_run_forecast_config_custom():
"""Tests `run_forecast_config` on weekly data with custom config:
- numeric and categorical regressors
- coverage
- null model
"""
data = generate_df_with_reg_for_tests(
freq="W-MON",
periods=140,
remove_extra_cols=True,
mask_test_actuals=True)
reg_cols = ["regressor1", "regressor2", "regressor_categ"]
keep_cols = [TIME_COL, VALUE_COL] + reg_cols
df = data["df"][keep_cols]
metric = EvaluationMetricEnum.MeanAbsoluteError
evaluation_metric = EvaluationMetricParam(
cv_selection_metric=metric.name,
agg_periods=7,
agg_func=np.max,
null_model_params={
"strategy": "quantile",
"constant": None,
"quantile": 0.5
}
)
evaluation_period = EvaluationPeriodParam(
test_horizon=10,
periods_between_train_test=5,
cv_horizon=4,
cv_min_train_periods=80,
cv_expanding_window=False,
cv_periods_between_splits=20,
cv_periods_between_train_test=3,
cv_max_splits=3
)
model_components = ModelComponentsParam(
regressors={
"regressor_cols": reg_cols
},
custom={
"fit_algorithm_dict": {
"fit_algorithm": "ridge",
"fit_algorithm_params": {"cv": 2}
}
}
)
computation = ComputationParam(
verbose=2
)
forecast_horizon = 27
coverage = 0.90
forecast_config = ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
computation_param=computation,
coverage=coverage,
evaluation_metric_param=evaluation_metric,
evaluation_period_param=evaluation_period,
forecast_horizon=forecast_horizon,
model_components_param=model_components
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
forecaster = Forecaster()
result = forecaster.run_forecast_config(
df=df,
config=forecast_config)
mse = EvaluationMetricEnum.RootMeanSquaredError.get_metric_name()
q80 = EvaluationMetricEnum.Quantile80.get_metric_name()
assert result.backtest.test_evaluation[mse] == pytest.approx(2.976, rel=1e-2)
assert result.backtest.test_evaluation[q80] == pytest.approx(1.360, rel=1e-2)
assert result.forecast.train_evaluation[mse] == pytest.approx(2.224, rel=1e-2)
assert result.forecast.train_evaluation[q80] == pytest.approx(0.941, rel=1e-2)
check_forecast_pipeline_result(
result,
coverage=coverage,
strategy=None,
score_func=metric.name,
greater_is_better=False)
with pytest.raises(KeyError, match="missing_regressor"):
model_components = ModelComponentsParam(
regressors={
"regressor_cols": ["missing_regressor"]
}
)
forecaster = Forecaster()
result = forecaster.run_forecast_config(
df=df,
config=ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
model_components_param=model_components
)
)
check_forecast_pipeline_result(
result,
coverage=None,
strategy=None,
score_func=metric.get_metric_func(),
greater_is_better=False)
def test_run_forecast_json():
"""Tests:
- no coverage
- hourly data (2+ years)
- default `hyperparameter_grid` (all interaction terms enabled)
"""
# sets random state for consistent comparison
data = generate_df_for_tests(
freq="H",
periods=700*24)
df = data["train_df"]
json_str = """{
"model_template": "SILVERKITE",
"forecast_horizon": 3359,
"model_components_param": {
"custom": {
"fit_algorithm_dict": {
"fit_algorithm": "linear"
}
}
}
}"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
forecaster = Forecaster()
result = forecaster.run_forecast_json(
df=df,
json_str=json_str)
mse = EvaluationMetricEnum.RootMeanSquaredError.get_metric_name()
q80 = EvaluationMetricEnum.Quantile80.get_metric_name()
assert result.backtest.test_evaluation[mse] == pytest.approx(2.120, rel=0.03)
assert result.backtest.test_evaluation[q80] == pytest.approx(0.863, rel=0.02)
assert result.forecast.train_evaluation[mse] == pytest.approx(1.975, rel=0.02)
assert result.forecast.train_evaluation[q80] == pytest.approx(0.786, rel=1e-2)
check_forecast_pipeline_result(
result,
coverage=None,
strategy=None,
score_func=EvaluationMetricEnum.MeanAbsolutePercentError.name,
greater_is_better=False)
def test_run_forecast_config_with_single_simple_silverkite_template():
# The generic name of single simple silverkite templates are not added to `ModelTemplateEnum`,
# therefore we test if these are recognized.
data = generate_df_for_tests(freq="D", periods=365)
df = data["df"]
metric = EvaluationMetricEnum.MeanAbsoluteError
evaluation_metric = EvaluationMetricParam(
cv_selection_metric=metric.name,
agg_periods=7,
agg_func=np.max,
null_model_params={
"strategy": "quantile",
"constant": None,
"quantile": 0.5
}
)
evaluation_period = EvaluationPeriodParam(
test_horizon=10,
periods_between_train_test=5,
cv_horizon=4,
cv_min_train_periods=80,
cv_expanding_window=False,
cv_periods_between_splits=20,
cv_periods_between_train_test=3,
cv_max_splits=2
)
model_components = ModelComponentsParam(
hyperparameter_override=[
{"estimator__yearly_seasonality": 1},
{"estimator__yearly_seasonality": 2}
]
)
computation = ComputationParam(
verbose=2
)
forecast_horizon = 27
coverage = 0.90
single_template_class = SimpleSilverkiteTemplateOptions(
freq=SILVERKITE_COMPONENT_KEYWORDS.FREQ.value.DAILY,
seas=SILVERKITE_COMPONENT_KEYWORDS.SEAS.value.NONE
)
forecast_config = ForecastConfig(
model_template=[single_template_class, "DAILY_ALGO_SGD", "SILVERKITE_DAILY_90"],
computation_param=computation,
coverage=coverage,
evaluation_metric_param=evaluation_metric,
evaluation_period_param=evaluation_period,
forecast_horizon=forecast_horizon,
model_components_param=model_components
)
forecaster = Forecaster()
result = forecaster.run_forecast_config(
df=df,
config=forecast_config)
summary = summarize_grid_search_results(result.grid_search)
# single_template_class is 1 template,
# "DAILY_ALGO_SGD" is 1 template and "SILVERKITE_DAILY_90" has 4 templates.
# With 2 items in `hyperparameter_override, there should be a total of 12 cases.
assert summary.shape[0] == 12
# Tests functionality for single template class only.
forecast_config = ForecastConfig(
model_template=single_template_class,
computation_param=computation,
coverage=coverage,
evaluation_metric_param=evaluation_metric,
evaluation_period_param=evaluation_period,
forecast_horizon=forecast_horizon
)
forecaster = Forecaster()
pipeline_parameters = forecaster.apply_forecast_config(
df=df,
config=forecast_config
)
assert_equal(
actual=pipeline_parameters["hyperparameter_grid"],
expected={
"estimator__time_properties": [None],
"estimator__origin_for_time_vars": [None],
"estimator__train_test_thresh": [None],
"estimator__training_fraction": [None],
"estimator__fit_algorithm_dict": [{"fit_algorithm": "linear", "fit_algorithm_params": None}],
"estimator__holidays_to_model_separately": [[]],
"estimator__holiday_lookup_countries": [[]],
"estimator__holiday_pre_num_days": [0],
"estimator__holiday_post_num_days": [0],
"estimator__holiday_pre_post_num_dict": [None],
"estimator__daily_event_df_dict": [None],
"estimator__changepoints_dict": [None],
"estimator__seasonality_changepoints_dict": [None],
"estimator__yearly_seasonality": [0],
"estimator__quarterly_seasonality": [0],
"estimator__monthly_seasonality": [0],
"estimator__weekly_seasonality": [0],
"estimator__daily_seasonality": [0],
"estimator__max_daily_seas_interaction_order": [0],
"estimator__max_weekly_seas_interaction_order": [2],
"estimator__autoreg_dict": [None],
"estimator__simulation_num": [10],
"estimator__lagged_regressor_dict": [None],
"estimator__min_admissible_value": [None],
"estimator__max_admissible_value": [None],
"estimator__normalize_method": [None],
"estimator__uncertainty_dict": [None],
"estimator__growth_term": ["linear"],
"estimator__regressor_cols": [[]],
"estimator__feature_sets_enabled": [False],
"estimator__extra_pred_cols": [[]],
"estimator__drop_pred_cols": [None],
"estimator__explicit_pred_cols": [None],
"estimator__regression_weight_col": [None],
},
ignore_keys={"estimator__time_properties": None}
)
def test_estimator_plot_components_from_forecaster():
"""Tests estimator's plot_components function after the Forecaster has set everything up at the top most level"""
# Test with real data (Female-births) via model template
dl = DataLoader()
data_path = dl.get_data_home(data_sub_dir="daily")
df = dl.get_df(data_path=data_path, data_name="daily_female_births")
metadata = MetadataParam(time_col="Date", value_col="Births", freq="D")
model_components = ModelComponentsParam(
seasonality={
"yearly_seasonality": True,
"quarterly_seasonality": True,
"weekly_seasonality": True,
"daily_seasonality": False
}
)
result = Forecaster().run_forecast_config(
df=df,
config=ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
forecast_horizon=30, # forecast 1 month
coverage=0.95, # 95% prediction intervals
metadata_param=metadata,
model_components_param=model_components
)
)
estimator = result.model.steps[-1][-1]
assert estimator.plot_components()
def test_estimator_get_coef_summary_from_forecaster():
"""Tests model summary for silverkite model with missing values in value_col after everything is setup by Forecaster"""
dl = DataLoader()
df_pt = dl.load_peyton_manning()
config = ForecastConfig().from_dict(dict(
model_template=ModelTemplateEnum.SILVERKITE.name,
forecast_horizon=10,
metadata_param=dict(
time_col="ts",
value_col="y",
freq="D"
),
model_components_param=dict(
custom={
"fit_algorithm_dict": {"fit_algorithm": "linear"}
}
)
))
result = Forecaster().run_forecast_config(
df=df_pt[:365], # shortens df to speed up
config=config
)
summary = result.model[-1].summary()
x = summary.get_coef_summary(
is_intercept=True,
return_df=True)
assert x.shape[0] == 1
summary.get_coef_summary(is_time_feature=True)
summary.get_coef_summary(is_event=True)
summary.get_coef_summary(is_trend=True)
summary.get_coef_summary(is_interaction=True)
x = summary.get_coef_summary(is_lag=True)
assert x is None
x = summary.get_coef_summary(
is_trend=True,
is_seasonality=False,
is_interaction=False,
return_df=True)
assert all([":" not in col for col in x["Pred_col"].tolist()])
assert "ct1" in x["Pred_col"].tolist()
assert "sin1_ct1_yearly" not in x["Pred_col"].tolist()
x = summary.get_coef_summary(return_df=True)
assert x.shape[0] == summary.info_dict["coef_summary_df"].shape[0]
| 13,870 |
623 | // Copyright (C) 2018 The Android Open Source Project
//
// 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.
package com.google.gerrit.acceptance.rest.change;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.GitUtil.assertPushOk;
import static com.google.gerrit.acceptance.GitUtil.pushHead;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.GitUtil;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.testsuite.project.ProjectOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.entities.Project;
import com.google.gerrit.entities.RefNames;
import com.google.gerrit.extensions.api.projects.ConfigInput;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo;
import com.google.gerrit.extensions.client.InheritableBoolean;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.ChangeInput;
import com.google.inject.Inject;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.PushResult;
import org.junit.Test;
public class WorkInProgressByDefaultIT extends AbstractDaemonTest {
@Inject private ProjectOperations projectOperations;
@Inject private RequestScopeOperations requestScopeOperations;
@Test
public void createChangeWithWorkInProgressByDefaultForProjectDisabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
ChangeInfo info =
gApi.changes().create(new ChangeInput(project.get(), "master", "empty change")).get();
assertThat(info.workInProgress).isNull();
}
@Test
public void createChangeWithWorkInProgressByDefaultForProjectEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForProject(project);
ChangeInput input = new ChangeInput(project.get(), "master", "empty change");
assertThat(gApi.changes().create(input).get().workInProgress).isTrue();
}
@Test
public void createChangeWithWorkInProgressByDefaultForUserEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForUser();
ChangeInput input = new ChangeInput(project.get(), "master", "empty change");
assertThat(gApi.changes().create(input).get().workInProgress).isTrue();
}
@Test
public void createChangeBypassWorkInProgressByDefaultForProjectEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForProject(project);
ChangeInput input = new ChangeInput(project.get(), "master", "empty change");
input.workInProgress = false;
assertThat(gApi.changes().create(input).get().workInProgress).isNull();
}
@Test
public void createChangeBypassWorkInProgressByDefaultForUserEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForUser();
ChangeInput input = new ChangeInput(project.get(), "master", "empty change");
input.workInProgress = false;
assertThat(gApi.changes().create(input).get().workInProgress).isNull();
}
@Test
public void createChangeWithWorkInProgressByDefaultForProjectInherited() throws Exception {
Project.NameKey parentProject = projectOperations.newProject().create();
Project.NameKey childProject = projectOperations.newProject().parent(parentProject).create();
setWorkInProgressByDefaultForProject(parentProject);
ChangeInfo info =
gApi.changes().create(new ChangeInput(childProject.get(), "master", "empty change")).get();
assertThat(info.workInProgress).isTrue();
}
@Test
public void pushWithWorkInProgressByDefaultForProjectEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForProject(project);
assertThat(createChange(project).getChange().change().isWorkInProgress()).isTrue();
}
@Test
public void pushWithWorkInProgressByDefaultForUserEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForUser();
assertThat(createChange(project).getChange().change().isWorkInProgress()).isTrue();
}
@Test
public void pushBypassWorkInProgressByDefaultForProjectEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForProject(project);
assertThat(
createChange(project, "refs/for/master%ready").getChange().change().isWorkInProgress())
.isFalse();
}
@Test
public void pushBypassWorkInProgressByDefaultForUserEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
setWorkInProgressByDefaultForUser();
assertThat(
createChange(project, "refs/for/master%ready").getChange().change().isWorkInProgress())
.isFalse();
}
@Test
public void pushWithWorkInProgressByDefaultForProjectDisabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
assertThat(createChange(project).getChange().change().isWorkInProgress()).isFalse();
}
@Test
public void pushWorkInProgressByDefaultForProjectInherited() throws Exception {
Project.NameKey parentProject = projectOperations.newProject().create();
Project.NameKey childProject = projectOperations.newProject().parent(parentProject).create();
setWorkInProgressByDefaultForProject(parentProject);
assertThat(createChange(childProject).getChange().change().isWorkInProgress()).isTrue();
}
@Test
public void pushNewPatchSetWithWorkInProgressByDefaultForUserEnabled() throws Exception {
Project.NameKey project = projectOperations.newProject().create();
// Create change.
TestRepository<InMemoryRepository> testRepo = cloneProject(project);
PushOneCommit.Result result =
pushFactory.create(admin.newIdent(), testRepo).to("refs/for/master");
result.assertOkStatus();
String changeId = result.getChangeId();
assertThat(gApi.changes().id(changeId).get().workInProgress).isNull();
setWorkInProgressByDefaultForUser();
// Create new patch set on existing change, this shouldn't mark the change as WIP.
result = pushFactory.create(admin.newIdent(), testRepo, changeId).to("refs/for/master");
result.assertOkStatus();
assertThat(gApi.changes().id(changeId).get().workInProgress).isNull();
}
@Test
public void pushNewPatchSetAndNewChangeAtOnceWithWorkInProgressByDefaultForUserEnabled()
throws Exception {
Project.NameKey project = projectOperations.newProject().create();
// Create change.
TestRepository<InMemoryRepository> testRepo = cloneProject(project);
RevCommit initialHead = getHead(testRepo.getRepository(), "HEAD");
RevCommit commit1a =
testRepo.commit().parent(initialHead).message("Change 1").insertChangeId().create();
String changeId1 = GitUtil.getChangeId(testRepo, commit1a).get();
testRepo.reset(commit1a);
PushResult result = pushHead(testRepo, "refs/for/master", false);
assertPushOk(result, "refs/for/master");
assertThat(gApi.changes().id(changeId1).get().workInProgress).isNull();
setWorkInProgressByDefaultForUser();
// Clone the repo again. The test connection keeps an AccountState internally, so we need to
// create a new connection after changing account properties.
PatchSet.Id ps1OfChange1 =
PatchSet.id(Change.id(gApi.changes().id(changeId1).get()._number), 1);
testRepo = cloneProject(project);
testRepo.git().fetch().setRefSpecs(RefNames.patchSetRef(ps1OfChange1) + ":c1").call();
testRepo.reset("c1");
// Create a new patch set on the existing change and in the same push create a new successor
// change.
RevCommit commit1b = testRepo.amend(commit1a).create();
testRepo.reset(commit1b);
RevCommit commit2 =
testRepo.commit().parent(commit1b).message("Change 2").insertChangeId().create();
String changeId2 = GitUtil.getChangeId(testRepo, commit2).get();
testRepo.reset(commit2);
result = pushHead(testRepo, "refs/for/master", false);
assertPushOk(result, "refs/for/master");
// Check that the existing change (changeId1) is not marked as WIP, but only the newly created
// change (changeId2).
assertThat(gApi.changes().id(changeId1).get().workInProgress).isNull();
assertThat(gApi.changes().id(changeId2).get().workInProgress).isTrue();
}
private void setWorkInProgressByDefaultForProject(Project.NameKey p) throws Exception {
ConfigInput input = new ConfigInput();
input.workInProgressByDefault = InheritableBoolean.TRUE;
gApi.projects().name(p.get()).config(input);
}
private void setWorkInProgressByDefaultForUser() throws Exception {
GeneralPreferencesInfo prefs = new GeneralPreferencesInfo();
prefs.workInProgressByDefault = true;
gApi.accounts().id(admin.id().get()).setPreferences(prefs);
// Generate a new API scope. User preferences are stored in IdentifiedUser, so we need to flush
// that entity.
requestScopeOperations.resetCurrentApiUser();
}
private PushOneCommit.Result createChange(Project.NameKey p) throws Exception {
return createChange(p, "refs/for/master");
}
private PushOneCommit.Result createChange(Project.NameKey p, String r) throws Exception {
TestRepository<InMemoryRepository> testRepo = cloneProject(p);
PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
PushOneCommit.Result result = push.to(r);
result.assertOkStatus();
return result;
}
}
| 3,249 |
494 | package com.by_syk.lib.nanoiconpack.dialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import com.by_syk.lib.nanoiconpack.R;
import com.by_syk.lib.nanoiconpack.bean.DonateBean;
import java.util.ArrayList;
import java.util.List;
/**
* Created by By_syk on 2016-11-16.
*/
public class SponsorsDialog extends DialogFragment {
private OnDonateListener onDonateListener;
public interface OnDonateListener {
void onDonate();
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ArrayList<DonateBean> dataList = (ArrayList<DonateBean>) getArguments().getSerializable("data");
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.preference_support_title_sponsors)
.setItems(parseData(dataList), null)
.setPositiveButton(R.string.dlg_bt_donate_too, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (onDonateListener != null) {
onDonateListener.onDonate();
}
}
})
.create();
}
@NonNull
private String[] parseData(ArrayList<DonateBean> dataList) {
if (dataList == null) {
return new String[0];
}
List<String> dataArr = new ArrayList<>();
for (int i = 0, len = dataList.size(); i < len; ++i) {
String sponsor = dataList.get(i).getDonator();
if (!TextUtils.isEmpty(sponsor)) {
if (!sponsor.contains("@")) {
sponsor = "@" + sponsor;
}
dataArr.add(sponsor);
}
}
return dataArr.toArray(new String[dataArr.size()]);
}
public void setOnDonateListener(OnDonateListener onDonateListener) {
this.onDonateListener = onDonateListener;
}
public static SponsorsDialog newInstance(ArrayList<DonateBean> dataList) {
SponsorsDialog dialog = new SponsorsDialog();
Bundle bundle = new Bundle();
bundle.putSerializable("data", dataList);
dialog.setArguments(bundle);
return dialog;
}
}
| 1,122 |
1,210 | <reponame>Passer-D/GameAISDK<filename>src/ImgProc/Comm/ImgReg/Recognizer/CDeformObjReg.h<gh_stars>1000+
/*
* Tencent is pleased to support the open source community by making GameAISDK available.
* This source code file is licensed under the GNU General Public License Version 3.
* For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
*/
#ifndef GAME_AI_SDK_IMGPROC_COMM_IMGREG_RECOGNIZER_CDEFORMOBJREG_H_
#define GAME_AI_SDK_IMGPROC_COMM_IMGREG_RECOGNIZER_CDEFORMOBJREG_H_
#include <string>
#include <vector>
#include "Comm/ImgReg/ImgProcess/CYOLOAPI.h"
#include "Comm/ImgReg/Recognizer/IObjReg.h"
// **************************************************************************************
// CDeformObjReg Structure Define
// **************************************************************************************
struct tagDeformObjRegElement {
int nMaskValue;
float fThreshold;
cv::Rect oROI;
std::string strCfgPath;
std::string strWeightPath;
std::string strNamePath;
std::string strMaskPath;
tagDeformObjRegElement() {
nMaskValue = 127;
fThreshold = 0.50f;
oROI = cv::Rect(-1, -1, -1, -1);
strCfgPath = "";
strWeightPath = "";
strNamePath = "";
strMaskPath = "";
}
};
struct tagDeformObjRegResult {
int nState;
int nBBoxNum;
tagBBox szBBoxes[MAX_BBOX_SIZE];
tagDeformObjRegResult() {
nState = 0;
nBBoxNum = 0;
}
};
// **************************************************************************************
// CDeformObjRegParam Class Define
// **************************************************************************************
class CDeformObjRegParam : public IObjRegParam {
public:
CDeformObjRegParam() {
m_oVecElements.clear();
}
virtual ~CDeformObjRegParam() {}
public:
std::vector<tagDeformObjRegElement> m_oVecElements;
};
// **************************************************************************************
// CDeformObjRegResult Class Define
// **************************************************************************************
class CDeformObjRegResult : public IObjRegResult {
public:
CDeformObjRegResult() {
m_nResultNum = 0;
}
virtual ~CDeformObjRegResult() {}
void SetResult(tagDeformObjRegResult szResults[], int *pResultNum) {
m_nResultNum = *pResultNum;
for (int i = 0; i < *pResultNum; i++) {
m_szResults[i] = szResults[i];
}
}
tagDeformObjRegResult* GetResult(int *pResultNum) {
*pResultNum = m_nResultNum;
return m_szResults;
}
private:
int m_nResultNum;
tagDeformObjRegResult m_szResults[MAX_ELEMENT_SIZE];
};
// **************************************************************************************
// CDeformObjReg Class Define
// **************************************************************************************
class CDeformObjReg : public IObjReg {
public:
CDeformObjReg();
~CDeformObjReg();
// interface
virtual int Initialize(IRegParam *pParam);
virtual int Predict(const tagRegData &stData, IRegResult *pResult);
virtual int Release();
private:
int FillYOLOAPIParam(const tagDeformObjRegElement &stParam, CYOLOAPIParam &oParam);
private:
std::vector<tagDeformObjRegElement> m_oVecParams; // vector of parameters
std::vector<CYOLOAPI> m_oVecYOLOAPIs; // vector of methods
};
#endif // GAME_AI_SDK_IMGPROC_COMM_IMGREG_RECOGNIZER_CDEFORMOBJREG_H_
| 1,400 |
16,518 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.googlemaps;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import com.google.android.gms.internal.maps.zzw;
import com.google.android.gms.maps.model.Polygon;
import org.junit.Test;
import org.mockito.Mockito;
public class PolygonControllerTest {
@Test
public void controller_SetsStrokeDensity() {
final zzw z = mock(zzw.class);
final Polygon polygon = spy(new Polygon(z));
final float density = 5;
final float strokeWidth = 3;
final PolygonController controller = new PolygonController(polygon, false, density);
controller.setStrokeWidth(strokeWidth);
Mockito.verify(polygon).setStrokeWidth(density * strokeWidth);
}
}
| 295 |
733 | from rx import config
from rx.internal import noop
from rx.core import Disposable
class AnonymousDisposable(Disposable):
"""Main disposable class"""
def __init__(self, action=None):
"""Creates a disposable object that invokes the specified action when
disposed.
Keyword arguments:
dispose -- Action to run during the first call to Disposable.dispose.
The action is guaranteed to be run at most once.
Returns the disposable object that runs the given action upon disposal.
"""
self.is_disposed = False
self.action = action or noop
self.lock = config["concurrency"].RLock()
def dispose(self):
"""Performs the task of cleaning up resources."""
dispose = False
with self.lock:
if not self.is_disposed:
dispose = True
self.is_disposed = True
if dispose:
self.action()
@classmethod
def empty(cls):
return cls(noop)
@classmethod
def create(cls, action):
return cls(action)
| 442 |
1,179 | <filename>tools/FileSignatureInfo/VerifySignature.cpp
/********************************************************************
VerifySignature.cpp : verifies the embedded signature of a PE file by using the WinVerifyTrust function.
from https://support.microsoft.com/en-us/help/323809/how-to-get-information-from-authenticode-signed-executables
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
********************************************************************/
#define _UNICODE 1
#define UNICODE 1
#include "stdafx.h"
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
// Link with the Wintrust.lib file.
#pragma comment (lib, "wintrust")
BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
LONG lStatus;
DWORD dwLastError;
// Initialize the WINTRUST_FILE_INFO structure.
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
/*
WVTPolicyGUID specifies the policy to apply on the file
WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks:
1) The certificate used to sign the file chains up to a root
certificate located in the trusted root certificate store. This
implies that the identity of the publisher has been verified by
a certification authority.
2) In cases where user interface is displayed (which this example
does not do), WinVerifyTrust will check for whether the
end entity certificate is stored in the trusted publisher store,
implying that the user trusts content from this publisher.
3) The end entity certificate has sufficient permission to sign
code, as indicated by the presence of a code signing EKU or no
EKU.
*/
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_DATA WinTrustData;
// Initialize the WinVerifyTrust input data structure.
// Default all fields to 0.
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
// Use default code signing EKU.
WinTrustData.pPolicyCallbackData = NULL;
// No data to pass to SIP.
WinTrustData.pSIPClientData = NULL;
// Disable WVT UI.
WinTrustData.dwUIChoice = WTD_UI_NONE;
// No revocation checking.
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
// Verify an embedded signature on a file.
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
// Verify action.
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
// Verification sets this value.
WinTrustData.hWVTStateData = NULL;
// Not used.
WinTrustData.pwszURLReference = NULL;
// This is not applicable if there is no UI because it changes
// the UI to accommodate running applications instead of
// installing applications.
WinTrustData.dwUIContext = 0;
// Set pFile.
WinTrustData.pFile = &FileData;
// WinVerifyTrust verifies signatures as specified by the GUID
// and Wintrust_Data.
lStatus = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
switch (lStatus)
{
case ERROR_SUCCESS:
/*
Signed file:
- Hash that represents the subject is trusted.
- Trusted publisher without any verification errors.
- UI was disabled in dwUIChoice. No publisher or
time stamp chain errors.
- UI was enabled in dwUIChoice and the user clicked
"Yes" when asked to install and run the signed
subject.
*/
wprintf_s(L"The file \"%s\" is signed and the signature "
L"was verified.\n",
pwszSourceFile);
break;
case TRUST_E_NOSIGNATURE:
// The file was not signed or had a signature
// that was not valid.
// Get the reason for no signature.
dwLastError = GetLastError();
if (TRUST_E_NOSIGNATURE == dwLastError ||
TRUST_E_SUBJECT_FORM_UNKNOWN == dwLastError ||
TRUST_E_PROVIDER_UNKNOWN == dwLastError)
{
// The file was not signed.
wprintf_s(L"The file \"%s\" is not signed.\n",
pwszSourceFile);
}
else
{
// The signature was not valid or there was an error
// opening the file.
wprintf_s(L"An unknown error occurred trying to "
L"verify the signature of the \"%s\" file.\n",
pwszSourceFile);
}
break;
case TRUST_E_EXPLICIT_DISTRUST:
// The hash that represents the subject or the publisher
// is not allowed by the admin or user.
wprintf_s(L"The signature is present, but specifically "
L"disallowed.\n");
break;
case TRUST_E_SUBJECT_NOT_TRUSTED:
// The user clicked "No" when asked to install and run.
wprintf_s(L"The signature is present, but not "
L"trusted.\n");
break;
case CRYPT_E_SECURITY_SETTINGS:
/*
The hash that represents the subject or the publisher
was not explicitly trusted by the admin and the
admin policy has disabled user trust. No signature,
publisher or time stamp errors.
*/
wprintf_s(L"CRYPT_E_SECURITY_SETTINGS - The hash "
L"representing the subject or the publisher wasn't "
L"explicitly trusted by the admin and admin policy "
L"has disabled user trust. No signature, publisher "
L"or timestamp errors.\n");
break;
default:
// The UI was disabled in dwUIChoice or the admin policy
// has disabled user trust. lStatus contains the
// publisher or time stamp chain error.
wprintf_s(L"Error is: 0x%x.\n",
lStatus);
break;
}
// Any hWVTStateData must be released by a call with close.
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
lStatus = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
return true;
}
| 2,425 |
5,098 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Converts `SavedModel` to TensorRT graph and measures inference time.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from absl import app
from absl import flags
import requests
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.python.saved_model import loader
from tensorflow.compat.v1.python.saved_model import tag_constants
from tensorflow.contrib import tensorrt as contrib_tensorrt
flags.DEFINE_string(
'image_url',
default='https://tensorflow.org/images/blogs/serving/cat.jpg',
help='URL of the image to use for prediction.')
flags.DEFINE_string(
'saved_model_dir',
default=None,
help='Location of `SavedModel`.')
flags.DEFINE_string(
'model_input',
default='Placeholder:0',
help='Model input that images are fed.')
flags.DEFINE_multi_string(
'model_outputs',
default=[
'map_1/TensorArrayStack/TensorArrayGatherV3:0',
'map_1/TensorArrayStack_1/TensorArrayGatherV3:0',
'map_1/TensorArrayStack_2/TensorArrayGatherV3:0',
'map_1/TensorArrayStack_3/TensorArrayGatherV3:0',
],
help='Model outputs that that are inferred.')
flags.DEFINE_integer(
'number',
default=100,
help='Number of times the inference is run to calculate inference time.')
FLAGS = flags.FLAGS
def main(argv):
del argv # Unused.
original_saved_model_dir = FLAGS.saved_model_dir.rstrip('/')
tensorrt_saved_model_dir = '{}_trt'.format(original_saved_model_dir)
# Converts `SavedModel` to TensorRT inference graph.
contrib_tensorrt.create_inference_graph(
None,
None,
input_saved_model_dir=original_saved_model_dir,
output_saved_model_dir=tensorrt_saved_model_dir)
print('Model conversion completed.')
# Gets the image.
get_image_response = requests.get(FLAGS.image_url)
number = FLAGS.number
saved_model_dirs = [original_saved_model_dir, tensorrt_saved_model_dir]
latencies = {}
for saved_model_dir in saved_model_dirs:
with tf.Graph().as_default():
with tf.Session() as sess:
# Loads the saved model.
loader.load(sess, [tag_constants.SERVING], saved_model_dir)
print('Model loaded {}'.format(saved_model_dir))
def _run_inf(session=sess, n=1):
"""Runs inference repeatedly."""
for _ in range(n):
session.run(
FLAGS.model_outputs,
feed_dict={
FLAGS.model_input: [get_image_response.content]})
# Run inference once to perform XLA compile step.
_run_inf(sess, 1)
start = time.time()
_run_inf(sess, number)
end = time.time()
latencies[saved_model_dir] = end - start
print('Time to run {} predictions:'.format(number))
for saved_model_dir, latency in latencies.items():
print('* {} seconds for {} runs for {}'.format(
latency, number, saved_model_dir))
if __name__ == '__main__':
flags.mark_flag_as_required('saved_model_dir')
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
| 1,413 |
555 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.ranger.services.nifi.client;
import org.junit.Assert;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
public class TestNiFiConnectionMgr {
@Test (expected = IllegalArgumentException.class)
public void testValidURLWithWrongEndPoint() throws Exception {
final String nifiUrl = "http://localhost:8080/nifi";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.NONE.name());
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
@Test (expected = IllegalArgumentException.class)
public void testInvalidURL() throws Exception {
final String nifiUrl = "not a url";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.NONE.name());
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
@Test
public void testAuthTypeNone() throws Exception {
final String nifiUrl = "http://localhost:8080/nifi-api/resources";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.NONE.name());
NiFiClient client = NiFiConnectionMgr.getNiFiClient("nifi", configs);
Assert.assertNotNull(client);
Assert.assertEquals(nifiUrl, client.getUrl());
Assert.assertNull(client.getSslContext());
}
@Test(expected = IllegalArgumentException.class)
public void testAuthTypeNoneMissingURL() throws Exception {
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, null);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.NONE.name());
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
@Test(expected = FileNotFoundException.class)
public void testAuthTypeSSL() throws Exception {
final String nifiUrl = "https://localhost:8080/nifi-api/resources";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.SSL.name());
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE, "src/test/resources/missing.jks");
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE_PASSWORD, "password");
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE_TYPE, "JKS");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE, "src/test/resources/missing.jks");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE_PASSWORD, "password");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE_TYPE, "JKS");
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
@Test(expected = IllegalArgumentException.class)
public void testAuthTypeSSLWithNonHttpsUrl() throws Exception {
final String nifiUrl = "http://localhost:8080/nifi-api/resources";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.SSL.name());
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE, "src/test/resources/missing.jks");
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE_PASSWORD, "password");
configs.put(NiFiConfigs.NIFI_SSL_KEYSTORE_TYPE, "JKS");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE, "src/test/resources/missing.jks");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE_PASSWORD, "password");
configs.put(NiFiConfigs.NIFI_SSL_TRUSTSTORE_TYPE, "JKS");
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
@Test(expected = IllegalArgumentException.class)
public void testAuthTypeSSLMissingConfigs() throws Exception {
final String nifiUrl = "http://localhost:8080/nifi";
Map<String,String> configs = new HashMap<>();
configs.put(NiFiConfigs.NIFI_URL, nifiUrl);
configs.put(NiFiConfigs.NIFI_AUTHENTICATION_TYPE, NiFiAuthType.SSL.name());
NiFiConnectionMgr.getNiFiClient("nifi", configs);
}
}
| 1,994 |
8,805 | <reponame>rudylee/expo
/*-----------------------------------------------------------------------------+
Copyright (c) 2008-2009: <NAME>
+------------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_TYPE_TRAITS_CODOMAIN_TYPE_OF_HPP_JOFA_100829
#define BOOST_ICL_TYPE_TRAITS_CODOMAIN_TYPE_OF_HPP_JOFA_100829
#include <set>
#include <boost/mpl/has_xxx.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/icl/type_traits/no_type.hpp>
#include <boost/icl/type_traits/is_container.hpp>
namespace boost{ namespace icl
{
namespace detail
{
BOOST_MPL_HAS_XXX_TRAIT_DEF(codomain_type)
}
template <class Type>
struct has_codomain_type
: mpl::bool_<detail::has_codomain_type<Type>::value>
{};
template <class Type, bool has_codomain_type, bool is_std_set>
struct get_codomain_type;
template <class Type>
struct get_codomain_type<Type, false, false>
{
typedef no_type type;
};
template <class Type, bool is_std_set>
struct get_codomain_type<Type, true, is_std_set>
{
typedef typename Type::codomain_type type;
};
template <class Type>
struct get_codomain_type<Type, false, true>
{
typedef typename Type::value_type type;
};
template <class Type>
struct codomain_type_of
{
typedef typename
get_codomain_type< Type
, has_codomain_type<Type>::value
, is_std_set<Type>::value
>::type type;
};
}} // namespace boost icl
#endif
| 854 |
451 | /*eLiSe06/05/99
Copyright (C) 1999 <NAME>
eLiSe : Elements of a Linux Image Software Environment
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Author: <NAME> IGN/MATIS
Internet: <EMAIL>
Phone: (33) 01 43 98 81 28
eLiSe06/05/99*/
#include "StdAfx.h"
#include "bench.h"
//++++++++++++++++++++++++++++++++++++
// DMR
//++++++++++++++++++++++++++++++++++++
class BenchDMR : public NROptF1vDer
{
public :
BenchDMR(INT deg);
REAL NRF1v(REAL);
REAL DerNRF1v(REAL);
void test();
private :
ElPolynome<REAL> _pol;
ElPolynome<REAL> _dpol;
};
REAL BenchDMR::NRF1v(REAL v)
{
return _pol(v);
}
REAL BenchDMR::DerNRF1v(REAL v)
{
return _dpol(v);
}
BenchDMR::BenchDMR(INT deg) :
_pol ((char *)0,deg),
_dpol ()
{
for (INT k=0 ; k< deg; k++)
_pol[k] = (NRrandom3()-0.5)*10;
_pol[deg] = NRrandom3()+0.5;
_dpol = _pol.deriv();
}
void BenchDMR::test()
{
REAL ax=-1,bx=1,cx,fa,fb,fc;
mnbrack(&ax,&bx,&cx,&fa,&fb,&fc);
REAL xmin1;
golden(ax,bx,cx,1e-15,&xmin1);
if (_pol.degre() <= 4)
BENCH_ASSERT(ElAbs(_dpol(xmin1)) < BIG_epsilon);
BENCH_ASSERT(ElAbs(_dpol(xmin1)) < GIGANTESQUE_epsilon);
Pt2dr aP = brent(true);
if (_pol.degre() <= 4)
BENCH_ASSERT(ElAbs(_dpol(aP.x)) < BIG_epsilon);
BENCH_ASSERT(ElAbs(_dpol(aP.x)) < GIGANTESQUE_epsilon);
}
void bench_optim_DMR()
{
for (INT k=0; k<5000 ; k++)
{
All_Memo_counter MC_INIT;
stow_memory_counter(MC_INIT);
{
BenchDMR BDMR((k%3+1)*2);
BDMR.test();
}
verif_memory_state(MC_INIT);
}
}
void bench_optim_0()
{
for (INT k=0 ; k<1 ; k++)
{
cout << "K= " << k << "\n";
{
All_Memo_counter MC_INIT;
stow_memory_counter(MC_INIT);
bench_optim_DMR();
verif_memory_state(MC_INIT);
}
cout << "END DMR \n";
{
All_Memo_counter MC_INIT;
stow_memory_counter(MC_INIT);
verif_memory_state(MC_INIT);
}
cout << "END DGC \n";
}
cout << "End Bench Optim0 \n";
}
| 1,360 |
1,120 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//************************ Includes *****************************
#ifdef _WIN32
#include <windows.h>
#endif
#include <k4a/k4a.h>
#include <k4ainternal/common.h>
#include <k4ainternal/logging.h>
#include <gtest/gtest.h>
#include <utcommon.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <k4a/k4a.h>
#include <azure_c_shared_utility/threadapi.h>
#include <azure_c_shared_utility/envvariable.h>
#include <deque>
#include <mutex>
#ifndef _WIN32
#include <time.h>
#endif
#define LLD(val) ((int64_t)(val))
#define STS_TO_MS(ts) (LLD((ts) / 1000000)) // System TS convertion to milliseconds
static bool g_skip_delay_off_color_validation = false;
static int32_t g_depth_delay_off_color_usec = 0;
static uint8_t g_device_index = K4A_DEVICE_DEFAULT;
static k4a_wired_sync_mode_t g_wired_sync_mode = K4A_WIRED_SYNC_MODE_STANDALONE;
static int g_capture_count = 50;
static bool g_synchronized_images_only = false;
static bool g_no_startup_flush = false;
static uint32_t g_subordinate_delay_off_master_usec = 0;
static bool g_manual_exposure = true;
static uint32_t g_exposure_setting = 31000; // will round up to nearest value
static bool g_power_line_50_hz = false;
using ::testing::ValuesIn;
typedef struct _sys_pts_time_t
{
uint64_t pts;
uint64_t system;
} sys_pts_time_t;
static std::mutex g_lock_mutex;
static std::deque<sys_pts_time_t> g_time_c; // Color image copy of data
static std::deque<sys_pts_time_t> g_time_i; // Ir image copy of data
struct latency_parameters
{
int test_number;
const char *test_name;
k4a_fps_t fps;
k4a_image_format_t color_format;
k4a_color_resolution_t color_resolution;
k4a_depth_mode_t depth_mode;
friend std::ostream &operator<<(std::ostream &os, const latency_parameters &obj)
{
return os << "test index: (" << obj.test_name << ") " << (int)obj.test_number;
}
};
struct thread_data
{
volatile bool save_samples;
volatile bool exit;
volatile uint32_t imu_samples;
k4a_device_t device;
};
class latency_perf : public ::testing::Test, public ::testing::WithParamInterface<latency_parameters>
{
public:
virtual void SetUp()
{
ASSERT_EQ(K4A_RESULT_SUCCEEDED, k4a_device_open(g_device_index, &m_device)) << "Couldn't open device\n";
ASSERT_NE(m_device, nullptr);
EXPECT_NE((FILE *)NULL, (m_file_handle = fopen("latency_testResults.csv", "a")));
}
virtual void TearDown()
{
if (m_device != nullptr)
{
k4a_device_close(m_device);
m_device = nullptr;
}
if (m_file_handle)
{
fclose(m_file_handle);
}
}
void print_and_log(const char *message, const char *mode, int64_t ave, int64_t min, int64_t max);
void process_image(k4a_capture_t capture,
uint64_t current_system_ts,
bool process_color,
bool *image_first_pass,
std::deque<uint64_t> *system_latency,
std::deque<uint64_t> *system_latency_from_pts,
uint64_t *system_ts_last,
uint64_t *system_ts_from_pts_last);
k4a_device_t m_device = nullptr;
FILE *m_file_handle;
};
static const char *get_string_from_color_format(k4a_image_format_t format)
{
switch (format)
{
case K4A_IMAGE_FORMAT_COLOR_NV12:
return "K4A_IMAGE_FORMAT_COLOR_NV12";
break;
case K4A_IMAGE_FORMAT_COLOR_YUY2:
return "K4A_IMAGE_FORMAT_COLOR_YUY2";
break;
case K4A_IMAGE_FORMAT_COLOR_MJPG:
return "K4A_IMAGE_FORMAT_COLOR_MJPG";
break;
case K4A_IMAGE_FORMAT_COLOR_BGRA32:
return "K4A_IMAGE_FORMAT_COLOR_BGRA32";
break;
case K4A_IMAGE_FORMAT_DEPTH16:
return "K4A_IMAGE_FORMAT_DEPTH16";
break;
case K4A_IMAGE_FORMAT_IR16:
return "K4A_IMAGE_FORMAT_IR16";
break;
case K4A_IMAGE_FORMAT_CUSTOM8:
return "K4A_IMAGE_FORMAT_CUSTOM8";
break;
case K4A_IMAGE_FORMAT_CUSTOM16:
return "K4A_IMAGE_FORMAT_CUSTOM16";
break;
case K4A_IMAGE_FORMAT_CUSTOM:
return "K4A_IMAGE_FORMAT_CUSTOM";
break;
}
assert(0);
return "K4A_IMAGE_FORMAT_UNKNOWN";
}
static const char *get_string_from_color_resolution(k4a_color_resolution_t resolution)
{
switch (resolution)
{
case K4A_COLOR_RESOLUTION_OFF:
return "OFF";
break;
case K4A_COLOR_RESOLUTION_720P:
return "1280 * 720 16:9";
break;
case K4A_COLOR_RESOLUTION_1080P:
return "1920 * 1080 16:9";
break;
case K4A_COLOR_RESOLUTION_1440P:
return "2560 * 1440 16:9";
break;
case K4A_COLOR_RESOLUTION_1536P:
return "2048 * 1536 4:3";
break;
case K4A_COLOR_RESOLUTION_2160P:
return "3840 * 2160 16:9";
break;
case K4A_COLOR_RESOLUTION_3072P:
return "4096 * 3072 4:3";
break;
}
assert(0);
return "Unknown resolution";
}
static const char *get_string_from_depth_mode(k4a_depth_mode_t mode)
{
switch (mode)
{
case K4A_DEPTH_MODE_OFF:
return "K4A_DEPTH_MODE_OFF";
break;
case K4A_DEPTH_MODE_NFOV_2X2BINNED:
return "K4A_DEPTH_MODE_NFOV_2X2BINNED";
break;
case K4A_DEPTH_MODE_NFOV_UNBINNED:
return "K4A_DEPTH_MODE_NFOV_UNBINNED";
break;
case K4A_DEPTH_MODE_WFOV_2X2BINNED:
return "K4A_DEPTH_MODE_WFOV_2X2BINNED";
break;
case K4A_DEPTH_MODE_WFOV_UNBINNED:
return "K4A_DEPTH_MODE_WFOV_UNBINNED";
break;
case K4A_DEPTH_MODE_PASSIVE_IR:
return "K4A_DEPTH_MODE_PASSIVE_IR";
break;
}
assert(0);
return "Unknown Depth";
}
static bool get_system_time(uint64_t *time_nsec)
{
k4a_result_t result = K4A_RESULT_SUCCEEDED;
#ifdef _WIN32
LARGE_INTEGER qpc = { 0 };
static LARGE_INTEGER freq = { 0 };
result = K4A_RESULT_FROM_BOOL(QueryPerformanceCounter(&qpc) != 0);
if (K4A_FAILED(result))
{
return false;
}
if (freq.QuadPart == 0)
{
result = K4A_RESULT_FROM_BOOL(QueryPerformanceFrequency(&freq) != 0);
if (K4A_FAILED(result))
{
return false;
}
}
// Calculate seconds in such a way we minimize overflow.
// Rollover happens, for a 1MHz Freq, when qpc.QuadPart > 0x003F FFFF FFFF FFFF; ~571 Years after boot.
*time_nsec = qpc.QuadPart / freq.QuadPart * 1000000000;
*time_nsec += qpc.QuadPart % freq.QuadPart * 1000000000 / freq.QuadPart;
#else
struct timespec ts_time;
result = K4A_RESULT_FROM_BOOL(clock_gettime(CLOCK_MONOTONIC, &ts_time) == 0);
if (K4A_FAILED(result))
{
return false;
}
// Rollover happens about ~136 years after boot.
*time_nsec = (uint64_t)ts_time.tv_sec * 1000000000 + (uint64_t)ts_time.tv_nsec;
#endif
return true;
}
static int _latency_imu_thread(void *param)
{
struct thread_data *data = (struct thread_data *)param;
k4a_result_t result;
k4a_imu_sample_t imu;
result = k4a_device_start_imu(data->device);
if (K4A_FAILED(result))
{
printf("Failed to start imu\n");
return result;
}
g_time_c.clear();
g_time_i.clear();
while (data->exit == false)
{
k4a_wait_result_t wresult = k4a_device_get_imu_sample(data->device, &imu, 10);
if (wresult == K4A_WAIT_RESULT_FAILED)
{
printf("k4a_device_get_imu_sample failed\n");
result = K4A_RESULT_FAILED;
break;
}
else if ((wresult == K4A_WAIT_RESULT_SUCCEEDED) && (data->save_samples))
{
sys_pts_time_t time;
time.pts = imu.acc_timestamp_usec;
if (get_system_time(&time.system) == 0)
{
result = K4A_RESULT_FAILED;
break;
}
// Save data to each of the queues
g_lock_mutex.lock();
g_time_c.push_back(time);
g_time_i.push_back(time);
g_lock_mutex.unlock();
}
};
k4a_device_stop_imu(data->device);
return result;
}
// Drop the lock and sleep for Xms. This is to allow the queue to fill again. Return if we yield too long.
#define YIELD_THREAD(lock_var, count, message) \
lock_var.unlock(); \
printf("Lock dropped while %s\n", message); \
ThreadAPI_Sleep(2); \
if (++count > 15) \
{ \
EXPECT_LT(count, 15); \
return 0; \
} \
lock_var.lock();
static uint64_t lookup_system_ts(uint64_t pts_ts, bool color)
{
sys_pts_time_t last_time;
uint64_t start_time_nsec;
uint64_t current_time_nsec;
int count = 0;
bool found = false;
std::deque<sys_pts_time_t> *time_queue = &g_time_i;
if (color)
{
time_queue = &g_time_c;
}
g_lock_mutex.lock();
// Record start time
if (get_system_time(&start_time_nsec) == 0)
{
printf("ERROR getting system time\n");
EXPECT_TRUE(0);
g_lock_mutex.unlock();
return 0;
}
int delay_count = 0;
while (time_queue->empty())
{
// Drop lock, wait, retake lock - Exit if taking too long
YIELD_THREAD(g_lock_mutex, delay_count, "Initializing")
}
last_time = time_queue->front();
time_queue->pop_front();
while (!found)
{
int x;
for (x = 0; !time_queue->empty(); x++)
{
last_time = time_queue->front();
if (pts_ts > last_time.pts)
{
// Hold onto last_time for 1 more loop
last_time = time_queue->front();
time_queue->pop_front();
}
else
{
// We just found the first system time that is beyond the one we are looking for.
if ((pts_ts - last_time.pts) < (time_queue->front().pts - pts_ts))
{
g_lock_mutex.unlock();
found = true;
return last_time.system;
}
uint64_t ret_time = time_queue->front().system;
g_lock_mutex.unlock();
found = true;
return ret_time;
}
if (get_system_time(¤t_time_nsec) == 0)
{
printf("ERROR getting system time\n");
EXPECT_TRUE(0);
g_lock_mutex.unlock();
return 0;
}
if (STS_TO_MS(current_time_nsec - start_time_nsec) > 1000)
{
printf("Count for break is %d\n", count);
break; // Don't hold lock too long, run YIELD_THREAD below
}
}
// Queue is drained or we held the lock too long. We need to let the IMU thread catch up. Drop lock, wait,
// retake lock - Exit if taking too long
YIELD_THREAD(g_lock_mutex, delay_count, "walking list.");
// Update start time after the thread yield
if (get_system_time(&start_time_nsec) == 0)
{
printf("ERROR getting system time\n");
EXPECT_TRUE(0);
g_lock_mutex.unlock();
return 0;
}
}
// Should not happen
EXPECT_FALSE(1);
g_lock_mutex.unlock();
return 0;
}
void latency_perf::print_and_log(const char *message, const char *mode, int64_t ave, int64_t min, int64_t max)
{
printf(" %30s %30s: Ave=%" PRId64 " min=%" PRId64 " max=%" PRId64 "\n", message, mode, ave, min, max);
if (m_file_handle)
{
char buffer[1024];
snprintf(buffer,
sizeof(buffer),
"%s, %s (min ave max),%" PRId64 ",%" PRId64 ",%" PRId64 ",",
mode,
message,
min,
ave,
max);
fputs(buffer, m_file_handle);
}
}
void latency_perf::process_image(k4a_capture_t capture,
uint64_t current_system_ts,
bool process_color,
bool *image_first_pass,
std::deque<uint64_t> *system_latency,
std::deque<uint64_t> *system_latency_from_pts,
uint64_t *system_ts_last,
uint64_t *system_ts_from_pts_last)
{
k4a_image_t image;
if (process_color)
{
image = k4a_capture_get_color_image(capture);
}
else
{
image = k4a_capture_get_ir_image(capture);
}
if (image)
{
uint64_t system_ts = k4a_image_get_system_timestamp_nsec(image);
uint64_t system_ts_from_pts = lookup_system_ts(k4a_image_get_device_timestamp_usec(image), process_color);
// Time from center of exposure until given to us from the SDK; based on Host system time.
uint64_t system_ts_latency = current_system_ts - system_ts;
// Time from center of exposure PTS time (converted to system time based on low latency IMU data) until we
// read the frame; based on Host system time.
uint64_t system_ts_latency_from_pts = current_system_ts - system_ts_from_pts;
if (system_ts_from_pts > current_system_ts)
{
printf("Calculated %s pts system time %" PRId64 " is after our arrival system time %" PRId64
" a diff of %" PRId64 "\n",
process_color ? "color" : "IR",
STS_TO_MS(system_ts_from_pts),
STS_TO_MS(current_system_ts),
STS_TO_MS(system_ts_from_pts - current_system_ts));
// Update values anyway
*system_ts_last = system_ts;
*system_ts_from_pts_last = system_ts_from_pts;
}
else
{
if (!*image_first_pass)
{
system_latency->push_back(current_system_ts - system_ts);
system_latency_from_pts->push_back(system_ts_latency_from_pts);
printf("| %9" PRId64 " [%5" PRId64 "] [%5" PRId64 "] ",
STS_TO_MS(system_ts),
STS_TO_MS(system_ts_latency),
STS_TO_MS(system_ts_latency_from_pts));
// TS should increase
EXPECT_GT(system_ts, *system_ts_last);
EXPECT_GT(system_ts_from_pts, *system_ts_from_pts_last);
}
*system_ts_last = system_ts;
*system_ts_from_pts_last = system_ts_from_pts;
*image_first_pass = false;
}
k4a_image_release(image);
}
else
{
printf("| ");
}
}
TEST_P(latency_perf, testTest)
{
auto as = GetParam();
const int32_t TIMEOUT_IN_MS = 1000;
k4a_capture_t capture = NULL;
int capture_count = g_capture_count;
bool failed = false;
k4a_device_configuration_t config = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL;
thread_data thread = { 0 };
THREAD_HANDLE th1 = NULL;
std::deque<uint64_t> color_system_latency;
std::deque<uint64_t> color_system_latency_from_pts;
std::deque<uint64_t> ir_system_latency;
std::deque<uint64_t> ir_system_latency_from_pts;
uint64_t current_system_ts = 0;
uint64_t color_system_ts_last = 0, color_system_ts_from_pts_last = 0;
uint64_t ir_system_ts_last = 0, ir_system_ts_from_pts_last = 0;
int32_t read_exposure = 0;
printf("Capturing %d frames for test: %s\n", g_capture_count, as.test_name);
{
int32_t power_line_setting = g_power_line_50_hz ? 1 : 2;
ASSERT_EQ(K4A_RESULT_SUCCEEDED,
k4a_device_set_color_control(m_device,
K4A_COLOR_CONTROL_POWERLINE_FREQUENCY,
K4A_COLOR_CONTROL_MODE_MANUAL,
power_line_setting));
printf("Power line mode set to manual and %s.\n", power_line_setting == 1 ? "50Hz" : "60Hz");
}
if (g_manual_exposure)
{
k4a_color_control_mode_t read_mode;
ASSERT_EQ(K4A_RESULT_SUCCEEDED,
k4a_device_set_color_control(m_device,
K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE,
K4A_COLOR_CONTROL_MODE_MANUAL,
(int32_t)g_exposure_setting));
ASSERT_EQ(K4A_RESULT_SUCCEEDED,
k4a_device_get_color_control(m_device,
K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE,
&read_mode,
&read_exposure));
printf(
"Setting exposure to manual mode, exposure target is: %d. Actual mode is: %s. Actual value is: %d.\n",
g_exposure_setting,
read_mode == K4A_COLOR_CONTROL_MODE_AUTO ? "auto" : "manual",
read_exposure);
read_exposure = 0; // Clear this so we read it again after sensor is started.
}
else
{
ASSERT_EQ(K4A_RESULT_SUCCEEDED,
k4a_device_set_color_control(m_device,
K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE,
K4A_COLOR_CONTROL_MODE_AUTO,
0));
printf("Auto Exposure\n");
read_exposure = 0;
}
config.color_format = as.color_format;
config.color_resolution = as.color_resolution;
config.depth_mode = as.depth_mode;
config.camera_fps = as.fps;
config.depth_delay_off_color_usec = g_depth_delay_off_color_usec;
config.wired_sync_mode = g_wired_sync_mode;
config.synchronized_images_only = g_synchronized_images_only;
config.subordinate_delay_off_master_usec = g_subordinate_delay_off_master_usec;
printf("Config being used is:\n");
printf(" color_format:%d\n", config.color_format);
printf(" color_resolution:%d\n", config.color_resolution);
printf(" depth_mode:%d\n", config.depth_mode);
printf(" camera_fps:%d\n", config.camera_fps);
printf(" synchronized_images_only:%d\n", config.synchronized_images_only);
printf(" depth_delay_off_color_usec:%d\n", config.depth_delay_off_color_usec);
printf(" wired_sync_mode:%d\n", config.wired_sync_mode);
printf(" subordinate_delay_off_master_usec:%d\n", config.subordinate_delay_off_master_usec);
printf(" disable_streaming_indicator:%d\n", config.disable_streaming_indicator);
printf("\n");
ASSERT_EQ(K4A_RESULT_SUCCEEDED, k4a_device_start_cameras(m_device, &config));
thread.device = m_device;
ASSERT_EQ(THREADAPI_OK, ThreadAPI_Create(&th1, _latency_imu_thread, &thread));
if (!g_no_startup_flush)
{
//
// Wait for streams to start and then purge the data collected
//
if (as.fps == K4A_FRAMES_PER_SECOND_30)
{
printf("Flushing first 2s of data\n");
ThreadAPI_Sleep(2000);
}
else if (as.fps == K4A_FRAMES_PER_SECOND_15)
{
printf("Flushing first 3s of data\n");
ThreadAPI_Sleep(3000);
}
else
{
printf("Flushing first 4s of data\n");
ThreadAPI_Sleep(4000);
}
while (K4A_WAIT_RESULT_SUCCEEDED == k4a_device_get_capture(m_device, &capture, 0))
{
// Drain the queue
k4a_capture_release(capture);
};
}
else
{
printf("Flushing no start of stream data\n");
}
// For consistent IMU timing, block entering the while loop until we get 1 sample
if (K4A_WAIT_RESULT_SUCCEEDED == k4a_device_get_capture(m_device, &capture, 1000))
{
k4a_capture_release(capture);
capture = NULL;
}
printf("Sys lat: is this difference in the system time recorded on the image and the system time when the image "
"was presented to the caller.\n");
printf(
"PTS lat: Similar to Sys lat, but instead of using the system time assigned to the image (which is recorded by "
"the Host PC), the image PTS (which is center of exposure in single camera mode) is used to "
"calculate a more accurate system time from when the same PTS arrived from the least latent sensor source, "
"IMU. The IMU data received is turned into a list of PTS values and associated system ts's for when each "
"sample arrived on system.\n");
printf("+---------------------------+---------------------------+\n");
printf("| Color Info (ms) | IR 16 Info (ms) |\n");
printf("| system [ sys ] [ PTS ] | system [ sys ] [ PTS ] |\n");
printf("| ts [ lat ] [ lat ] | ts [ lat ] [ lat ] |\n");
printf("+---------------------------+---------------------------+\n");
thread.save_samples = true; // start saving IMU samples
bool color_first_pass = true;
bool ir_first_pass = true;
capture_count++; // to account for dropping the first sample
while (capture_count-- > 0)
{
if (capture)
{
k4a_capture_release(capture);
}
// Get a depth frame
k4a_wait_result_t wresult = k4a_device_get_capture(m_device, &capture, TIMEOUT_IN_MS);
if (wresult != K4A_WAIT_RESULT_SUCCEEDED)
{
if (wresult == K4A_WAIT_RESULT_TIMEOUT)
{
printf("Timed out waiting for a capture\n");
}
else // wresult == K4A_WAIT_RESULT_FAILED:
{
printf("Failed to read a capture\n");
capture_count = 0;
}
failed = true;
continue;
}
if (get_system_time(¤t_system_ts) == 0)
{
printf("Timed out waiting for a capture\n");
failed = true;
continue;
}
if (read_exposure == 0)
{
k4a_image_t image = k4a_capture_get_color_image(capture);
if (image)
{
read_exposure = (int32_t)k4a_image_get_exposure_usec(image);
k4a_image_release(image);
}
}
process_image(capture,
current_system_ts,
true, // Color Image
&color_first_pass,
&color_system_latency,
&color_system_latency_from_pts,
&color_system_ts_last,
&color_system_ts_from_pts_last);
process_image(capture,
current_system_ts,
false, // IR Image
&ir_first_pass,
&ir_system_latency,
&ir_system_latency_from_pts,
&ir_system_ts_last,
&ir_system_ts_from_pts_last);
printf("|\n"); // End of line
} // End capture loop
thread.exit = true; // shut down IMU thread
k4a_device_stop_cameras(m_device);
if (capture)
{
k4a_capture_release(capture);
}
int thread_result;
ASSERT_EQ(THREADAPI_OK, ThreadAPI_Join(th1, &thread_result));
ASSERT_EQ(thread_result, (int)K4A_RESULT_SUCCEEDED);
printf("\nLatency Results:\n");
{
// init CSV line
if (m_file_handle != 0)
{
std::time_t date_time = std::time(NULL);
char buffer_date_time[100];
std::strftime(buffer_date_time, sizeof(buffer_date_time), "%c", localtime(&date_time));
const char *computer_name = environment_get_variable("COMPUTERNAME");
const char *disable_synchronization = environment_get_variable("K4A_DISABLE_SYNCHRONIZATION");
char buffer[1024];
snprintf(buffer,
sizeof(buffer),
"%s, %s, %s, %s,%s, %s, fps, %d, %s, captures, %d, %d, %d,",
buffer_date_time,
computer_name ? computer_name : "computer name not set",
as.test_name,
disable_synchronization ? disable_synchronization : "0",
get_string_from_color_format(as.color_format),
get_string_from_color_resolution(as.color_resolution),
k4a_convert_fps_to_uint(as.fps),
get_string_from_depth_mode(as.depth_mode),
g_capture_count,
g_manual_exposure,
read_exposure);
fputs(buffer, m_file_handle);
}
}
{
uint64_t color_system_latency_ave = 0;
uint64_t min = (uint64_t)-1;
uint64_t max = 0;
for (size_t x = 0; x < color_system_latency.size(); x++)
{
color_system_latency_ave += color_system_latency[x];
if (color_system_latency[x] < min)
{
min = color_system_latency[x];
}
if (color_system_latency[x] > max)
{
max = color_system_latency[x];
}
}
color_system_latency_ave = color_system_latency_ave / color_system_latency.size();
print_and_log("Color System Time Latency",
get_string_from_color_format(config.color_format),
STS_TO_MS(color_system_latency_ave),
STS_TO_MS(min),
STS_TO_MS(max));
}
{
uint64_t color_system_latency_from_pts_ave = 0;
uint64_t min = (uint64_t)-1;
uint64_t max = 0;
for (size_t x = 0; x < color_system_latency_from_pts.size(); x++)
{
color_system_latency_from_pts_ave += color_system_latency_from_pts[x];
if (color_system_latency_from_pts[x] < min)
{
min = color_system_latency_from_pts[x];
}
if (color_system_latency_from_pts[x] > max)
{
max = color_system_latency_from_pts[x];
}
}
color_system_latency_from_pts_ave = color_system_latency_from_pts_ave / color_system_latency_from_pts.size();
print_and_log("Color System Time PTS Latency",
get_string_from_color_format(config.color_format),
STS_TO_MS(color_system_latency_from_pts_ave),
STS_TO_MS(min),
STS_TO_MS(max));
}
{
uint64_t ir_system_latency_ave = 0;
uint64_t min = (uint64_t)-1;
uint64_t max = 0;
for (size_t x = 0; x < ir_system_latency.size(); x++)
{
ir_system_latency_ave += ir_system_latency[x];
if (ir_system_latency[x] < min)
{
min = ir_system_latency[x];
}
if (ir_system_latency[x] > max)
{
max = ir_system_latency[x];
}
}
ir_system_latency_ave = ir_system_latency_ave / ir_system_latency.size();
print_and_log(" IR System Time Latency",
get_string_from_depth_mode(config.depth_mode),
STS_TO_MS(ir_system_latency_ave),
STS_TO_MS(min),
STS_TO_MS(max));
}
{
uint64_t ir_system_latency_from_pts_ave = 0;
uint64_t min = (uint64_t)-1;
uint64_t max = 0;
for (size_t x = 0; x < ir_system_latency_from_pts.size(); x++)
{
ir_system_latency_from_pts_ave += ir_system_latency_from_pts[x];
if (ir_system_latency_from_pts[x] < min)
{
min = ir_system_latency_from_pts[x];
}
if (ir_system_latency_from_pts[x] > max)
{
max = ir_system_latency_from_pts[x];
}
}
ir_system_latency_from_pts_ave = ir_system_latency_from_pts_ave / ir_system_latency_from_pts.size();
print_and_log(" IR System Time PTS",
get_string_from_depth_mode(config.depth_mode),
STS_TO_MS(ir_system_latency_from_pts_ave),
STS_TO_MS(min),
STS_TO_MS(max));
}
printf("\n");
if (m_file_handle != 0)
{
// Terminate line
fputs("\n", m_file_handle);
}
ASSERT_EQ(K4A_RESULT_SUCCEEDED,
k4a_device_set_color_control(m_device,
K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE,
K4A_COLOR_CONTROL_MODE_AUTO,
0));
ASSERT_EQ(failed, false);
return;
}
// K4A_DEPTH_MODE_WFOV_UNBINNED is the most demanding depth mode, only runs at 15FPS or less
// clang-format off
// PASSIVE_IR is fastest Depth Mode - YUY2 is fastest Color mode
static struct latency_parameters tests_30fps[] = {
// All Color modes with fast Depth
{ 0, "FPS_30_MJPEG_2160P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_2160P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 1, "FPS_30_MJPEG_1536P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_1536P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 2, "FPS_30_MJPEG_1440P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_1440P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 3, "FPS_30_MJPEG_1080P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_1080P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 4, "FPS_30_MJPEG_0720P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 5, "FPS_30_NV12__0720P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_NV12, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 6, "FPS_30_YUY2__0720P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 7, "FPS_30_BGRA32_2160P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_2160P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 8, "FPS_30_BGRA32_1536P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_1536P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 9, "FPS_30_BGRA32_1440P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_1440P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 10, "FPS_30_BGRA32_1080P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_1080P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 11, "FPS_30_BGRA32_0720P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_PASSIVE_IR},
// All Depth Modes with fastest Color
{ 12, "FPS_30_YUY2__0720P_NFOV_2X2BINNED", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_NFOV_2X2BINNED},
{ 13, "FPS_30_YUY2__0720P_NFOV_UNBINNED", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_NFOV_UNBINNED},
{ 14, "FPS_30_YUY2__0720P_WFOV_2X2BINNED", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_WFOV_2X2BINNED},
{ 15, "FPS_30_YUY2__0720P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_30, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_PASSIVE_IR},
};
INSTANTIATE_TEST_CASE_P(30FPS_TESTS, latency_perf, ValuesIn(tests_30fps));
static struct latency_parameters tests_15fps[] = {
// All Color modes with fast Depth
{ 0, "FPS_15_MJPEG_3072P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_15, K4A_IMAGE_FORMAT_COLOR_MJPG, K4A_COLOR_RESOLUTION_3072P, K4A_DEPTH_MODE_PASSIVE_IR},
{ 1, "FPS_15_BGRA32_3072P_PASSIVE_IR", K4A_FRAMES_PER_SECOND_15, K4A_IMAGE_FORMAT_COLOR_BGRA32, K4A_COLOR_RESOLUTION_3072P, K4A_DEPTH_MODE_PASSIVE_IR},
// All Depth Modes with fastest Color
{ 2, "FPS_15_YUY2__0720P_WFOV_UNBINNED", K4A_FRAMES_PER_SECOND_15, K4A_IMAGE_FORMAT_COLOR_YUY2, K4A_COLOR_RESOLUTION_720P, K4A_DEPTH_MODE_WFOV_UNBINNED},
};
INSTANTIATE_TEST_CASE_P(15FPS_TESTS, latency_perf, ValuesIn(tests_15fps));
// clang-format on
int main(int argc, char **argv)
{
bool error = false;
k4a_unittest_init();
::testing::InitGoogleTest(&argc, argv);
for (int i = 1; i < argc; ++i)
{
char *argument = argv[i];
for (int j = 0; argument[j]; j++)
{
argument[j] = (char)tolower(argument[j]);
}
if (strcmp(argument, "--depth_delay_off_color") == 0)
{
if (i + 1 <= argc)
{
g_depth_delay_off_color_usec = (int32_t)strtol(argv[i + 1], NULL, 10);
printf("Setting g_depth_delay_off_color_usec = %d\n", g_depth_delay_off_color_usec);
i++;
}
else
{
printf("Error: depth_delay_off_color parameter missing\n");
error = true;
}
}
else if (strcmp(argument, "--skip_delay_off_color_validation") == 0)
{
g_skip_delay_off_color_validation = true;
}
else if (strcmp(argument, "--master") == 0)
{
g_wired_sync_mode = K4A_WIRED_SYNC_MODE_MASTER;
printf("Setting g_wired_sync_mode = K4A_WIRED_SYNC_MODE_MASTER\n");
}
else if (strcmp(argument, "--subordinate") == 0)
{
g_wired_sync_mode = K4A_WIRED_SYNC_MODE_SUBORDINATE;
printf("Setting g_wired_sync_mode = K4A_WIRED_SYNC_MODE_SUBORDINATE\n");
}
else if (strcmp(argument, "--synchronized_images_only") == 0)
{
g_synchronized_images_only = true;
printf("g_synchronized_images_only = true\n");
}
else if (strcmp(argument, "--no_startup_flush") == 0)
{
g_no_startup_flush = true;
printf("g_no_startup_flush = true\n");
}
else if (strcmp(argument, "--60hz") == 0)
{
g_power_line_50_hz = false;
printf("g_power_line_50_hz = false\n");
}
else if (strcmp(argument, "--50hz") == 0)
{
g_power_line_50_hz = true;
printf("g_power_line_50_hz = true\n");
}
else if (strcmp(argument, "--index") == 0)
{
if (i + 1 <= argc)
{
g_device_index = (uint8_t)strtol(argv[i + 1], NULL, 10);
printf("setting g_device_index = %d\n", g_device_index);
i++;
}
else
{
printf("Error: index parameter missing\n");
error = true;
}
}
else if (strcmp(argument, "--subordinate_delay_off_master_usec") == 0)
{
if (i + 1 <= argc)
{
g_subordinate_delay_off_master_usec = (uint32_t)strtol(argv[i + 1], NULL, 10);
printf("g_subordinate_delay_off_master_usec = %d\n", g_subordinate_delay_off_master_usec);
i++;
}
else
{
printf("Error: index parameter missing\n");
error = true;
}
}
else if (strcmp(argument, "--capture_count") == 0)
{
if (i + 1 <= argc)
{
g_capture_count = (int)strtol(argv[i + 1], NULL, 10);
printf("g_capture_count g_device_index = %d\n", g_capture_count);
i++;
}
else
{
printf("Error: index parameter missing\n");
error = true;
}
}
else if (strcmp(argument, "--exposure") == 0)
{
if (i + 1 <= argc)
{
g_exposure_setting = (uint32_t)strtol(argv[i + 1], NULL, 10);
printf("g_exposure_setting = %d\n", g_exposure_setting);
g_manual_exposure = true;
i++;
}
else
{
printf("Error: index parameter missing\n");
error = true;
}
}
else if (strcmp(argument, "--auto") == 0)
{
g_manual_exposure = false;
printf("Auto Exposure Enabled\n");
}
if ((strcmp(argument, "-h") == 0) || (strcmp(argument, "/h") == 0) || (strcmp(argument, "-?") == 0) ||
(strcmp(argument, "/?") == 0))
{
error = true;
}
}
if (error)
{
printf("\n\nOptional Custom Test Settings:\n");
printf(" --depth_delay_off_color <+/- microseconds>\n");
printf(" This is the time delay the depth image capture is delayed off the color.\n");
printf(" valid ranges for this are -1 frame time to +1 frame time. The percentage\n");
printf(" needs to be multiplied by 100 to achieve correct behavior; 10000 is \n");
printf(" 100.00%%, 100 is 1.00%%.\n");
printf(" --skip_delay_off_color_validation\n");
printf(" Set this when don't want the results of color to depth timestamp \n"
" measurements to allow your test run to fail. They will still be logged\n"
" to output and the CSV file.\n");
printf(" --master\n");
printf(" Run device in master mode\n");
printf(" --subordinate\n");
printf(" Run device in subordinate mode\n");
printf(" --index\n");
printf(" The device index to target when calling k4a_device_open()\n");
printf(" --capture_count\n");
printf(" The number of captures the test should read; default is 100\n");
printf(" --synchronized_images_only\n");
printf(" By default this setting is false, enabling this will for the test to wait for\n");
printf(" both and depth images to be available.\n");
printf(" --subordinate_delay_off_master_usec <+ microseconds>\n");
printf(" This is the time delay the device captures off the master devices capture sync\n");
printf(" pulse. This value needs to be less than one image sample period, i.e for 30FPS \n");
printf(" this needs to be less than 33333us.\n");
printf(" --no_startup_flush\n");
printf(" By default the test will wait for streams to run for X seconds to stabilize. This\n");
printf(" disables that.\n");
printf(" --exposure <exposure in usec>\n");
printf(" Deault is manual exposure with an exposure of 33,333us. This will test with the manual exposure "
"setting\n");
printf(" that is passed in.\n");
printf(" --auto\n");
printf(" By default the test uses manual exposure. This will test with auto exposure.\n");
printf(" --60hz\n");
printf(" <default> Sets the power line compensation frequency to 60Hz\n");
printf(" --50hz\n");
printf(" Sets the power line compensation frequency to 50Hz\n");
return 1; // Indicates an error or warning
}
int results = RUN_ALL_TESTS();
k4a_unittest_deinit();
return results;
}
| 21,708 |
488 | <filename>src/midend/programAnalysis/genericDataflow/simpleAnalyses/sgnAnalysis.h
#include <featureTests.h>
#ifdef ROSE_ENABLE_SOURCE_ANALYSIS
#ifndef SGN_ANALYSIS_H
#define SGN_ANALYSIS_H
#include "genericDataflowCommon.h"
#include "VirtualCFGIterator.h"
#include "cfgUtils.h"
#include "CallGraphTraverse.h"
#include "analysisCommon.h"
#include "analysis.h"
#include "dataflow.h"
#include "latticeFull.h"
#include "liveDeadVarAnalysis.h"
#include "printAnalysisStates.h"
extern int sgnAnalysisDebugLevel;
// Maintains sign information about live variables. If a given variable may be either positive or negative, this object becomes top.
// There is one SgnLattice object for every variable
class SgnLattice : public FiniteLattice
{
public:
// The different levels of this lattice
typedef enum{
// this object is uninitialized
uninitialized,
// no information is known about the value of the variable
bottom,
// this variable is = 0
eqZero,
// the sign of the variable is known
sgnKnown,
// this variable can be either positive or negative
top} sgnLevels;
// The different states of this lattice (in level sgnKnown)
typedef enum{
// This variable's state is unknown
unknown,
// This variable is positive or =zero
posZero,
// This variable is negative or =zero
negZero} sgnStates;
private:
sgnStates sgnState;
private:
// this object's current level in the lattice: (uninitialized, bottom, sgnKnown, top)
sgnLevels level;
public:
SgnLattice()
{
sgnState = unknown;
level=uninitialized;
}
SgnLattice(const SgnLattice& that)
{
this->sgnState = that.sgnState;
this->level = that.level;
}
SgnLattice(long val)
{
if(val == 0)
this->level = eqZero;
else {
this->level = sgnKnown;
if(val > 0) this->sgnState = posZero;
else this->sgnState = negZero;
}
}
// Ensures that the state of this lattice is initialized
void initialize()
{
if(level == uninitialized)
{
sgnState=unknown;
level=bottom;
}
}
// returns a copy of this lattice
Lattice* copy() const;
// overwrites the state of this Lattice with that of that Lattice
void copy(Lattice* that);
// overwrites the state of this Lattice with that of that Lattice
// returns true if this causes this lattice to change and false otherwise
bool copyMod(Lattice* that_arg);
// computes the meet of this and that and saves the result in this
// returns true if this causes this to change and false otherwise
bool meetUpdate(Lattice* that);
bool operator==(Lattice* that);
// returns the current state of this object
sgnStates getSgnState() const;
sgnLevels getLevel() const;
// Sets the state of this lattice to bottom
// returns true if this causes the lattice's state to change, false otherwise
bool setBot();
// Sets the state of this lattice to eqZero.
// returns true if this causes the lattice's state to change, false otherwise
bool setEqZero();
// Sets the state of this lattice to sgnKnown, with the given sign.
// returns true if this causes the lattice's state to change, false otherwise
bool setSgnKnown(sgnStates sgnState);
// Sets the state of this lattice to sgnKnown, with the sign of the given value.
// returns true if this causes the lattice's state to change, false otherwise
bool set(int val);
// Sets the state of this lattice to top
// returns true if this causes the lattice's state to change, false otherwise
bool setTop();
// Increments the state of this object by increment
// returns true if this causes the lattice's state to change, false otherwise
bool plus(long increment);
// Increments the state of this object by the contents of that
// returns true if this causes the lattice's state to change, false otherwise
bool plus(const SgnLattice& that);
// Decrements the state of this object by increment
// returns true if this causes the lattice's state to change, false otherwise
bool minus(long increment);
// Decrements the state of this object by the contents of that
// returns true if this causes the lattice's state to change, false otherwise
bool minus(const SgnLattice& that);
// Negates the state of the object
// returns true if this causes the lattice's state to change, false otherwise
bool negate();
// Multiplies and/or divides the state of this object by value
// returns true if this causes the lattice's state to change, false otherwise
bool multdiv(long multiplier);
// Multiplies and/or divides the state of this object by the contents of that
// returns true if this causes the lattice's state to change, false otherwise
bool multdiv(const SgnLattice& that);
// Applies a generic complex operation to this and that objects, storing the results in this object
// returns true if this causes the lattice's state to change, false otherwise
bool complexOp(const SgnLattice& that);
string str(string indent="");
};
class SgnAnalysis : public IntraFWDataflow
{
protected:
static map<varID, Lattice*> constVars;
static bool constVars_init;
// The LiveDeadVarsAnalysis that identifies the live/dead state of all application variables.
// Needed to create a FiniteVarsExprsProductLattice.
LiveDeadVarsAnalysis* ldva;
public:
SgnAnalysis(LiveDeadVarsAnalysis* ldva): IntraFWDataflow()
{
this->ldva = ldva;
}
// generates the initial lattice state for the given dataflow node, in the given function, with the given NodeState
//vector<Lattice*> genInitState(const Function& func, const DataflowNode& n, const NodeState& state);
void genInitState(const Function& func, const DataflowNode& n, const NodeState& state,
vector<Lattice*>& initLattices, vector<NodeFact*>& initFacts);
bool transfer(const Function& func, const DataflowNode& n, NodeState& state, const vector<Lattice*>& dfInfo);
};
// prints the Lattices set by the given SgnAnalysis
void printSgnAnalysisStates(SgnAnalysis* sa, string indent="");
#endif
#endif
| 3,215 |
495 | {
"title": "WORKSHOPPER EXAMPLE WORKSHOP",
"subtitle": "\u001b[23mSelect an exercise and hit \u001b[3mEnter\u001b[23m to begin",
"menu": {
"credits": "CREDITS"
},
"exercise": {
"foo": "FOO",
"bar": "BAR",
"baz": "BAZ"
}
} | 122 |
605 | //===- StaticValueUtils.cpp - Utilities for dealing with static values ----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Support/LLVM.h"
#include "llvm/ADT/APSInt.h"
namespace mlir {
/// Helper function to dispatch an OpFoldResult into `staticVec` if:
/// a) it is an IntegerAttr
/// In other cases, the OpFoldResult is dispached to the `dynamicVec`.
/// In such dynamic cases, a copy of the `sentinel` value is also pushed to
/// `staticVec`. This is useful to extract mixed static and dynamic entries that
/// come from an AttrSizedOperandSegments trait.
void dispatchIndexOpFoldResult(OpFoldResult ofr,
SmallVectorImpl<Value> &dynamicVec,
SmallVectorImpl<int64_t> &staticVec,
int64_t sentinel) {
auto v = ofr.dyn_cast<Value>();
if (!v) {
APInt apInt = ofr.get<Attribute>().cast<IntegerAttr>().getValue();
staticVec.push_back(apInt.getSExtValue());
return;
}
dynamicVec.push_back(v);
staticVec.push_back(sentinel);
}
void dispatchIndexOpFoldResults(ArrayRef<OpFoldResult> ofrs,
SmallVectorImpl<Value> &dynamicVec,
SmallVectorImpl<int64_t> &staticVec,
int64_t sentinel) {
for (OpFoldResult ofr : ofrs)
dispatchIndexOpFoldResult(ofr, dynamicVec, staticVec, sentinel);
}
/// Extract int64_t values from the assumed ArrayAttr of IntegerAttr.
SmallVector<int64_t, 4> extractFromI64ArrayAttr(Attribute attr) {
return llvm::to_vector<4>(
llvm::map_range(attr.cast<ArrayAttr>(), [](Attribute a) -> int64_t {
return a.cast<IntegerAttr>().getInt();
}));
}
/// Given a value, try to extract a constant Attribute. If this fails, return
/// the original value.
OpFoldResult getAsOpFoldResult(Value val) {
Attribute attr;
if (matchPattern(val, m_Constant(&attr)))
return attr;
return val;
}
/// Given an array of values, try to extract a constant Attribute from each
/// value. If this fails, return the original value.
SmallVector<OpFoldResult> getAsOpFoldResult(ArrayRef<Value> values) {
return llvm::to_vector<4>(
llvm::map_range(values, [](Value v) { return getAsOpFoldResult(v); }));
}
/// If ofr is a constant integer or an IntegerAttr, return the integer.
Optional<int64_t> getConstantIntValue(OpFoldResult ofr) {
// Case 1: Check for Constant integer.
if (auto val = ofr.dyn_cast<Value>()) {
APSInt intVal;
if (matchPattern(val, m_ConstantInt(&intVal)))
return intVal.getSExtValue();
return llvm::None;
}
// Case 2: Check for IntegerAttr.
Attribute attr = ofr.dyn_cast<Attribute>();
if (auto intAttr = attr.dyn_cast_or_null<IntegerAttr>())
return intAttr.getValue().getSExtValue();
return llvm::None;
}
/// Return true if ofr1 and ofr2 are the same integer constant attribute values
/// or the same SSA value.
/// Ignore integer bitwidth and type mismatch that come from the fact there is
/// no IndexAttr and that IndexType has no bitwidth.
bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2) {
auto cst1 = getConstantIntValue(ofr1), cst2 = getConstantIntValue(ofr2);
if (cst1 && cst2 && *cst1 == *cst2)
return true;
auto v1 = ofr1.dyn_cast<Value>(), v2 = ofr2.dyn_cast<Value>();
return v1 && v1 == v2;
}
} // namespace mlir
| 1,430 |
2,134 | <filename>src/test/java/org/http4k/example/JavaExample.java
package org.http4k.example;
import okhttp3.OkHttpClient;
import org.http4k.client.DualSyncAsyncHttpHandler;
import org.http4k.client.OkHttp;
import org.http4k.core.BodyMode;
import org.http4k.core.Filter;
import org.http4k.core.Request;
import org.http4k.core.Response;
import org.http4k.core.Status;
import org.http4k.routing.RoutingHttpHandler;
import org.http4k.server.Http4kServer;
import org.http4k.server.SunHttp;
import static org.http4k.core.Http4kKt.then;
import static org.http4k.core.Method.POST;
import static org.http4k.routing.RoutingKt.bind;
import static org.http4k.routing.RoutingKt.routes;
import static org.http4k.server.Http4kServerKt.asServer;
public class JavaExample {
public static void main(String[] args) {
Filter f = next -> req -> next.invoke(req.body(req.bodyString().substring(0, 5)));
RoutingHttpHandler routing = routes(bind("/path", POST).to(req -> Response.create(Status.ACCEPTED)));
RoutingHttpHandler app = then(f, routing);
Http4kServer http4kServer = asServer(app, new SunHttp(8000));
http4kServer.start();
DualSyncAsyncHttpHandler client = OkHttp.create(new OkHttpClient.Builder().build(), BodyMode.Memory.INSTANCE);
System.out.println(client.invoke(Request.create(POST, "http://localhost:8000/path").body("1234567890")));
http4kServer.stop();
}
}
| 532 |
1,564 | package org.modelmapper.functional.inherit;
import java.util.HashMap;
import java.util.Map;
import org.modelmapper.AbstractTest;
import org.modelmapper.PropertyMap;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
@Test
public class ValueReaderInheritanceTest extends AbstractTest {
static class Dest {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@BeforeMethod
public void setUp() {
modelMapper.getConfiguration().setImplicitMappingEnabled(false);
}
@SuppressWarnings("unchecked")
public void shouldInclude() throws Exception {
modelMapper.addMappings(new PropertyMap<Map<String, Object>, Dest>() {
@Override
protected void configure() {
map(source("name")).setName(null);
map(source("address")).setAddress(null);
}
}).include(HashMap.class, Dest.class);
Map<String, Object> src = new HashMap<String, Object>();
src.put("name", "foo");
src.put("address", "bar");
Dest dest = modelMapper.map(src, Dest.class);
assertEquals(dest.name, "foo");
assertEquals(dest.address, "bar");
}
public void shouldNotMapIfNotInclude() throws Exception {
modelMapper.addMappings(new PropertyMap<Map<String, Object>, Dest>() {
@Override
protected void configure() {
map(source("name")).setName(null);
map(source("address")).setAddress(null);
}
});
Map<String, Object> src = new HashMap<String, Object>();
src.put("name", "foo");
src.put("address", "bar");
Dest dest = modelMapper.map(src, Dest.class);
assertNull(dest.name);
assertNull(dest.address);
}
}
| 732 |
1,009 | /*
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/idpl.html.
*
* Software distributed under the License is distributed on
* an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
*
* The Original Code was created by <NAME>. for IBPhoenix.
* The development of the Original Code was sponsored by <NAME>.
*
* Copyright (c) 2001 IBPhoenix
* All Rights Reserved.
*/
// stdafx.cpp : source file that includes just the standard includes
// fbudf.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 307 |
310 | {
"name": "Slim Folio Pro",
"description": "A keyboard case for the iPad Pro.",
"url": "https://www.logitech.com/en-us/products/ipad-keyboards/slim-folio-pro.html"
}
| 66 |
1,940 | <gh_stars>1000+
package org.opentech.fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.widget.ImageView;
import org.opentech.R;
public class RoomImageDialogFragment extends DialogFragment {
public static final String TAG = "room";
public static RoomImageDialogFragment newInstance(String roomName, @DrawableRes int imageResId) {
RoomImageDialogFragment f = new RoomImageDialogFragment();
Bundle args = new Bundle();
args.putString("roomName", roomName);
args.putInt("imageResId", imageResId);
f.setArguments(args);
return f;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
ImageView imageView = new ImageView(getActivity());
imageView.setImageResource(args.getInt("imageResId"));
Dialog dialog = new AlertDialog.Builder(getActivity()).setTitle(args.getString("roomName")).setView(imageView).create();
dialog.getWindow().getAttributes().windowAnimations = R.style.RoomImageDialogAnimations;
return dialog;
}
public void show(FragmentManager manager) {
show(manager, TAG);
}
}
| 500 |
2,875 | <reponame>makelove/OpenCV-Python-Tutorial
# -*- coding: utf-8 -*-
# @Time : 2017/7/12 下午8:28
# @Author : play4fun
# @File : 凸包-凸性检测-边界矩形-最小外接圆-拟合.py
# @Software: PyCharm
"""
凸包-凸性检测-边界矩形-最小外接圆-拟合.py:
"""
import cv2
import numpy as np
img=cv2.imread('../data/lightning.png',0)
image, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt=contours[0]
'''
函数 cv2.convexHull() 可以用来检测一个曲线是否具有凸性缺 并能纠 正缺 。一般来 凸性曲线总是凸出来的 至少是平的。如果有地方凹 去 了就 叫做凸性缺
例如下图中的手。红色曲线显示了手的凸包 凸性缺 双箭头标出来了。
'''
# convexHull(points, hull=None, clockwise=None, returnPoints=None)
hull = cv2.convexHull(points, hull, clockwise, returnPoints)
'''
points 我们 传入的 廓
• hull 输出 通常不需要
• clockwise 方向标志。如果 置为 True 出的凸包是顺时针 方向的。 否则为逆时针 方向。
• returnPoints 值为 True。它会 回凸包上点的坐标。如果 置 为 False 就会 回与凸包点对应的 廓上的点。
'''
hull = cv2.convexHull(cnt)
# 凸性检测
# 函数 cv2.isContourConvex() 可以可以用来检测一个曲线是不是凸的。它只能 回 True 或 False。没什么大不了的。
k = cv2.isContourConvex(cnt)
# 边界矩形
'''
直边界矩形 一个直矩形 就是没有旋转的矩形 。它不会考虑对象是否旋转。 所以边界矩形的 积不是最小的。可以使用函数 cv2.boundingRect() 查 找得到。
x y 为矩形左上角的坐标 w h 是矩形的宽和 。
'''
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
'''
旋转矩形
这里,以最小面积绘制边界矩形,因此也考虑旋转。使用的功能是cv2.minAreaRect()。它返回一个Box2D结构,其中包含以下条件 - (中心(x,y),(宽度,高度),旋转角度)。但是要绘制这个矩形,我们需要矩形的四个角。它是通过函数cv2.boxPoints()
'''
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
# 最小外接圆
# 函数 cv2.minEnclosingCircle() 可以帮我们找到一个对 的外切圆。它是所有能够包括对 的圆中 积最小的一个。
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
# 椭圆拟合
# 使用的函数为 cv2.ellipse() 回值其实就是旋 界矩形的内切圆
ellipse = cv2.fitEllipse(cnt)
#((135.34278869628906, 134.22764587402344),(57.018402099609375, 166.91265869140625),136.8311767578125)
angle=ellipse[2]
im = cv2.ellipse(img, ellipse, (0, 255, 0), 2)
# 直线拟合
# 我们可以根据一组点拟合出一条直线 同样我们也可以为图像中的白色点 拟合出一条直线。
rows, cols = img.shape[:2]
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x * vy / vx) + y)
righty = int(((cols - x) * vy / vx) + y)
cv2.line(img, (cols - 1, righty), (0, lefty), (0, 255, 0), 2)
| 1,955 |
3,084 | /*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
userscan.c
Abstract:
The implementation of user space scanning module. You have to install filter driver first, and
have filter manager load the minifilter. When filter driver is in its position, after calling
UserScanInit(...) all the subsequent CreateFile or CloseHandle would trigger the data scan if
the file is dirty.
Before the user space scanner exit, it must call UserScanFinalize(...) to cleanup the data structure
and close the listening threads.
Environment:
User mode
--*/
#include <stdio.h>
#include <assert.h>
#include "userscan.h"
#include "utility.h"
#define USER_SCAN_THREAD_COUNT 6 // the number of scanning worker threads.
typedef struct _SCANNER_MESSAGE {
//
// Required structure header.
//
FILTER_MESSAGE_HEADER MessageHeader;
//
// Private scanner-specific fields begin here.
//
AV_SCANNER_NOTIFICATION Notification;
//
// Overlapped structure: this is not really part of the message
// However we embed it here so that when we get pOvlp in
// GetQueuedCompletionStatus(...), we can restore the message
// via CONTAINING_RECORD macro.
//
OVERLAPPED Ovlp;
} SCANNER_MESSAGE, *PSCANNER_MESSAGE;
#define SCANNER_MESSAGE_SIZE (sizeof(FILTER_MESSAGE_HEADER) + sizeof(AV_SCANNER_NOTIFICATION))
typedef struct _SCANNER_REPLY_MESSAGE {
//
// Required structure header.
//
FILTER_REPLY_HEADER ReplyHeader;
//
// Private scanner-specific fields begin here.
//
ULONG ThreadId;
} SCANNER_REPLY_MESSAGE, *PSCANNER_REPLY_MESSAGE;
#define SCANNER_REPLY_MESSAGE_SIZE (sizeof(FILTER_REPLY_HEADER) + sizeof(ULONG))
//
// Local routines
//
AVSCAN_RESULT
UserScanMemoryStream(
_In_reads_bytes_(Size) PUCHAR StartingAddress,
_In_ SIZE_T Size,
_Inout_ PBOOLEAN pAbort
);
HRESULT
UserScanHandleStartScanMsg(
_In_ PUSER_SCAN_CONTEXT Context,
_In_ PSCANNER_MESSAGE Message,
_In_ PSCANNER_THREAD_CONTEXT ThreadCtx
);
HRESULT
UserScanWorker (
_Inout_ PUSER_SCAN_CONTEXT Context
);
HRESULT
UserScanListenAbortProc (
_Inout_ PUSER_SCAN_CONTEXT Context
);
DWORD
WaitForAll (
_In_ PSCANNER_THREAD_CONTEXT ScanThreadCtxes
);
HRESULT
UserScanGetThreadContextById (
_In_ DWORD ThreadId,
_In_ PUSER_SCAN_CONTEXT Context,
_Out_ PSCANNER_THREAD_CONTEXT *ScanThreadCtx
);
VOID
UserScanSynchronizedCancel (
_In_ PUSER_SCAN_CONTEXT Context
);
HRESULT
UserScanClosePorts (
_In_ PUSER_SCAN_CONTEXT Context
);
HRESULT
UserScanCleanup (
_In_ PUSER_SCAN_CONTEXT Context
);
//
// Implementation of exported routines.
// Declared in userscan.h
//
HRESULT
UserScanInit (
_Inout_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine initializes all the necessary data structures and forks listening threads.
The caller thread is responsible for calling UserScanFinalize(...) to cleanup the
data structures and close the listening threads.
Arguments:
Context - User scan context, please see userscan.h
Return Value:
S_OK if successful. Otherwise, it returns a HRESULT error value.
--*/
{
HRESULT hr = S_OK;
ULONG i = 0;
HANDLE hEvent = NULL;
PSCANNER_THREAD_CONTEXT scanThreadCtxes = NULL;
HANDLE hListenAbort = NULL;
AV_CONNECTION_CONTEXT connectionCtx = {0};
if (NULL == Context) {
return MAKE_HRESULT(SEVERITY_ERROR, 0, E_POINTER);
}
//
// Create the abort listening thead.
// This thread is particularly listening the abortion event.
//
hListenAbort = CreateThread( NULL,
0,
(LPTHREAD_START_ROUTINE)UserScanListenAbortProc,
Context,
CREATE_SUSPENDED,
NULL );
if (NULL == hListenAbort) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
//
// Initialize scan thread contexts.
//
scanThreadCtxes = HeapAlloc(GetProcessHeap(), 0, sizeof(SCANNER_THREAD_CONTEXT) * USER_SCAN_THREAD_COUNT);
if (NULL == scanThreadCtxes) {
hr = MAKE_HRESULT(SEVERITY_ERROR, 0, E_OUTOFMEMORY);
goto Cleanup;
}
ZeroMemory(scanThreadCtxes, sizeof(SCANNER_THREAD_CONTEXT) * USER_SCAN_THREAD_COUNT);
//
// Create scan listening threads.
//
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
scanThreadCtxes[i].Handle = CreateThread( NULL,
0,
(LPTHREAD_START_ROUTINE)UserScanWorker,
Context,
CREATE_SUSPENDED,
&scanThreadCtxes[i].ThreadId );
if (NULL == scanThreadCtxes[i].Handle) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
InitializeCriticalSection(&(scanThreadCtxes[i].Lock));
}
//
// Prepare the scan communication port.
//
connectionCtx.Type = AvConnectForScan;
hr = FilterConnectCommunicationPort( AV_SCAN_PORT_NAME,
0,
&connectionCtx,
sizeof(AV_CONNECTION_CONTEXT),
NULL,
&Context->ConnectionPort );
if (FAILED(hr)) {
Context->ConnectionPort = NULL;
goto Cleanup;
}
//
// Create the IO completion port for asynchronous message passing.
//
Context->Completion = CreateIoCompletionPort( Context->ConnectionPort,
NULL,
0,
USER_SCAN_THREAD_COUNT );
if ( NULL == Context->Completion ) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
Context->ScanThreadCtxes = scanThreadCtxes;
Context->AbortThreadHandle = hListenAbort;
//
// Resume all the scanning threads.
//
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
if ( ResumeThread( scanThreadCtxes[i].Handle ) == -1) {
fprintf(stderr, "[UserScanInit]: ResumeThread scan listening thread failed.\n");
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
}
//
// Resume abort listening thread.
//
if ( ResumeThread( hListenAbort ) == -1 ) {
fprintf(stderr, "[UserScanInit]: ResumeThread abort listening thread failed.\n");
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
//
// Pump messages into queue of completion port.
//
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
PSCANNER_MESSAGE msg = HeapAlloc( GetProcessHeap(), 0, sizeof( SCANNER_MESSAGE ) );
if (NULL == msg) {
hr = MAKE_HRESULT(SEVERITY_ERROR, 0, E_OUTOFMEMORY);
goto Cleanup;
}
FillMemory( &msg->Ovlp, sizeof(OVERLAPPED), 0);
hr = FilterGetMessage( Context->ConnectionPort,
&msg->MessageHeader,
FIELD_OFFSET( SCANNER_MESSAGE, Ovlp ),
&msg->Ovlp );
if (hr == HRESULT_FROM_WIN32( ERROR_IO_PENDING )) {
hr = S_OK;
} else {
fprintf(stderr, "[UserScanInit]: FilterGetMessage failed.\n");
DisplayError(hr);
HeapFree(GetProcessHeap(), 0, msg );
goto Cleanup;
}
}
return hr;
Cleanup:
if (Context->Completion && !CloseHandle(Context->Completion)) {
fprintf(stderr, "[UserScanInit] Error! Close completion port failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
if (Context->ConnectionPort && !CloseHandle(Context->ConnectionPort)) {
fprintf(stderr, "[UserScanInit] Error! Close connection port failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
if (scanThreadCtxes) {
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
if (scanThreadCtxes[i].Handle && !CloseHandle(scanThreadCtxes[i].Handle)) {
fprintf(stderr, "[UserScanInit] Error! Close scan thread failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
DeleteCriticalSection(&(scanThreadCtxes[i].Lock));
}
HeapFree(GetProcessHeap(), 0, scanThreadCtxes);
}
if (hListenAbort && !CloseHandle(hListenAbort)) {
fprintf(stderr, "[UserScanInit] Error! Close listen abort thread failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
if (hEvent && !CloseHandle(hEvent)) {
fprintf(stderr, "[UserScanInit] Error! Close event handle failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
return hr;
}
HRESULT
UserScanFinalize (
_In_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine cleans up all the necessary data structures and closes listening threads.
It does the following things:
1) Cancel all the scanning threads and wait for them to terminate.
2) Close all the thread handles
3) Close all the port handles
4) Free memory of scan thread contexts.
Arguments:
Context - User scan context, please see userscan.h
Return Value:
S_OK if successful. Otherwise, it returns a HRESULT error value.
--*/
{
HRESULT hr = S_OK;
printf("=================finalize\n");
UserScanSynchronizedCancel( Context );
printf("[UserScanFinalize]: Closing connection port\n");
hr = UserScanCleanup( Context );
return hr;
}
//
// Implementation of local routines
//
DWORD
WaitForAll (
_In_ PSCANNER_THREAD_CONTEXT ScanThreadCtxes
)
/*++
Routine Description:
A local helper function that enable the caller to wair for all the scan threads.
Arguments:
ScanThreadCtxes - Scan thread contextes.
Return Value:
Please consult WaitForMultipleObjects(...)
--*/
{
ULONG i = 0;
HANDLE hScanThreads[USER_SCAN_THREAD_COUNT] = {0};
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
hScanThreads[i] = ScanThreadCtxes[i].Handle;
}
return WaitForMultipleObjects(USER_SCAN_THREAD_COUNT, hScanThreads, TRUE, INFINITE);
}
HRESULT
UserScanGetThreadContextById (
_In_ DWORD ThreadId,
_In_ PUSER_SCAN_CONTEXT Context,
_Out_ PSCANNER_THREAD_CONTEXT *ScanThreadCtx
)
/*++
Routine Description:
This routine search for the scan thread context by its thread id.
Arguments:
ThreadId - The thread id to be searched.
Context - The user scan context.
ScanThreadCtx - Output scan thread context.
Return Value:
S_OK if found, otherwise not found.
--*/
{
HRESULT hr = S_OK;
ULONG i;
PSCANNER_THREAD_CONTEXT scanThreadCtx = Context->ScanThreadCtxes;
*ScanThreadCtx = NULL;
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
if ( ThreadId == scanThreadCtx[i].ThreadId ) {
*ScanThreadCtx = (scanThreadCtx + i);
return hr;
}
}
return MAKE_HRESULT(SEVERITY_ERROR,0,E_FAIL);
}
VOID
UserScanSynchronizedCancel (
_In_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine tries to abort all the scanning threads and wait for them to terminate.
Arguments:
Context - User scan context, please see userscan.h
Return Value:
Please consult WaitForMultipleObjects(...)
--*/
{
ULONG i;
PSCANNER_THREAD_CONTEXT scanThreadCtxes = Context->ScanThreadCtxes;
if (NULL == scanThreadCtxes) {
fprintf(stderr, "Scan thread contexes are NOT suppoed to be NULL.\n");
return;
}
//
// Tell all scanning threads that the program is going to exit.
//
Context->Finalized = TRUE;
//
// Signal cancellation events for all scanning threads.
//
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
scanThreadCtxes[i].Aborted = TRUE;
}
//
// Wake up the listening thread if it is waiting for message
// via GetQueuedCompletionStatus()
//
CancelIoEx(Context->ConnectionPort, NULL);
//
// Wait for all scan threads to complete cancellation,
// so we will be able to close the connection port and etc.
//
WaitForAll(scanThreadCtxes);
return;
}
HRESULT
UserScanClosePorts (
_In_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine cleans up all the necessary data structures and closes listening threads.
It does closing the scanning communication port and completion port.
Arguments:
Context - User scan context, please see userscan.h
Return Value:
S_OK if successful. Otherwise, it returns a HRESULT error value.
--*/
{
HRESULT hr = S_OK;
if (!CloseHandle(Context->ConnectionPort)) {
fprintf(stderr, "[UserScanFinalize]: Failed to close the connection port.\n");
hr = HRESULT_FROM_WIN32(GetLastError());
}
Context->ConnectionPort = NULL;
if (!CloseHandle(Context->Completion)) {
fprintf(stderr, "[UserScanFinalize]: Failed to close the completion port.\n");
hr = HRESULT_FROM_WIN32(GetLastError());
}
Context->Completion = NULL;
return hr;
}
HRESULT
UserScanCleanup (
_In_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine cleans up all the necessary data structures and closes listening threads.
It does closing abort thread handle and all scanning threads. It also closes the ports
by calling UserScanClosePorts(...).
Arguments:
Context - User scan context, please see userscan.h
Return Value:
S_OK if successful. Otherwise, it returns a HRESULT error value.
--*/
{
ULONG i = 0;
HRESULT hr = S_OK;
PSCANNER_THREAD_CONTEXT scanThreadCtxes = Context->ScanThreadCtxes;
if (NULL == scanThreadCtxes) {
fprintf(stderr, "Scan thread contexes are NOT suppoed to be NULL.\n");
return E_POINTER;
}
if (Context->AbortThreadHandle) {
CloseHandle( Context->AbortThreadHandle );
}
hr = UserScanClosePorts( Context );
//
// Clean up scan thread contexts
//
for (i = 0;
i < USER_SCAN_THREAD_COUNT;
i ++ ) {
if (scanThreadCtxes[i].Handle && !CloseHandle(scanThreadCtxes[i].Handle)) {
fprintf(stderr, "[UserScanInit] Error! Close scan thread failed.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
DeleteCriticalSection(&(scanThreadCtxes[i].Lock));
}
HeapFree( GetProcessHeap(), 0, scanThreadCtxes );
Context->ScanThreadCtxes = NULL;
return hr;
}
AVSCAN_RESULT
UserScanMemoryStream(
_In_reads_bytes_(Size) PUCHAR StartingAddress,
_In_ SIZE_T Size,
_Inout_ PBOOLEAN pAbort
)
/*++
Routine Description:
This routine is a naive search for virus signiture.
Note that this function is by no means efficient and scalable, but
this is not the focus of this example. Thus, an anti-virus
vendor may want to focus on and expand this function.
It will reset the abort flag if it is aborted.
Arguments:
StartingAddress - The starting address of the memory to be searched.
Size - The size of the memory.
pAbort - A pointer to a boolean that notifies the scanning should be canceled..
Infected - TRUE if this file is infected. FALSE, otherwise.
Return Value:
S_OK.
--*/
{
ULONG i;
UCHAR targetString[AV_DEFAULT_SEARCH_PATTERN_SIZE] = {0};
SIZE_T searchStringLength = AV_DEFAULT_SEARCH_PATTERN_SIZE-1;
ULONG ind;
PUCHAR p;
PUCHAR start = StartingAddress;
PUCHAR end = start + Size - searchStringLength;
//
// Decode the target pattern. We could decode only once and cache it.
//
CopyMemory( (PVOID) targetString,
AV_DEFAULT_SEARCH_PATTERN,
AV_DEFAULT_SEARCH_PATTERN_SIZE );
for (ind = 0;
ind < searchStringLength;
ind++) {
targetString[ind] = ((UCHAR)targetString[ind]) ^ AV_DEFAULT_PATTERN_XOR_KEY;
}
targetString[searchStringLength] = '\0';
//
// Scan the memory stream for the target pattern.
// If not cancelled.
//
for (p = start, i = 1;
p <= end ;
p++, i++) {
//
// If (*pAbort == TRUE), then we abort the scanning in the loop.
//
if ( *pAbort ) {
*pAbort = FALSE;
return AvScanResultUndetermined;
}
if ( !memcmp( p, targetString, searchStringLength )) {
return AvScanResultInfected;
}
}
return AvScanResultClean;
}
HRESULT
UserScanHandleStartScanMsg(
_In_ PUSER_SCAN_CONTEXT Context,
_In_ PSCANNER_MESSAGE Message,
_In_ PSCANNER_THREAD_CONTEXT ThreadCtx
)
/*++
Routine Description:
After receiving the scan request from the kernel. This routine is
the main function that handle the scan request.
This routine does not know which file it is scanning because it
does not need to know.
Its main job includes:
1) Send message to the filter to create a section object.
2) Map the view of the section.
3) Scan the memory
4) Send message to tell the filter the result of the scan
and close the section object.
Arguments:
Context - The user scan context.
Message - The message recieved from the kernel.
ThreadCtx - The scan thread context.
Return Value:
S_OK.
--*/
{
HRESULT hr = S_OK;
ULONG bytesReturned = 0;
HANDLE sectionHandle = NULL;
DWORD dwErrCode = 0;
PVOID scanAddress = NULL;
MEMORY_BASIC_INFORMATION memoryInfo;
PAV_SCANNER_NOTIFICATION notification = &Message->Notification;
COMMAND_MESSAGE commandMessage = {0};
DWORD flags = 0;
//
// Send the message to the filter to create a section object for data scan.
// If success, we would get section handle.
//
// We just have to transparently pass ScanContextId to filter, which we
// obtained from the filter previously.
//
commandMessage.Command = AvCmdCreateSectionForDataScan;
commandMessage.ScanId = notification->ScanId;
commandMessage.ScanThreadId = ThreadCtx->ThreadId;
hr = FilterSendMessage( Context->ConnectionPort,
&commandMessage,
sizeof( COMMAND_MESSAGE ),
§ionHandle,
sizeof( HANDLE ),
&bytesReturned );
if (FAILED(hr)) {
fprintf(stderr,
"[UserScanHandleStartScanMsg]: Failed to send message SendMessageToCreateSection to the minifilter.\n");
DisplayError(hr);
return hr;
}
scanAddress = MapViewOfFile( sectionHandle,
FILE_MAP_READ,
0L,
0L,
0 );
if (scanAddress == NULL) {
fprintf(stderr, "[UserScanHandleStartScanMsg]: Failed to map the view.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
goto Cleanup;
}
if( !VirtualQuery( scanAddress, &memoryInfo, sizeof(memoryInfo) )) {
fprintf(stderr, "[UserScanHandleStartScanMsg]: Failed to query the view.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
goto Cleanup;
}
//
// Data scan here.
//
commandMessage.ScanResult = UserScanMemoryStream( (PUCHAR)scanAddress,
memoryInfo.RegionSize,
&ThreadCtx->Aborted );
//
// If scanning on file open, give the pages a transient boost
// since they may soon be accessed in read operations on the
// file.
//
if (notification->Reason == AvScanOnOpen) {
flags = MEM_UNMAP_WITH_TRANSIENT_BOOST;
}
Cleanup:
if (scanAddress != NULL) {
if (!UnmapViewOfFileEx( scanAddress, flags )) {
fprintf(stderr, "[UserScanHandleStartScanMsg]: Failed to unmap the view.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
}
//
// We have to close the section handle after we finish using it.
// It is required to close the section handle here in user mode.
//
if (!CloseHandle(sectionHandle)) {
fprintf(stderr, "[UserScanHandleStartScanMsg]: Failed to close the section handle.\n");
DisplayError(HRESULT_FROM_WIN32(dwErrCode));
}
//
// Send the message to tell filter to close the section object.
// This call will set the file clean or infected depending on the scan result, and
// also trigger events and release the waiting I/O request thread.
//
commandMessage.Command = AvCmdCloseSectionForDataScan;
hr = FilterSendMessage( Context->ConnectionPort,
&commandMessage,
sizeof( COMMAND_MESSAGE ),
NULL,
0,
&bytesReturned );
if (FAILED(hr)) {
fprintf(stderr,
"[UserScanHandleStartScanMsg]: Failed to close message SendMessageToCreateSection to the minifilter.\n");
DisplayError( hr );
return hr;
}
return hr;
}
HRESULT
UserScanWorker (
_Inout_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine is the scanning worker thread procedure.
The pseudo-code of this function is as follows,
while(TRUE) {
1) Get a overlap structure from the completion port.
2) Obtain message from overlap structure.
3) Process the message via calling UserScanHandleStartScanMsg(...)
4) Pump overlap structure into completion port using FilterGetMessage(...)
}
Arguments:
Context - The user scan context.
Return Value:
S_OK if no error occurs; Otherwise, it would return appropriate HRESULT.
--*/
{
HRESULT hr = S_OK;
PSCANNER_MESSAGE message = NULL;
SCANNER_REPLY_MESSAGE replyMsg;
LPOVERLAPPED pOvlp = NULL;
DWORD outSize;
ULONG_PTR key;
BOOL success = FALSE;
PSCANNER_THREAD_CONTEXT threadCtx = NULL;
hr = UserScanGetThreadContextById( GetCurrentThreadId(), Context, &threadCtx );
if (FAILED(hr)) {
fprintf(stderr,
"[UserScanWorker]: Failed to get thread context.\n");
return hr;
}
ZeroMemory( &replyMsg, SCANNER_REPLY_MESSAGE_SIZE );
printf("Current thread handle %p, id:%u\n", threadCtx->Handle, threadCtx->ThreadId);
//
// This thread is waiting for scan message from the driver
//
for(;;) {
message = NULL;
//
// Get overlapped structure asynchronously, the overlapped structure
// was previously pumped by FilterGetMessage(...)
//
success = GetQueuedCompletionStatus( Context->Completion, &outSize, &key, &pOvlp, INFINITE );
if (!success) {
hr = HRESULT_FROM_WIN32(GetLastError());
//
// The completion port handle associated with it is closed
// while the call is outstanding, the function returns FALSE,
// *lpOverlapped will be NULL, and GetLastError will return ERROR_ABANDONED_WAIT_0
//
if (hr == E_HANDLE) {
printf("Completion port becomes unavailable.\n");
hr = S_OK;
} else if (hr == HRESULT_FROM_WIN32(ERROR_ABANDONED_WAIT_0)) {
printf("Completion port was closed.\n");
hr = S_OK;
}
break;
}
//
// Recover message strcuture from overlapped structure.
// Remember we embedded overlapped structure inside SCANNER_MESSAGE.
// This is because the overlapped structure obtained from GetQueuedCompletionStatus(...)
// is asynchronously and not guranteed in order.
//
message = CONTAINING_RECORD( pOvlp, SCANNER_MESSAGE, Ovlp );
if (AvMsgStartScanning == message->Notification.Message) {
//
// Reset the abort flag since this is a new scan request and remember
// the scan context ID. This ID will allow us to match a cancel request
// with a given scan task.
//
EnterCriticalSection(&(threadCtx->Lock));
threadCtx->Aborted = FALSE;
threadCtx->ScanId = message->Notification.ScanId;
LeaveCriticalSection(&(threadCtx->Lock));
//
// Reply the scanning worker thread handle to the filter
// This is important because the filter will also wait for the scanning thread
// in case that the scanning thread is killed before telling filter
// the scan is done or aborted.
//
ZeroMemory( &replyMsg, SCANNER_REPLY_MESSAGE_SIZE );
replyMsg.ReplyHeader.MessageId = message->MessageHeader.MessageId;
replyMsg.ThreadId = threadCtx->ThreadId;
hr = FilterReplyMessage( Context->ConnectionPort,
&replyMsg.ReplyHeader,
SCANNER_REPLY_MESSAGE_SIZE );
if (FAILED(hr)) {
fprintf(stderr,
"[UserScanWorker]: Failed to reply thread handle to the minifilter\n");
DisplayError(hr);
break;
}
hr = UserScanHandleStartScanMsg( Context, message, threadCtx );
} else {
assert( FALSE ); // This thread should not receive other kinds of message.
}
if (FAILED(hr)) {
fprintf(stderr,
"[UserScanWorker]: Failed to handle the message.\n");
}
//
// If fianlized flag is set from main thread,
// then it would break the while loop.
//
if (Context->Finalized) {
break;
}
//
// After we process the message, pump a overlapped structure into completion port again.
//
hr = FilterGetMessage( Context->ConnectionPort,
&message->MessageHeader,
FIELD_OFFSET( SCANNER_MESSAGE, Ovlp ),
&message->Ovlp );
if (hr == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)) {
printf("FilterGetMessage aborted.\n");
break;
} else if (hr != HRESULT_FROM_WIN32( ERROR_IO_PENDING )) {
fprintf(stderr,
"[UserScanWorker]: Failed to get message from the minifilter. \n0x%x, 0x%x\n",
hr, HRESULT_FROM_WIN32(GetLastError()));
DisplayError(hr);
break;
}
} // end of while(TRUE)
if (message) {
//
// Free the memory, which originally allocated at UserScanInit(...)
//
HeapFree(GetProcessHeap(), 0, message);
}
printf("***Thread id %u exiting\n", threadCtx->ThreadId);
return hr;
}
HRESULT
UserScanListenAbortProc (
_Inout_ PUSER_SCAN_CONTEXT Context
)
/*++
Routine Description:
This routine is the abort listening thread procedure.
This thread is particularly listening the abortion notifcation from the filter.
The pseudo-code of this function is as follows,
while(TRUE) {
1) Wair for and get a message from the filter via FilterGetMessage(...)
2) Find the scan thread context by its thread id.
3) Set the cancel flag to be TRUE.
}
Arguments:
Context - The user scan context.
Return Value:
S_OK if no error occurs; Otherwise, it would return appropriate HRESULT.
--*/
{
HRESULT hr = S_OK;
HANDLE abortPort = NULL; // A port for listening the abort notification from driver.
SCANNER_MESSAGE message;
DWORD dwThisThread = GetCurrentThreadId();
SCANNER_REPLY_MESSAGE replyMsg;
AV_CONNECTION_CONTEXT connectionCtx = {0};
PSCANNER_THREAD_CONTEXT threadCtx = NULL;
ZeroMemory( &message, SCANNER_MESSAGE_SIZE );
//
// Prepare the abort communication port.
//
connectionCtx.Type = AvConnectForAbort;
hr = FilterConnectCommunicationPort( AV_ABORT_PORT_NAME,
0,
&connectionCtx,
sizeof(AV_CONNECTION_CONTEXT),
NULL,
&abortPort );
if (FAILED(hr)) {
abortPort = NULL;
return hr;
}
//
// This thread is listening an scan abortion notifcation or filter unloading from the kernel
// If it receives notification, its type must be AvMsgAbortScanning or AvMsgFilterUnloading
//
for(;;) {
//
// Wait until an abort command is sent from filter.
//
hr = FilterGetMessage( abortPort,
&message.MessageHeader,
SCANNER_MESSAGE_SIZE,
NULL );
if (hr == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)) {
printf("[UserScanListenAbortProc]: FilterGetMessage aborted.\n");
hr = S_OK;
break;
} else if (FAILED(hr)) {
fprintf(stderr,
"[UserScanListenAbortProc]: Failed to get message from the minifilter.\n" );
DisplayError(hr);
continue;
}
printf("[UserScanListenAbortProc]: Got message %llu. \n", message.MessageHeader.MessageId);
if (AvMsgAbortScanning == message.Notification.Message) {
//
// After this thread receives AvMsgAbortScanning
// it does
// 1) Find the user scan thread context
// 2) Set Aborted flag to be TRUE
//
hr = UserScanGetThreadContextById(message.Notification.ScanThreadId,
Context,
&threadCtx);
if (SUCCEEDED(hr)) {
printf("[UserScanListenAbortProc]: User Set AvMsgAbortScanning\n");
//
// Without critical section here, we cannot prevent the scanner thread from
// proceeding to the next task after we check the Id and before we set the abort flag.
// In short, without critical section, it will be a TOCTTOU bug.
//
EnterCriticalSection(&(threadCtx->Lock));
if (threadCtx->ScanId == message.Notification.ScanId) {
threadCtx->Aborted = TRUE;
printf("[UserScanListenAbortProc]: %lld aborted\n", message.Notification.ScanId);
} else {
printf("[UserScanListenAbortProc]: tried to abort %lld, but current scan in this thread is %lld\n",
message.Notification.ScanId,
threadCtx->ScanId);
}
LeaveCriticalSection(&(threadCtx->Lock));
} else {
fprintf(stderr, "[UserScanListenAbortProc]: Error! UserScanGetThreadContextById failed.\n");
}
} else if (AvMsgFilterUnloading == message.Notification.Message) {
//
// After this thread receives AvMsgFilterUnloading
// it does
// 1) Cancell all the scanning threads
// 2) Wait for them to finish the cancel.
// 3) Reply to filter so that the filter can know it can close the server ports.
// 4) Close scan port, completion port, and abortion port.
// 5) Exit the process
//
UserScanSynchronizedCancel( Context );
printf("The filter is unloading, exit!\n");
ZeroMemory( &replyMsg, SCANNER_REPLY_MESSAGE_SIZE );
replyMsg.ReplyHeader.MessageId = message.MessageHeader.MessageId;
replyMsg.ThreadId = dwThisThread;
hr = FilterReplyMessage( abortPort,
&replyMsg.ReplyHeader,
SCANNER_REPLY_MESSAGE_SIZE );
if (FAILED(hr)) {
fprintf(stderr, "[UserScanListenAbortProc]: Error! FilterReplyMessage failed.\n");
}
UserScanClosePorts( Context );
CloseHandle( abortPort );
ExitProcess( 0 );
break;
} else {
assert( FALSE ); // This thread should not receive other kinds of message.
}
if (FAILED(hr)) {
fprintf(stderr, "[UserScanListenAbortProc]: Failed to handle the message.\n");
DisplayError(HRESULT_FROM_WIN32(GetLastError()));
}
} // end of while(TRUE)
if (!CloseHandle(abortPort)) {
fprintf(stderr, "[UserScanListenAbortProc]: Failed to close the connection port.\n");
}
abortPort = NULL;
return hr;
}
| 17,754 |
521 | <reponame>Fimbure/icebox-1<filename>third_party/libdwarf-20191104/tsearch/config.h
/* Nothing here, really, a placeholder to enable testing. */
#define HAVE_CONFIG_H 1
/* Define to 1 if tsearch is based on the AVL algorithm. */
/* #define TSEARCH_USE_BAL 1 */
/* Define to 1 if tsearch is based on the binary algorithm. */
/* #define TSEARCH_USE_BIN 1 */
/* Define to 1 if tsearch is based on the chepp algorithm. */
/* #define TSEARCH_USE_EPP 1 */
/* Define to 1 if tsearch is based on the hash algorithm. */
/* #define TSEARCH_USE_HASH 1 */
#define TSEARCH_USE_HASH 1
/* Define to 1 if tsearch is based on the red-black algorithm. */
/* #define TSEARCH_USE_RED 1 */
/* Assuming we have stdint.h and it has uintptr_t.
Not intended to work everywhere, the tsearch
directory stands a bit outside of libdwarf/dwarfdump. */
#define HAVE_STDINT_H 1
/* Define 1 if we have the Windows specific header stdafx.h */
#undef HAVE_STDAFX_H
/* Just for building tsearch independent of
libdwarf/dwarfdump/dwarfgen. */
#define HAVE_UNUSED_ATTRIBUTE
#ifdef HAVE_UNUSED_ATTRIBUTE
#define UNUSEDARG __attribute__ ((unused))
#else
#define UNUSEDARG
#endif
| 419 |
903 | <filename>smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TypedPropertiesBag.java
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package software.amazon.smithy.codegen.core;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.smithy.utils.MapUtils;
class TypedPropertiesBag {
private final Map<String, Object> properties;
TypedPropertiesBag(Map<String, Object> properties) {
this.properties = MapUtils.copyOf(properties);
}
/**
* Gets the additional properties of the object.
*
* @return Returns a map of additional property strings.
*/
public Map<String, Object> getProperties() {
return properties;
}
/**
* Gets a specific property if present.
*
* @param name Property to retrieve.
* @return Returns the optionally found property.
*/
public Optional<Object> getProperty(String name) {
return Optional.ofNullable(properties.get(name));
}
/**
* Gets an additional property of a specific type.
*
* @param name Name of the property to get.
* @param type Type of value to expect.
* @param <T> Type of value to expect.
* @return Returns a map of additional property strings.
* @throws IllegalArgumentException if the value is not of the given type.
*/
@SuppressWarnings("unchecked")
public <T> Optional<T> getProperty(String name, Class<T> type) {
return getProperty(name)
.map(value -> {
if (!type.isInstance(value)) {
throw new IllegalArgumentException(String.format(
"%s property `%s` of `%s` is not an instance of `%s`. Found `%s`",
getClass().getSimpleName(), name, this, type.getName(), value.getClass().getName()));
}
return (T) value;
});
}
/**
* Gets a specific additional property or throws if missing.
*
* @param name Property to retrieve.
* @return Returns the found property.
* @throws IllegalArgumentException if the property is not present.
*/
public Object expectProperty(String name) {
return getProperty(name).orElseThrow(() -> new IllegalArgumentException(String.format(
"Property `%s` is not part of %s, `%s`", name, getClass().getSimpleName(), this)));
}
/**
* Gets a specific additional property or throws if missing or if the
* property is not an instance of the given type.
*
* @param name Property to retrieve.
* @param type Type of value to expect.
* @param <T> Type of value to expect.
* @return Returns the found property.
* @throws IllegalArgumentException if the property is not present.
* @throws IllegalArgumentException if the value is not of the given type.
*/
public <T> T expectProperty(String name, Class<T> type) {
return getProperty(name, type).orElseThrow(() -> new IllegalArgumentException(String.format(
"Property `%s` is not part of %s, `%s`", name, getClass().getSimpleName(), this)));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof TypedPropertiesBag)) {
return false;
} else {
return properties.equals(((TypedPropertiesBag) o).properties);
}
}
@Override
public int hashCode() {
return Objects.hash(properties);
}
/**
* Builds a SymbolReference.
*/
abstract static class Builder<T extends Builder> {
Map<String, Object> properties = new HashMap<>();
/**
* Sets a specific custom property.
*
* @param key Key to set.
* @param value Value to set.
* @return Returns the builder.
*/
@SuppressWarnings("unchecked")
public T putProperty(String key, Object value) {
properties.put(key, value);
return (T) this;
}
/**
* Removes a specific custom property.
*
* @param key Key to remove.
* @return Returns the builder.
*/
@SuppressWarnings("unchecked")
public T removeProperty(String key) {
properties.remove(key);
return (T) this;
}
/**
* Replaces all of the custom properties.
*
* @param properties Custom properties to replace with.
* @return Returns the builder.
*/
@SuppressWarnings("unchecked")
public T properties(Map<String, Object> properties) {
this.properties.clear();
this.properties.putAll(properties);
return (T) this;
}
}
}
| 2,144 |
13,885 | // Copyright 2016 The Draco Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "draco/point_cloud/point_cloud_builder.h"
namespace draco {
PointCloudBuilder::PointCloudBuilder() {}
void PointCloudBuilder::Start(PointIndex::ValueType num_points) {
point_cloud_ = std::unique_ptr<PointCloud>(new PointCloud());
point_cloud_->set_num_points(num_points);
}
int PointCloudBuilder::AddAttribute(GeometryAttribute::Type attribute_type,
int8_t num_components, DataType data_type) {
GeometryAttribute ga;
ga.Init(attribute_type, nullptr, num_components, data_type, false,
DataTypeLength(data_type) * num_components, 0);
return point_cloud_->AddAttribute(ga, true, point_cloud_->num_points());
}
void PointCloudBuilder::SetAttributeValueForPoint(int att_id,
PointIndex point_index,
const void *attribute_value) {
PointAttribute *const att = point_cloud_->attribute(att_id);
att->SetAttributeValue(att->mapped_index(point_index), attribute_value);
}
void PointCloudBuilder::SetAttributeValuesForAllPoints(
int att_id, const void *attribute_values, int stride) {
PointAttribute *const att = point_cloud_->attribute(att_id);
const int data_stride =
DataTypeLength(att->data_type()) * att->num_components();
if (stride == 0) {
stride = data_stride;
}
if (stride == data_stride) {
// Fast copy path.
att->buffer()->Write(0, attribute_values,
point_cloud_->num_points() * data_stride);
} else {
// Copy attribute entries one by one.
for (PointIndex i(0); i < point_cloud_->num_points(); ++i) {
att->SetAttributeValue(
att->mapped_index(i),
static_cast<const uint8_t *>(attribute_values) + stride * i.value());
}
}
}
std::unique_ptr<PointCloud> PointCloudBuilder::Finalize(
bool deduplicate_points) {
if (deduplicate_points) {
#ifdef DRACO_ATTRIBUTE_VALUES_DEDUPLICATION_SUPPORTED
point_cloud_->DeduplicateAttributeValues();
#endif
#ifdef DRACO_ATTRIBUTE_INDICES_DEDUPLICATION_SUPPORTED
point_cloud_->DeduplicatePointIds();
#endif
}
return std::move(point_cloud_);
}
} // namespace draco
| 1,041 |
1,583 | <filename>src/main.py
"""This module is for thread start."""
import state
import sys
from bitmessagemain import main
from termcolor import colored
print(colored('kivy is not supported at the moment for this version..', 'red'))
sys.exit()
if __name__ == '__main__':
state.kivy = True
print("Kivy Loading......")
main()
| 109 |
647 |
#ifndef DPC_DATASTREAM_SUPPLIER_HH
#define DPC_DATASTREAM_SUPPLIER_HH
#include "../../Log/DataStream.hh"
#include "../../Log/DataStreamFactory.hh"
#include <vector>
#include "DPM/DPM_extfn.hh"
#include "DPM/DPM_run.hh"
#include "DPM/DPM_product.hh"
#include "DPM/DPM_time_constraints.hh"
/**
* This class attempts to supply DataStreams according to a set of specifications.
* @author <NAME>
*/
class DPC_datastream_supplier {
public:
/**
* Constructor.
*/
DPC_datastream_supplier( DPM_product *product );
/**
* Destructor.
*/
~DPC_datastream_supplier();
/**
* Return a DatasStream as specified by the arguments.
*/
DataStream *getDataStream( const char *VarName,
const char *ToUnits,
const char *FromUnitsHint,
DPM_run *Run,
DPM_time_constraints* time_constraints );
DataStream *getDataStream( const char *VarName,
const char *ToUnits,
const char *FromUnitsHint,
const char *Machine,
const unsigned short Port,
DPM_time_constraints* time_constraints );
private:
DPM_product *product;
DataStreamFactory *data_stream_factory;
};
#endif
| 711 |
669 | <reponame>hinzundcode/NodObjC
# This file is used with the GYP meta build system.
# http://code.google.com/p/gyp
# To build try this:
# svn co http://gyp.googlecode.com/svn/trunk gyp
# ./gyp/gyp -f make --depth=. framework.gyp
# make
{
'targets': [
{
'target_name': 'test_framework',
'product_name': 'Test Framework',
'type': 'shared_library',
'mac_bundle': 1,
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
],
},
'sources': [
'test.m'
],
'libraries': [ '-lobjc' ],
'mac_framework_headers': [
'test.h'
],
'xcode_settings': {
'INFOPLIST_FILE': 'Info.plist'
, 'GCC_DYNAMIC_NO_PIC': 'NO'
}
}
]
}
| 413 |
605 | <filename>mlir/include/mlir/TableGen/Builder.h
//===- Builder.h - Builder classes ------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Builder wrapper to simplify using TableGen Record for building
// operations/types/etc.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_TABLEGEN_BUILDER_H_
#define MLIR_TABLEGEN_BUILDER_H_
#include "mlir/Support/LLVM.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
namespace llvm {
class Init;
class Record;
class SMLoc;
} // namespace llvm
namespace mlir {
namespace tblgen {
/// Wrapper class with helper methods for accessing Builders defined in
/// TableGen.
class Builder {
public:
/// This class represents a single parameter to a builder method.
class Parameter {
public:
/// Return a string containing the C++ type of this parameter.
StringRef getCppType() const;
/// Return an optional string containing the name of this parameter. If
/// None, no name was specified for this parameter by the user.
Optional<StringRef> getName() const { return name; }
/// Return an optional string containing the default value to use for this
/// parameter.
Optional<StringRef> getDefaultValue() const;
private:
Parameter(Optional<StringRef> name, const llvm::Init *def)
: name(name), def(def) {}
/// The optional name of the parameter.
Optional<StringRef> name;
/// The tablegen definition of the parameter. This is either a StringInit,
/// or a CArg DefInit.
const llvm::Init *def;
// Allow access to the constructor.
friend Builder;
};
/// Construct a builder from the given Record instance.
Builder(const llvm::Record *record, ArrayRef<llvm::SMLoc> loc);
/// Return a list of parameters used in this build method.
ArrayRef<Parameter> getParameters() const { return parameters; }
/// Return an optional string containing the body of the builder.
Optional<StringRef> getBody() const;
protected:
/// The TableGen definition of this builder.
const llvm::Record *def;
private:
/// A collection of parameters to the builder.
SmallVector<Parameter> parameters;
};
} // namespace tblgen
} // namespace mlir
#endif // MLIR_TABLEGEN_BUILDER_H_
| 757 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.shared;
import com.yahoo.jrt.ListenFailedException;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.MessageBusParams;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* @author <NAME>
*/
public class SharedMessageBusTestCase {
@Test
public void requireThatMbusCanNotBeNull() {
try {
new SharedMessageBus(null);
fail();
} catch (NullPointerException e) {
// expected
}
}
@Test
public void requireThatMbusIsClosedOnDestroy() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
SharedMessageBus mbus = SharedMessageBus.newInstance(new MessageBusParams(),
new RPCNetworkParams()
.setSlobrokConfigId(slobrok.configId()));
mbus.release();
assertFalse(mbus.messageBus().destroy());
}
}
| 546 |
310 | {
"name": "Resolve Control",
"description": "A control panel for Davinci Resolve.",
"url": "https://www.blackmagicdesign.com/products/davinciresolve/control"
} | 55 |
321 | <reponame>RijuDasgupta9116/LintCode
"""
Given two strings, find the longest comment subsequence (LCS).
Your code should return the length of LCS.
"""
__author__ = 'Danyang'
class Solution:
def longestCommonSubsequence(self, A, B):
"""
let f(i, j) represents the LCS END WITH A[i], B[j]
f(i, j) = f(i-1, j-1)+1, if A[i] == A[j]
f(i, j) = max{f(i-1, j), f(i, j-1)}, otherwise
:param A: str
:param B: str
:return: The length of longest common subsequence of A and B.
"""
m = len(A)
n = len(B)
f = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)]
if m == 0 or n == 0:
return 0
for i in xrange(1, m+1):
for j in xrange(1, n+1):
if A[i-1] == B[j-1]:
f[i][j] = f[i-1][j-1]+1
else:
f[i][j] = max(f[i][j-1], f[i-1][j])
return f[-1][-1] | 528 |
16,461 | #import "ABI43_0_0REATransition.h"
@interface ABI43_0_0REATransitionGroup : ABI43_0_0REATransition
@property (nonatomic) BOOL sequence;
@property (nonatomic) NSArray *transitions;
- (instancetype)initWithConfig:(NSDictionary *)config;
@end
@interface ABI43_0_0REAVisibilityTransition : ABI43_0_0REATransition
@property (nonatomic) ABI43_0_0REATransitionAnimationType animationType;
- (ABI43_0_0REATransitionAnimation *)appearView:(UIView*)view inParent:(UIView*)parent;
- (ABI43_0_0REATransitionAnimation *)disappearView:(UIView*)view fromParent:(UIView*)parent;
- (instancetype)initWithConfig:(NSDictionary *)config;
@end
@interface ABI43_0_0REAInTransition : ABI43_0_0REAVisibilityTransition
- (instancetype)initWithConfig:(NSDictionary *)config;
@end
@interface ABI43_0_0REAOutTransition : ABI43_0_0REAVisibilityTransition
- (instancetype)initWithConfig:(NSDictionary *)config;
@end
@interface ABI43_0_0REAChangeTransition : ABI43_0_0REATransition
- (instancetype)initWithConfig:(NSDictionary *)config;
@end
| 384 |
12,718 | <reponame>dylux/sail-riscv
/*============================================================================
This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by <NAME>.
Copyright 2017 The Regents of the University of California. All rights
reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#ifndef opts_GCC_h
#define opts_GCC_h 1
#ifdef INLINE
#include <stdint.h>
#include "primitiveTypes.h"
#ifdef SOFTFLOAT_BUILTIN_CLZ
INLINE uint_fast8_t softfloat_countLeadingZeros16( uint16_t a )
{ return a ? __builtin_clz( a ) - 16 : 16; }
#define softfloat_countLeadingZeros16 softfloat_countLeadingZeros16
INLINE uint_fast8_t softfloat_countLeadingZeros32( uint32_t a )
{ return a ? __builtin_clz( a ) : 32; }
#define softfloat_countLeadingZeros32 softfloat_countLeadingZeros32
INLINE uint_fast8_t softfloat_countLeadingZeros64( uint64_t a )
{ return a ? __builtin_clzll( a ) : 64; }
#define softfloat_countLeadingZeros64 softfloat_countLeadingZeros64
#endif
#ifdef SOFTFLOAT_INTRINSIC_INT128
INLINE struct uint128 softfloat_mul64ByShifted32To128( uint64_t a, uint32_t b )
{
union { unsigned __int128 ui; struct uint128 s; } uZ;
uZ.ui = (unsigned __int128) a * ((uint_fast64_t) b<<32);
return uZ.s;
}
#define softfloat_mul64ByShifted32To128 softfloat_mul64ByShifted32To128
INLINE struct uint128 softfloat_mul64To128( uint64_t a, uint64_t b )
{
union { unsigned __int128 ui; struct uint128 s; } uZ;
uZ.ui = (unsigned __int128) a * b;
return uZ.s;
}
#define softfloat_mul64To128 softfloat_mul64To128
INLINE
struct uint128 softfloat_mul128By32( uint64_t a64, uint64_t a0, uint32_t b )
{
union { unsigned __int128 ui; struct uint128 s; } uZ;
uZ.ui = ((unsigned __int128) a64<<64 | a0) * b;
return uZ.s;
}
#define softfloat_mul128By32 softfloat_mul128By32
INLINE
void
softfloat_mul128To256M(
uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0, uint64_t *zPtr )
{
unsigned __int128 z0, mid1, mid, z128;
z0 = (unsigned __int128) a0 * b0;
mid1 = (unsigned __int128) a64 * b0;
mid = mid1 + (unsigned __int128) a0 * b64;
z128 = (unsigned __int128) a64 * b64;
z128 += (unsigned __int128) (mid < mid1)<<64 | mid>>64;
mid <<= 64;
z0 += mid;
z128 += (z0 < mid);
zPtr[indexWord( 4, 0 )] = z0;
zPtr[indexWord( 4, 1 )] = z0>>64;
zPtr[indexWord( 4, 2 )] = z128;
zPtr[indexWord( 4, 3 )] = z128>>64;
}
#define softfloat_mul128To256M softfloat_mul128To256M
#endif
#endif
#endif
| 1,547 |
72,551 | #import <Foundation/Foundation.h>
#define MY_ERROR_ENUM(_type, _name, _domain) \
enum _name : _type _name; \
enum __attribute__((ns_error_domain(_domain))) _name : _type
@class NSString;
extern NSString *const TestErrorDomain;
typedef MY_ERROR_ENUM(int, TestError, TestErrorDomain) {
TENone,
TEOne,
TETwo,
};
extern NSString *const ExhaustiveErrorDomain;
typedef MY_ERROR_ENUM(int, ExhaustiveError, ExhaustiveErrorDomain) {
EENone,
EEOne,
EETwo,
} __attribute__((enum_extensibility(closed)));
extern NSString *const OtherErrorDomain;
typedef MY_ERROR_ENUM(int, OtherErrorCode, OtherErrorDomain) {
OtherA,
OtherB,
OtherC,
};
extern NSString *TypedefOnlyErrorDomain;
typedef enum __attribute__((ns_error_domain(TypedefOnlyErrorDomain))) {
TypedefOnlyErrorBadness
} TypedefOnlyError;
TestError getErr(void);
ExhaustiveError getExhaustiveErr(void);
| 407 |
3,269 | // Time: O(m + n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* prev_first = nullptr, *last = list1;
for (int i = 0; i < b; ++i) {
if (i == a - 1) {
prev_first = last;
}
last = last->next;
}
prev_first->next = list2;
for (; list2->next; list2 = list2->next);
list2->next = last->next;
last->next = nullptr;
return list1;
}
};
| 392 |
3,200 | /**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "backend/kernel_compiler/cpu/ps/embedding_look_up_proxy_kernel.h"
#include <vector>
#include <algorithm>
#include "ps/worker.h"
#include "ps/util.h"
namespace mindspore {
namespace kernel {
namespace ps {
constexpr size_t kEmbeddingLookUpProxyInputsNum = 2;
constexpr size_t kEmbeddingLookUpProxyOutputsNum = 1;
void EmbeddingLookUpProxyKernel::InitKernel(const CNodePtr &kernel_node) {
MS_EXCEPTION_IF_NULL(kernel_node);
EmbeddingLookUpCPUKernel::InitKernel(kernel_node);
auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0);
auto indices_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 1);
auto output_shape = AnfAlgo::GetOutputInferShape(kernel_node, 0);
size_t axis = kShape2dDims - input_shape.size();
if (input_shape.empty() || input_shape.size() > kShape2dDims) {
MS_LOG(EXCEPTION) << "Input shape should not empty or greater than " << kShape2dDims << "-D, but got "
<< input_shape.size();
}
for (auto dim : input_shape) {
input_dims_ *= dim;
}
if (input_dims_ * sizeof(float) > INT_MAX) {
MS_LOG(EXCEPTION) << "PS mode embedding lookup max embedding table size is " << INT_MAX << ", current shape "
<< input_shape << " is too large.";
}
if (mindspore::ps::PSContext::instance()->is_worker()) {
key_ = AnfAlgo::GetNodeAttr<size_t>(kernel_node, kAttrPsKey);
}
std::vector<float> values;
(void)std::transform(input_shape.begin(), input_shape.end(), std::back_inserter(values),
[](size_t dim) -> float { return SizeToFloat(dim); });
(void)std::transform(indices_shape.begin(), indices_shape.end(), std::back_inserter(values),
[](size_t dim) -> float { return SizeToFloat(dim); });
(void)std::transform(output_shape.begin(), output_shape.end(), std::back_inserter(values),
[](size_t dim) -> float { return SizeToFloat(dim); });
MS_LOG(INFO) << "Init embedding lookup proxy kernel, input shape:" << input_shape
<< ", indices_shape:" << indices_shape << ", output_shape:" << output_shape;
if (mindspore::ps::PSContext::instance()->is_worker()) {
mindspore::ps::Worker::GetInstance().AddEmbeddingTable(key_, input_shape[axis]);
mindspore::ps::ParamInitInfoMessage info;
if (!mindspore::ps::Worker::GetInstance().InitPSEmbeddingTable(key_, input_shape, indices_shape, output_shape,
info)) {
MS_LOG(EXCEPTION) << "InitPSEmbeddingTable failed.";
}
}
}
bool EmbeddingLookUpProxyKernel::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> &,
const std::vector<kernel::AddressPtr> &outputs) {
CHECK_KERNEL_INPUTS_NUM(inputs.size(), kEmbeddingLookUpProxyInputsNum, kernel_name_);
CHECK_KERNEL_OUTPUTS_NUM(outputs.size(), kEmbeddingLookUpProxyOutputsNum, kernel_name_);
auto indices_addr = reinterpret_cast<int *>(inputs[1]->addr);
auto output_addr = reinterpret_cast<float *>(outputs[0]->addr);
size_t input_size = inputs[1]->size;
size_t output_size = outputs[0]->size;
size_t size = input_size / sizeof(int);
std::vector<int> lookup_ids(size, 0);
std::vector<float> lookup_result(output_size / sizeof(float), 0);
auto ret = memcpy_s(lookup_ids.data(), lookup_ids.size() * sizeof(int), indices_addr, input_size);
if (ret != EOK) {
MS_LOG(EXCEPTION) << "Lookup id memcpy failed.";
}
if (!mindspore::ps::Worker::GetInstance().DoPSEmbeddingLookup(key_, lookup_ids, &lookup_result,
mindspore::ps::kEmbeddingLookupCmd)) {
MS_LOG(EXCEPTION) << "DoPSEmbeddingLookup failed.";
}
auto ret2 = memcpy_s(output_addr, outputs[0]->size, lookup_result.data(), output_size);
if (ret2 != EOK) {
MS_LOG(EXCEPTION) << "Lookup result memcpy failed.";
}
return true;
}
} // namespace ps
} // namespace kernel
} // namespace mindspore
| 1,851 |
3,857 | <filename>dev.skidfuscator.obfuscator/src/main/java/dev/skidfuscator/obf/skidasm/SkidClass.java
package dev.skidfuscator.obf.skidasm;
import lombok.Data;
import org.mapleir.asm.ClassNode;
import java.util.List;
@Data
public class SkidClass {
private final ClassNode node;
private final List<SkidGraph> graphs;
public SkidClass(ClassNode node, List<SkidGraph> graphs) {
this.node = node;
this.graphs = graphs;
}
}
| 180 |
815 | <reponame>xj361685640/ParaView<gh_stars>100-1000
/*=========================================================================
Program: ParaView
Module: pqAnimationShortcutDecorator.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqAnimationShortcutDecorator.h"
#include "pqAnimationShortcutWidget.h"
#include "pqCoreUtilities.h"
#include "pqDoubleVectorPropertyWidget.h"
#include "vtkPVGeneralSettings.h"
#include "vtkSMDoubleRangeDomain.h"
#include "vtkSMIntRangeDomain.h"
#include "vtkSMRepresentationProxy.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMVectorProperty.h"
#include <QLayout>
//-----------------------------------------------------------------------------
pqAnimationShortcutDecorator::pqAnimationShortcutDecorator(pqPropertyWidget* parentWidget)
: Superclass(nullptr, parentWidget)
{
QLayout* layout = parentWidget->layout();
// Adding pqAnimationShortcutWidget
this->Widget =
new pqAnimationShortcutWidget(parentWidget, parentWidget->proxy(), parentWidget->property());
layout->addWidget(this->Widget);
// Get the current ShowShortcutAnimation setting
vtkPVGeneralSettings* generalSettings = vtkPVGeneralSettings::GetInstance();
this->Widget->setVisible(generalSettings->GetShowAnimationShortcuts());
// Connect to a slot to catch when the settings changes
pqCoreUtilities::connect(
generalSettings, vtkCommand::ModifiedEvent, this, SLOT(generalSettingsChanged()));
}
//-----------------------------------------------------------------------------
pqAnimationShortcutDecorator::~pqAnimationShortcutDecorator() = default;
//-----------------------------------------------------------------------------
bool pqAnimationShortcutDecorator::accept(pqPropertyWidget* parentWidget)
{
if (parentWidget)
{
// Test the property widget
vtkSMVectorProperty* vp = vtkSMVectorProperty::SafeDownCast(parentWidget->property());
vtkSMSourceProxy* source = vtkSMSourceProxy::SafeDownCast(parentWidget->proxy());
vtkSMRepresentationProxy* repr = vtkSMRepresentationProxy::SafeDownCast(parentWidget->proxy());
// Its proxy should be a source, but not a representation.
// Its property should be a VectorProperty of a single element
if (source && !repr && vp && vp->GetNumberOfElements() == 1 && vp->GetAnimateable())
{
bool hasRange = true;
vtkSMDomain* domain = vp->FindDomain<vtkSMDoubleRangeDomain>();
if (!domain)
{
domain = vp->FindDomain<vtkSMIntRangeDomain>();
if (!domain)
{
hasRange = false;
}
}
// And it must contain a range domain
if (hasRange)
{
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
void pqAnimationShortcutDecorator::generalSettingsChanged()
{
this->Widget->setVisible(vtkPVGeneralSettings::GetInstance()->GetShowAnimationShortcuts());
}
| 1,262 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Notre-Dame-de-Mésage","circ":"2ème circonscription","dpt":"Isère","inscrits":928,"abs":511,"votants":417,"blancs":37,"nuls":11,"exp":369,"res":[{"nuance":"REM","nom":"<NAME>","voix":271},{"nuance":"FN","nom":"M. <NAME>","voix":98}]} | 126 |
3,083 | /*
Copyright 2014 Google Inc. 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.
*/
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.LoadCancelledException;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriteriumCreator;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTree;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTreeNode;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.JCriteriumTree;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.JCriteriumTreeNode;
import com.google.security.zynamics.binnavi.ZyGraph.ZyGraphFactory;
import com.google.security.zynamics.binnavi.config.FileReadException;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;
import java.util.List;
public class SetupCriteriaGraphTest {
public void setUp() throws CouldntLoadDataException, LoadCancelledException, FileReadException,
CouldntSaveDataException {
final ZyGraph graph = ZyGraphFactory.generateTestGraph();
final CCriteriaFactory criteriaFactory = new CCriteriaFactory(graph, null, null);
final List<ICriteriumCreator> criteria = criteriaFactory.getConditions();
final CCriteriumTree m_ctree = new CCriteriumTree();
final JCriteriumTree jtree = new JCriteriumTree(m_ctree, criteria);
jtree.getModel().setRoot(
new JCriteriumTreeNode(m_ctree, m_ctree.getRoot().getCriterium(), criteria));
final CCriteriumTreeNode parent = new CCriteriumTreeNode(null);
final CCriteriumTreeNode child = new CCriteriumTreeNode(null);
m_ctree.appendNode(parent, child);
}
}
| 768 |
3,493 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import logging
from attacks.abstract_attack import AbstractAttack
import subprocess
from lib.timeout import timeout
from lib.keys_wrapper import PrivateKey
from lib.utils import rootpath
import json
logger = logging.getLogger("global_logger")
class Attack(AbstractAttack):
def attack(self, publickey, cipher=[]):
raise NotImplementedError()
e = 10000
result = os.system("lib/nsif/nsifc " + str(publickey.n))
return (str(result), None)
| 188 |
948 | <reponame>ismaelamezcua-ucol/contiki-ng<gh_stars>100-1000
#define BUILD_WITH_SHELL 1
| 40 |
1,694 | <reponame>cheneric-git/ArmsComponent<gh_stars>1000+
/*
* Copyright 2017 JessYan
*
* 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.
*/
package me.jessyan.armscomponent.gank.mvp.model.entity;
import java.io.Serializable;
/**
* ================================================
* 如果你服务器返回的数据格式固定为这种方式(这里只提供思想,服务器返回的数据格式可能不一致,可根据自家服务器返回的格式作更改)
* 指定范型即可改变 {@code data} 字段的类型, 达到重用 {@link GankBaseResponse}
* <p>
* Created by JessYan on 26/09/2016 15:19
* <a href="mailto:<EMAIL>">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class GankBaseResponse<T> implements Serializable {
private int page;
private int pageCount;
private int status;
private int totalCounts;
private T data;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getTotalCounts() {
return totalCounts;
}
public void setTotalCounts(int totalCounts) {
this.totalCounts = totalCounts;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| 838 |
310 | /*
Copyright 2011 Google Inc. 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.
Author: <EMAIL> (<NAME>)
Author: <EMAIL> (<NAME>)
*/
/*Modified by <NAME>*/
#include "lz77.h"
#include "util.h"
#include "match.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ZopfliInitLZ77Store(ZopfliLZ77Store* store) {
store->size = 0;
store->litlens = 0;
store->dists = 0;
store->symbols = 0;
}
void ZopfliCleanLZ77Store(ZopfliLZ77Store* store) {
free(store->litlens);
free(store->dists);
}
void ZopfliCopyLZ77Store(const ZopfliLZ77Store* source, ZopfliLZ77Store* dest) {
ZopfliCleanLZ77Store(dest);
dest->litlens = (unsigned short*)malloc(sizeof(*dest->litlens) * source->size);
dest->dists = (unsigned short*)malloc(sizeof(*dest->dists) * source->size);
if (!dest->litlens || !dest->dists) exit(1); /* Allocation failed. */
dest->size = source->size;
memcpy(dest->litlens, source->litlens, source->size * sizeof(*dest->dists));
memcpy(dest->dists, source->dists, source->size * sizeof(*dest->dists));
}
/*
Appends the length and distance to the LZ77 arrays of the ZopfliLZ77Store.
context must be a ZopfliLZ77Store*.
*/
static void ZopfliStoreLitLenDist(unsigned short length, unsigned char dist,
ZopfliLZ77Store* store) {
size_t size2 = store->size; /* Needed for using ZOPFLI_APPEND_DATA twice. */
ZOPFLI_APPEND_DATA(length, &store->litlens, &store->size);
ZOPFLI_APPEND_DATA(dist, (unsigned char**)&store->dists, &size2);
}
#ifndef NDEBUG
void ZopfliVerifyLenDist(const unsigned char* data, size_t datasize, size_t pos,
unsigned short dist, unsigned short length) {
assert(pos + length <= datasize);
for (size_t i = 0; i < length; i++) {
assert(data[pos - dist + i] == data[pos + i]);
}
}
#endif
static unsigned symtox(unsigned lls){
if (lls <= 279){
return 0;
}
if (lls <= 283){
return 100;
}
return 200;
}
/*
LZ4 HC - High Compression Mode of LZ4
Copyright (C) 2011-2015, <NAME>.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : https://github.com/Cyan4973/lz4
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
#include <stdint.h>
typedef uint8_t BYTE;
typedef uint16_t U16;
typedef uint32_t U32;
#define DICTIONARY_LOGSIZE 15
#define DICTIONARY_LOGSIZE3 11 //better use 9 for PNG
#define MAXD (1<<DICTIONARY_LOGSIZE)
#define MAXD3 (1<<DICTIONARY_LOGSIZE3)
#define MAX_DISTANCE MAXD - 1
#define MAX_DISTANCE3 MAXD3 - 1
#define HASH_LOG (DICTIONARY_LOGSIZE + 1)
#define HASHTABLESIZE (1 << HASH_LOG)
#define HASH_LOG3 DICTIONARY_LOGSIZE3
#define HASHTABLESIZE3 (1 << HASH_LOG3)
typedef struct
{
U32 hashTable[HASHTABLESIZE];
U16 chainTable[MAXD];
const BYTE* base; /* All index relative to this position */
U32 nextToUpdate; /* index from which to continue dictionary update */
} LZ4HC_Data_Structure;
typedef struct
{
U32 hashTable[HASHTABLESIZE3];
U16 chainTable[MAXD3];
const BYTE* base; /* All index relative to this position */
U32 nextToUpdate; /* index from which to continue dictionary update */
} LZ3HC_Data_Structure;
#ifdef __SSE4_2__
#include <nmmintrin.h>
static U32 LZ4HC_hashPtr(const void* ptr) { return _mm_crc32_u32(0, *(unsigned*)ptr) >> (32-HASH_LOG); }
static U32 LZ4HC_hashPtr3(const void* ptr) { return _mm_crc32_u32(0, (*(unsigned*)ptr) & 0xFFFFFF) >> (32-HASH_LOG3); }
#else
#define HASH_FUNCTION(i) (((i) * 2654435761U) >> (32-HASH_LOG))
#define HASH_FUNCTION3(i) (((i) * 2654435761U) >> (32-HASH_LOG3))
static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(*(unsigned*)ptr); }
static U32 LZ4HC_hashPtr3(const void* ptr) { return HASH_FUNCTION3((*(unsigned*)ptr) & 0xFFFFFF); }
#endif
static void LZ4HC_init (LZ4HC_Data_Structure* hc4, const BYTE* start)
{
memset((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
memset(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
hc4->nextToUpdate = MAXD;
hc4->base = start - MAXD;
}
static void LZ4HC_init3 (LZ3HC_Data_Structure* hc4, const BYTE* start)
{
memset((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
memset(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
hc4->nextToUpdate = MAXD3;
hc4->base = start - MAXD3;
}
/* Update chains up to ip (excluded) */
static void LZ4HC_Insert (LZ4HC_Data_Structure* hc4, const BYTE* ip)
{
U16* chainTable = hc4->chainTable;
U32* HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 target = (U32)(ip - base);
U32 idx = hc4->nextToUpdate;
while(idx < target)
{
U32 h = LZ4HC_hashPtr(base+idx);
U32 delta = idx - HashTable[h];
if (delta>MAX_DISTANCE) delta = MAX_DISTANCE;
chainTable[idx & MAX_DISTANCE] = (U16)delta;
HashTable[h] = idx;
idx++;
}
hc4->nextToUpdate = target;
}
static void LZ4HC_Insert3 (LZ3HC_Data_Structure* hc4, const BYTE* ip)
{
U16* chainTable = hc4->chainTable;
U32* HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 target = (U32)(ip - base);
U32 idx = hc4->nextToUpdate;
while(idx < target)
{
U32 h = LZ4HC_hashPtr3(base+idx);
U32 delta = idx - HashTable[h];
if (delta>MAX_DISTANCE3) delta = MAX_DISTANCE3;
chainTable[idx & MAX_DISTANCE3] = (U16)delta;
HashTable[h] = idx;
idx++;
}
hc4->nextToUpdate = target;
}
static int LZ4HC_InsertAndFindBestMatch(LZ4HC_Data_Structure* hc4, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 lowLimit = (2 * MAXD > (U32)(ip-base)) ? MAXD : (U32)(ip - base) - (MAXD - 1);
const BYTE* match;
int nbAttempts = 650; //PNG 650//ENWIK 600/700
size_t ml=3;
/* HC4 match finder */
LZ4HC_Insert(hc4, ip);
U32 matchIndex = HashTable[LZ4HC_hashPtr(ip)];
while ((matchIndex>=lowLimit) && nbAttempts)
{
nbAttempts--;
match = base + matchIndex;
if (*(unsigned*)(match+ml - 3) == *(unsigned*)(ip+ml - 3))
{
size_t mlt = GetMatch(ip, match, iLimit, iLimit - 8) - ip;
if (mlt > ml) { ml = mlt; *matchpos = match;
if (ml == ZOPFLI_MAX_MATCH){
return ZOPFLI_MAX_MATCH;
}
}
}
matchIndex -= chainTable[matchIndex & MAX_DISTANCE];
}
return (int)ml;
}
static int LZ4HC_InsertAndFindBestMatch3 (LZ3HC_Data_Structure* hc4, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
if (iLimit - ip < 3){
return 0;
}
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 lowLimit = (2 * MAXD3 > (U32)(ip-base)) ? MAXD3 : (U32)(ip - base) - (MAXD3 - 1);
/* HC3 match finder */
LZ4HC_Insert3(hc4, ip);
U32 matchIndex = HashTable[LZ4HC_hashPtr3(ip)];
unsigned val = (*(unsigned*)ip) & 0xFFFFFF;
while ((matchIndex>=lowLimit))
{
const BYTE* match = base + matchIndex;
if (((*(unsigned*)match) & 0xFFFFFF) == val) { *matchpos = match; return 3;}
matchIndex -= chainTable[matchIndex & MAX_DISTANCE3];
}
return 0;
}
#include "deflate.h"
size_t ZopfliLZ77LazyLauncher(const unsigned char* in,
size_t instart, size_t inend, unsigned fs);
size_t ZopfliLZ77LazyLauncher(const unsigned char* in,
size_t instart, size_t inend, unsigned fs) {
ZopfliLZ77Store store;
ZopfliInitLZ77Store(&store);
ZopfliOptions options;
ZopfliInitOptions(&options, 4, 0, 0);
if (fs == 3){
unsigned char x = 0;
unsigned char* ou = 0;
size_t back = 0;
ZopfliDeflate(&options, 1, in + instart, inend - instart, &x, &ou, &back);
free(ou);
return back;
}
ZopfliLZ77Lazy(&options, in,
instart, inend,
&store);
size_t ret = ZopfliCalculateBlockSize(store.litlens, store.dists, 0, store.size, 2, 0, 1);
ZopfliCleanLZ77Store(&store);
return ret;
}
void ZopfliLZ77Lazy(const ZopfliOptions* options, const unsigned char* in,
size_t instart, size_t inend,
ZopfliLZ77Store* store) {
LZ4HC_Data_Structure mmc;
LZ3HC_Data_Structure h3;
size_t i = 0;
unsigned short leng;
unsigned short dist;
unsigned lengthscore;
size_t windowstart = instart > ZOPFLI_WINDOW_SIZE
? instart - ZOPFLI_WINDOW_SIZE : 0;
unsigned prev_length = 0;
unsigned prev_match = 0;
unsigned char match_available = 0;
LZ4HC_init(&mmc, &in[windowstart]);
LZ4HC_init3(&h3, &in[instart > MAXD3 ? instart - MAXD3 : 0]);
for (i = instart; i < inend; i++) {
const BYTE* matchpos;
int y = LZ4HC_InsertAndFindBestMatch(&mmc, &in[i], &in[inend] > &in[i] + ZOPFLI_MAX_MATCH ? &in[i] + ZOPFLI_MAX_MATCH : &in[inend], &matchpos);
if (y >= 4 && i + 4 <= inend){
dist = &in[i] - matchpos;
leng = y;
}
else if (!match_available){
y = LZ4HC_InsertAndFindBestMatch3(&h3, &in[i], &in[inend], &matchpos);
if (y == 3){
leng = 3;
dist = &in[i] - matchpos;
}
else{
leng = 0;
}
}
lengthscore = leng;
if (lengthscore == 3 && dist > 1024){
--lengthscore;
}
if (lengthscore == 4 && dist > 2048){
--lengthscore;
}
if (lengthscore == 5 && dist > 4096){
--lengthscore;
}
if (match_available) {
match_available = 0;
if (lengthscore > prev_length + 1) {
ZopfliStoreLitLenDist(in[i - 1], 0, store);
if (lengthscore >= ZOPFLI_MIN_MATCH) {
match_available = 1;
prev_length = leng;
prev_match = dist;
continue;
}
} else {
/* Add previous to output. */
leng = prev_length;
dist = prev_match;
/* Add to output. */
#ifndef NDEBUG
ZopfliVerifyLenDist(in, inend, i - 1, dist, leng);
#endif
unsigned lls = ZopfliGetLengthSymbol(leng);
ZopfliStoreLitLenDist(lls + ((leng - symtox(lls)) << 9), ZopfliGetDistSymbol(dist) + 1, store);
i += leng - 2;
continue;
}
}
else if (lengthscore >= ZOPFLI_MIN_MATCH && leng < options->greed) {
match_available = 1;
prev_length = leng;
prev_match = dist;
continue;
}
/* Add to output. */
if (lengthscore >= ZOPFLI_MIN_MATCH) {
#ifndef NDEBUG
ZopfliVerifyLenDist(in, inend, i, dist, leng);
#endif
unsigned lls = ZopfliGetLengthSymbol(leng);
ZopfliStoreLitLenDist(lls + ((leng - symtox(lls)) << 9), ZopfliGetDistSymbol(dist) + 1, store);
} else {
leng = 1;
ZopfliStoreLitLenDist(in[i], 0, store);
}
i += leng - 1;
}
}
void ZopfliLZ77Counts(const unsigned short* litlens, const unsigned short* dists, size_t start, size_t end, size_t* ll_count, size_t* d_count, unsigned char symbols) {
for (unsigned i = 0; i < 288; i++) {
ll_count[i] = 0;
}
for (unsigned i = 0; i < 32; i++) {
d_count[i] = 0;
}
ll_count[256] = 1; /* End symbol. */
size_t i;
if (symbols){
#if defined(__GNUC__) && (defined(__x86_64__) || defined(_M_X64))
size_t d_count1[32] = {0};
size_t d_count2[32] = {0};
size_t d_count3[32] = {0};
const unsigned char* distc = (const unsigned char*)dists;
size_t rstart = start + ((end - start) & 15);
for (i = start; i < rstart; i++) {
d_count[distc[i]]++;
ll_count[litlens[i] & 511]++;
}
#define ANDLLS 511LLU + (511LLU << 16) + (511LLU << 32) + (511LLU << 48)
const unsigned char* ipo = &distc[rstart];
while (ipo < distc + end)
{
size_t c = *(size_t*)ipo; ipo += 8;
size_t c1 = *(size_t*)ipo; ipo += 8;
d_count[(unsigned char) c ]++;
d_count1[(unsigned char)(c>>8) ]++;
d_count2[(unsigned char)(c>>16)]++;
d_count3[(unsigned char)(c>>24) ]++;
d_count[(unsigned char) (c>>32) ]++;
d_count1[(unsigned char)(c>>40) ]++;
d_count2[(unsigned char)(c>>48)]++;
d_count3[ (c>>56) ]++;
d_count[(unsigned char) c1 ]++;
d_count1[(unsigned char)(c1>>8) ]++;
d_count2[(unsigned char)(c1>>16)]++;
d_count3[(unsigned char)(c1>>24) ]++;
d_count[(unsigned char) (c1>>32) ]++;
d_count1[(unsigned char)(c1>>40) ]++;
d_count2[(unsigned char)(c1>>48)]++;
d_count3[ (c1>>56) ]++;
}
for (i = 0; i < 32; i++){
d_count[i] += d_count1[i] + d_count2[i] + d_count3[i];
}
for (i = 0; i < 31; i++) {
d_count[i] = d_count[i + 1];
}
size_t ll_count1[288] = {0};
size_t ll_count2[288] = {0};
size_t ll_count3[288] = {0};
const unsigned short* ip = &litlens[rstart];
while (ip < litlens + end)
{
size_t c = (*(size_t*)ip) & ANDLLS; ip += 4;
size_t c1 = (*(size_t*)ip) & ANDLLS; ip += 4;
ll_count[(unsigned short) c ]++;
ll_count1[(unsigned short)(c>>16) ]++;
ll_count2[(unsigned short)(c>>32)]++;
ll_count3[ c>>48 ]++;
ll_count[(unsigned short) c1 ]++;
ll_count1[(unsigned short)(c1>>16) ]++;
ll_count2[(unsigned short)(c1>>32)]++;
ll_count3[ c1>>48 ]++;
c = (*(size_t*)ip) & ANDLLS; ip += 4;
c1 = (*(size_t*)ip) & ANDLLS; ip += 4;
ll_count[(unsigned short) c ]++;
ll_count1[(unsigned short)(c>>16) ]++;
ll_count2[(unsigned short)(c>>32)]++;
ll_count3[ c>>48 ]++;
ll_count[(unsigned short) c1 ]++;
ll_count1[(unsigned short)(c1>>16) ]++;
ll_count2[(unsigned short)(c1>>32)]++;
ll_count3[ c1>>48 ]++;
}
for (i = 0; i < 288; i++){
ll_count[i] += ll_count1[i] + ll_count2[i] + ll_count3[i];
}
#else
const unsigned char* distc = (const unsigned char*)dists;
for (i = start; i < end; i++) {
d_count[distc[i]]++;
}
for (i = 0; i < 31; i++) {
d_count[i] = d_count[i + 1];
}
for (i = start; i < end; i++) {
ll_count[litlens[i] & 511]++;
}
#endif
return;
}
size_t lenarrything[515] = {0};
size_t lenarrything2[515] = {0};
size_t d_count2[64] = {0};
size_t* dc = d_count2 + 1;
size_t* dc2 = d_count2 + 32;
if ((end - start) % 2){
lenarrything[litlens[start] + !dists[start] * 259]++;
dc[ZopfliGetDistSymbol(dists[start])]++;
start++;
}
for (i = start; i < end; i++) {
lenarrything[litlens[i] + !dists[i] * 259]++;
dc[ZopfliGetDistSymbol(dists[i])]++;
i++;
lenarrything2[litlens[i] + !dists[i] * 259]++;
dc2[ZopfliGetDistSymbol(dists[i])]++;
}
for (i = 0; i < 256; i++){
ll_count[i] = lenarrything[i + 259] + lenarrything2[i + 259];
}
for (i = 3; i < 259; i++){
ll_count[ZopfliGetLengthSymbol(i)] += lenarrything[i] + lenarrything2[i];
}
for (i = 0; i < 30; i++){
d_count[i] = dc[i] + dc2[i];
}
}
| 7,541 |
5,169 | <filename>Specs/2/1/4/iDevs/0.1.0/iDevs.podspec.json
{
"name": "iDevs",
"version": "0.1.0",
"summary": "iOS 工具库合集",
"description": "iOS 工具库开发工具合集",
"homepage": "https://github.com/yaochenfeng/iDevs",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"yaochenfeng": "<EMAIL>"
},
"source": {
"git": "https://github.com/yaochenfeng/iDevs.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "8.0"
},
"ios": {
"vendored_frameworks": "iDevs/Frameworks/*.framework",
"frameworks": [
"AVFoundation",
"AudioToolbox"
],
"libraries": "sqlite3"
},
"resources": "iDevs/Frameworks/ATSDK.framework/Versions/A/Resources/*"
}
| 357 |
558 | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, <NAME>, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: <NAME> <<EMAIL>>
// Author: <NAME> <<EMAIL>>
// ==========================================================================
// Implementation of the StringSet specialization Dependent<Tight>, the
// the default specialization of Dependent<>.
// ==========================================================================
#ifndef SEQAN_SEQUENCE_STRING_SET_DEPENDENT_TIGHT_H_
#define SEQAN_SEQUENCE_STRING_SET_DEPENDENT_TIGHT_H_
namespace seqan {
// ============================================================================
// Forwards
// ============================================================================
// ============================================================================
// Tags, Classes, Enums
// ============================================================================
// TODO(holtgrew): Change name of specialization to Dependent StringSet.
/*!
* @class DependentStringSet Dependent StringSet
* @extends StringSet
* @headerfile <seqan/sequence.h>
* @brief StringSet implementation that only stores pointers to strings in other string sets.
*
* @signature template <typename TString, typename TSpec>
* class StringSet<TString, Depedent<TSpec> >;
*
* @tparam TString The type of the string to store in the string set.
* @tparam TSpec Tag for further specializing the string set.
*
* The class is not usable itself, only its subclasses @link TightDependentStringSet @endlink and
* @link GenerousDependentStringSet @endlink are.
*/
/*!
* @class TightDependentStringSet Tight Dependent StringSet
* @extends DependentStringSet
* @headerfile <seqan/sequence.h>
* @brief Very space efficient Dependent StringSet implementation.
*
* @signature template <typename TString>
* class StringSet<TString, Depedent<Tight> >;
*
* @tparam TString The type of the string to store in the string set.
*
* See @link GenerousDependentStringSet @endlink for a Dependent StringSet implementation that allows for more
* efficient access to strings in the container via ids at the cost of higher memory usage.
*/
/**
.Spec.Dependent:
..summary:A string set storing references of the strings.
..cat:Sequences
..general:Class.StringSet
..signature:StringSet<TString, Dependent<TSpec> >
..param.TString:The string type.
...type:Class.String
..param.TSpec:The specializing type for the dependent string set.
...default:$Tight$
...remarks:Possible values are $Tight$ or $Generous$
...remarks:$Tight$ is very space efficient whereas $Generous$ provides fast access to the strings in the container via ids.
..include:seqan/sequence.h
*/
// Default id holder string set
template <typename TSpec = Tight>
struct Dependent;
// StringSet with individual sequences in a tight string of string pointers and corr. IDs
template <typename TString>
class StringSet<TString, Dependent<Tight> >
{
public:
typedef String<TString *> TStrings;
typedef typename Id<StringSet>::Type TIdType;
typedef typename Position<StringSet>::Type TPosition;
typedef String<TIdType> TIds;
typedef std::map<TIdType, TPosition> TIdPosMap;
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
TIdType lastId;
TStrings strings;
TIds ids;
TIdPosMap id_pos_map;
TLimits limits;
bool limitsValid; // is true if limits contains the cumulative sum of the sequence lengths
TConcatenator concat;
StringSet()
: lastId(0), limitsValid(true)
{
SEQAN_CHECKPOINT;
appendValue(limits, 0);
}
template <typename TDefault>
StringSet(StringSet<TString, Owner<TDefault> > const & _other)
: lastId(0), limitsValid(true)
{
SEQAN_CHECKPOINT;
appendValue(limits, 0);
for (unsigned int i = 0; i < length(_other); ++i)
appendValue(*this, _other[i]);
}
// ----------------------------------------------------------------------
// Subscription operators; have to be defined in class def.
// ----------------------------------------------------------------------
template <typename TPos>
inline typename Reference<StringSet>::Type
operator[] (TPos pos)
{
SEQAN_CHECKPOINT;
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator[] (TPos pos) const
{
return value(*this, pos);
}
};
// ============================================================================
// Metafunctions
// ============================================================================
// ============================================================================
// Functions
// ============================================================================
// --------------------------------------------------------------------------
// Function appendValue()
// --------------------------------------------------------------------------
template <typename TString, typename TExpand >
inline void appendValue(
StringSet<TString, Dependent<Tight> > & me,
TString const & obj,
Tag<TExpand> tag)
{
SEQAN_CHECKPOINT;
typedef typename Position<StringSet<TString, Dependent<Tight> > >::Type TPos;
appendValue(me.limits, lengthSum(me) + length(obj), tag);
typedef typename StringSet<TString, Dependent<Tight> >::TIdType TIdType;
appendValue(me.strings, const_cast<TString*>(&obj));
TIdType last = me.lastId++;
appendValue(me.ids, last, tag);
me.id_pos_map.insert(std::make_pair(last, (TPos)(length(me.strings) - 1)));
}
// --------------------------------------------------------------------------
// Function clear()
// --------------------------------------------------------------------------
template <typename TString >
inline void clear(StringSet<TString, Dependent<Tight> >& me)
{
SEQAN_CHECKPOINT;
clear(me.strings);
me.id_pos_map.clear();
resize(me.limits, 1, Exact());
me.limitsValid = true;
clear(me.ids);
me.lastId = 0;
}
// --------------------------------------------------------------------------
// Function value()
// --------------------------------------------------------------------------
template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Dependent<Tight> > >::Type
value(StringSet<TString, Dependent<Tight> >& me, TPos pos)
{
SEQAN_CHECKPOINT;
return *me.strings[pos];
}
template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Dependent<Tight> > const >::Type
value(StringSet<TString, Dependent<Tight> >const & me, TPos pos)
{
return *me.strings[pos];
}
// --------------------------------------------------------------------------
// Function getValueById()
// --------------------------------------------------------------------------
template <typename TString, typename TId>
inline typename Reference<StringSet<TString, Dependent<Tight> > >::Type
getValueById(StringSet<TString, Dependent<Tight> > & me,
TId const id)
{
SEQAN_ASSERT_GT_MSG(me.id_pos_map.count(id), 0u, "String id must be known!");
return (value(me, me.id_pos_map.find(id)->second));
}
// --------------------------------------------------------------------------
// Function assignValueById()
// --------------------------------------------------------------------------
template<typename TString, typename TString2>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
assignValueById(StringSet<TString, Dependent<Tight> >& me,
TString2& obj)
{
SEQAN_CHECKPOINT;
appendValue(me, obj);
SEQAN_ASSERT_EQ(length(me.limits), length(me) + 1);
return positionToId(me, length(me.strings) - 1);
}
template<typename TString, typename TId1>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
assignValueById(StringSet<TString, Dependent<Tight> >& me,
TString& obj,
TId1 id)
{
SEQAN_CHECKPOINT;
typedef StringSet<TString, Dependent<Tight> > TStringSet;
typedef typename TStringSet::TIdPosMap::const_iterator TIter;
typedef typename Id<TStringSet>::Type TId;
if (me.lastId < (TId) id) me.lastId = (TId) (id + 1);
TIter pos = me.id_pos_map.find(id);
if (pos != me.id_pos_map.end()) {
me.strings[pos->second] = &obj;
me.limitsValid = false;
return id;
}
appendValue(me.strings, &obj);
appendValue(me.ids, id);
me.id_pos_map.insert(std::make_pair(id, length(me.strings) - 1));
appendValue(me.limits, lengthSum(me) + length(obj));
return id;
}
// --------------------------------------------------------------------------
// Function removeValueById()
// --------------------------------------------------------------------------
template<typename TString, typename TId>
inline void
removeValueById(StringSet<TString, Dependent<Tight> >& me, TId const id)
{
SEQAN_CHECKPOINT;
typedef StringSet<TString, Dependent<Tight> > TStringSet;
typedef typename Size<TStringSet>::Type TSize;
typedef typename TStringSet::TIdPosMap::iterator TIter;
SEQAN_ASSERT_EQ(length(me.limits), length(me) + 1);
TIter pos = me.id_pos_map.find(id);
if (pos != me.id_pos_map.end()) {
TSize remPos = pos->second;
erase(me.strings, remPos);
erase(me.ids, remPos);
me.id_pos_map.erase(pos);
resize(me.limits, length(me.limits) - 1, Generous());
for(TIter itChange = me.id_pos_map.begin(); itChange != me.id_pos_map.end(); ++itChange) {
if (itChange->second > remPos) --(itChange->second);
}
}
SEQAN_ASSERT_EQ(length(me.limits), length(me) + 1);
}
// --------------------------------------------------------------------------
// Function positionToId()
// --------------------------------------------------------------------------
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
positionToId(StringSet<TString, Dependent<Tight> > & me,
TPos const pos)
{
SEQAN_CHECKPOINT;
return me.ids[pos];
}
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
positionToId(StringSet<TString, Dependent<Tight> > const & me,
TPos const pos)
{
SEQAN_CHECKPOINT;
return me.ids[pos];
}
// --------------------------------------------------------------------------
// Function idToPosition()
// --------------------------------------------------------------------------
template <typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
idToPosition(StringSet<TString, Dependent<Tight> > const & me,
TId const id)
{
SEQAN_CHECKPOINT;
return me.id_pos_map.find(id)->second;
/*
for(unsigned i = 0; i < length(me.ids); ++i)
if ((TId) me.ids[i] == id)
return i;
return 0;
*/
}
} // namespace seqan
#endif // #ifndef SEQAN_SEQUENCE_STRING_SET_DEPENDENT_TIGHT_H_
| 4,235 |
302 | /*!
* utils.h - test utils for liburkel
* Copyright (c) 2020, <NAME> (MIT License).
* https://github.com/handshake-org/liburkel
*/
#ifndef _URKEL_UTILS_H
#define _URKEL_UTILS_H
#include <stddef.h>
#undef ASSERT
#define ASSERT(expr) do { \
if (!(expr)) \
__urkel_test_assert_fail(__FILE__, __LINE__, #expr); \
} while (0)
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define URKEL_PATH "./urkel_db_test"
#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
/* Avoid a GCC bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95189 */
# define urkel_memcmp __urkel_test_memcmp
#else
# include <string.h>
# define urkel_memcmp memcmp
#endif
typedef struct urkel_kv_s {
unsigned char key[32];
unsigned char value[64];
} urkel_kv_t;
void
__urkel_test_assert_fail(const char *file, int line, const char *expr);
int
__urkel_test_memcmp(const void *s1, const void *s2, size_t n);
urkel_kv_t *
urkel_kv_generate(size_t len);
void
urkel_kv_free(urkel_kv_t *kvs);
urkel_kv_t *
urkel_kv_dup(urkel_kv_t *kvs, size_t len);
void
urkel_kv_sort(urkel_kv_t *kvs, size_t len);
#endif /* _URKEL_UTILS_H */
| 593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.