max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,380 | <reponame>jagmeet787/Smack
/**
*
* Copyright 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
*
* 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.jivesoftware.smack.util;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
/**
* Extends a {@link HashMap} with {@link WeakReference} values, so that
* weak references which have been cleared are periodically removed from
* the map. The cleaning occurs as part of {@link #put}, after a specific
* number ({@link #cleanInterval}) of calls to {@link #put}.
*
* @param <K> The key type.
* @param <V> The value type.
*
* @author <NAME>
*/
public class CleaningWeakReferenceMap<K, V>
extends HashMap<K, WeakReference<V>> {
private static final long serialVersionUID = 0L;
/**
* The number of calls to {@link #put} after which to clean this map
* (i.e. remove cleared {@link WeakReference}s from it).
*/
private final int cleanInterval;
/**
* The number of times {@link #put} has been called on this instance
* since the last time it was {@link #clean}ed.
*/
private int numberOfInsertsSinceLastClean = 0;
/**
* Initializes a new {@link CleaningWeakReferenceMap} instance with the
* default clean interval.
*/
public CleaningWeakReferenceMap() {
this(50);
}
/**
* Initializes a new {@link CleaningWeakReferenceMap} instance with a given
* clean interval.
* @param cleanInterval the number of calls to {@link #put} after which the
* map will clean itself.
*/
public CleaningWeakReferenceMap(int cleanInterval) {
this.cleanInterval = cleanInterval;
}
@Override
public WeakReference<V> put(K key, WeakReference<V> value) {
WeakReference<V> ret = super.put(key, value);
if (numberOfInsertsSinceLastClean++ > cleanInterval) {
numberOfInsertsSinceLastClean = 0;
clean();
}
return ret;
}
/**
* Removes all cleared entries from this map (i.e. entries whose value
* is a cleared {@link WeakReference}).
*/
private void clean() {
Iterator<Entry<K, WeakReference<V>>> iter = entrySet().iterator();
while (iter.hasNext()) {
Entry<K, WeakReference<V>> e = iter.next();
if (e != null && e.getValue() != null
&& e.getValue().get() == null) {
iter.remove();
}
}
}
}
| 1,063 |
4,879 | <filename>search/retrieval.hpp<gh_stars>1000+
#pragma once
#include "search/cbv.hpp"
#include "search/feature_offset_match.hpp"
#include "search/query_params.hpp"
#include "platform/mwm_traits.hpp"
#include "coding/reader.hpp"
#include "geometry/rect2d.hpp"
#include "base/cancellable.hpp"
#include "base/checked_cast.hpp"
#include "base/dfa_helpers.hpp"
#include "base/levenshtein_dfa.hpp"
#include <cstdint>
#include <functional>
#include <memory>
#include <utility>
class MwmValue;
namespace search
{
class MwmContext;
class TokenSlice;
class Retrieval
{
public:
template<typename Value>
using TrieRoot = trie::Iterator<ValueList<Value>>;
using Features = search::CBV;
struct ExtendedFeatures
{
ExtendedFeatures() = default;
ExtendedFeatures(ExtendedFeatures const &) = default;
ExtendedFeatures(ExtendedFeatures &&) = default;
explicit ExtendedFeatures(Features const & cbv) : m_features(cbv), m_exactMatchingFeatures(cbv)
{
}
ExtendedFeatures(Features && features, Features && exactMatchingFeatures)
: m_features(std::move(features)), m_exactMatchingFeatures(std::move(exactMatchingFeatures))
{
}
ExtendedFeatures & operator=(ExtendedFeatures const &) = default;
ExtendedFeatures & operator=(ExtendedFeatures &&) = default;
ExtendedFeatures Intersect(ExtendedFeatures const & rhs) const
{
ExtendedFeatures result;
result.m_features = m_features.Intersect(rhs.m_features);
result.m_exactMatchingFeatures =
m_exactMatchingFeatures.Intersect(rhs.m_exactMatchingFeatures);
return result;
}
ExtendedFeatures Intersect(Features const & cbv) const
{
ExtendedFeatures result;
result.m_features = m_features.Intersect(cbv);
result.m_exactMatchingFeatures = m_exactMatchingFeatures.Intersect(cbv);
return result;
}
void SetFull()
{
m_features.SetFull();
m_exactMatchingFeatures.SetFull();
}
void ForEach(std::function<void(uint32_t, bool)> const & f) const
{
m_features.ForEach([&](uint64_t id) {
f(base::asserted_cast<uint32_t>(id), m_exactMatchingFeatures.HasBit(id));
});
}
Features m_features;
Features m_exactMatchingFeatures;
};
Retrieval(MwmContext const & context, base::Cancellable const & cancellable);
// Following functions retrieve all features matching to |request| from the search index.
ExtendedFeatures RetrieveAddressFeatures(
SearchTrieRequest<strings::UniStringDFA> const & request) const;
ExtendedFeatures RetrieveAddressFeatures(
SearchTrieRequest<strings::PrefixDFAModifier<strings::UniStringDFA>> const & request) const;
ExtendedFeatures RetrieveAddressFeatures(
SearchTrieRequest<strings::LevenshteinDFA> const & request) const;
ExtendedFeatures RetrieveAddressFeatures(
SearchTrieRequest<strings::PrefixDFAModifier<strings::LevenshteinDFA>> const & request) const;
// Retrieves all postcodes matching to |slice| from the search index.
Features RetrievePostcodeFeatures(TokenSlice const & slice) const;
// Retrieves all features belonging to |rect| from the geometry index.
Features RetrieveGeometryFeatures(m2::RectD const & rect, int scale) const;
private:
template <template <typename> class R, typename... Args>
ExtendedFeatures Retrieve(Args &&... args) const;
MwmContext const & m_context;
base::Cancellable const & m_cancellable;
ModelReaderPtr m_reader;
std::unique_ptr<TrieRoot<Uint64IndexValue>> m_root;
};
} // namespace search
| 1,238 |
356 | <filename>app/src/main/java/com/idrv/coach/bean/CheckUpdate.java
package com.idrv.coach.bean;
/**
* time:2016/4/5
* description:版本升级
*
* @author sunjianfei
*/
public class CheckUpdate {
String versionName;
String versionCode;
String url;
boolean upgrade;
String description;
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionCode() {
return versionCode;
}
public void setVersionCode(String versionCode) {
this.versionCode = versionCode;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isUpgrade() {
return upgrade;
}
public void setUpgrade(boolean upgrade) {
this.upgrade = upgrade;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 426 |
14,668 | // 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 "content/browser/memory/swap_metrics_driver_impl_linux.h"
#include <memory>
#include "base/memory/ptr_util.h"
#include "base/process/process_metrics.h"
#include "base/time/time.h"
#include "content/public/browser/swap_metrics_driver.h"
namespace content {
namespace {
bool HasSwap() {
base::SystemMemoryInfoKB memory_info;
if (!base::GetSystemMemoryInfo(&memory_info))
return false;
return memory_info.swap_total > 0;
}
} // namespace
// static
std::unique_ptr<SwapMetricsDriver> SwapMetricsDriver::Create(
std::unique_ptr<Delegate> delegate,
const base::TimeDelta update_interval) {
return HasSwap() ? base::WrapUnique<SwapMetricsDriver>(
new SwapMetricsDriverImplLinux(std::move(delegate),
update_interval))
: std::unique_ptr<SwapMetricsDriver>();
}
SwapMetricsDriverImplLinux::SwapMetricsDriverImplLinux(
std::unique_ptr<Delegate> delegate,
const base::TimeDelta update_interval)
: SwapMetricsDriverImpl(std::move(delegate), update_interval) {}
SwapMetricsDriverImplLinux::~SwapMetricsDriverImplLinux() = default;
SwapMetricsDriver::SwapMetricsUpdateResult
SwapMetricsDriverImplLinux::UpdateMetricsInternal(base::TimeDelta interval) {
base::VmStatInfo vmstat;
if (!base::GetVmStatInfo(&vmstat)) {
return SwapMetricsDriver::SwapMetricsUpdateResult::kSwapMetricsUpdateFailed;
}
uint64_t in_counts = vmstat.pswpin - last_pswpin_;
uint64_t out_counts = vmstat.pswpout - last_pswpout_;
last_pswpin_ = vmstat.pswpin;
last_pswpout_ = vmstat.pswpout;
if (interval.is_zero())
return SwapMetricsDriver::SwapMetricsUpdateResult::
kSwapMetricsUpdateSuccess;
delegate_->OnSwapInCount(in_counts, interval);
delegate_->OnSwapOutCount(out_counts, interval);
return SwapMetricsDriver::SwapMetricsUpdateResult::kSwapMetricsUpdateSuccess;
}
} // namespace content
| 798 |
507 | <filename>lib/mayaUsd/commands/layerEditorWindowCommand.cpp<gh_stars>100-1000
//
// Copyright 2020 Autodesk
//
// 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 "layerEditorWindowCommand.h"
#include "abstractLayerEditorWindow.h"
#include <maya/MGlobal.h>
#include <maya/MSyntax.h>
namespace {
#define DEF_FLAG(short, long) \
const char k_##long##Flag[] = #short; \
const char k_##long##FlagLong[] = #long;
#define FLAG(long) k_##long##FlagLong
DEF_FLAG(rl, reload)
DEF_FLAG(ps, proxyShape)
// query flags
DEF_FLAG(se, selectionLength)
DEF_FLAG(il, isInvalidLayer)
DEF_FLAG(sl, isSessionLayer)
DEF_FLAG(dl, isLayerDirty)
DEF_FLAG(su, isSubLayer)
DEF_FLAG(al, isAnonymousLayer)
DEF_FLAG(in, isIncomingLayer)
DEF_FLAG(ns, layerNeedsSaving)
DEF_FLAG(am, layerAppearsMuted)
DEF_FLAG(mu, layerIsMuted)
DEF_FLAG(r, layerIsReadOnly)
// edit flags
DEF_FLAG(rs, removeSubLayer)
DEF_FLAG(sv, saveEdits)
DEF_FLAG(de, discardEdits)
DEF_FLAG(aa, addAnonymousSublayer)
DEF_FLAG(ap, addParentLayer)
DEF_FLAG(lo, loadSubLayers)
DEF_FLAG(ml, muteLayer)
DEF_FLAG(pl, printLayer)
DEF_FLAG(cl, clearLayer)
DEF_FLAG(sp, selectPrimsWithSpec)
const MString WORKSPACE_CONTROL_NAME = "mayaUsdLayerEditor";
} // namespace
namespace MAYAUSD_NS_DEF {
// AbstractLayerEditorCreator implememtation
AbstractLayerEditorCreator* AbstractLayerEditorCreator::_instance = nullptr;
AbstractLayerEditorCreator* AbstractLayerEditorCreator::instance()
{
return AbstractLayerEditorCreator::_instance;
}
AbstractLayerEditorCreator::AbstractLayerEditorCreator()
{
AbstractLayerEditorCreator::_instance = this;
}
AbstractLayerEditorCreator::~AbstractLayerEditorCreator()
{
AbstractLayerEditorCreator::_instance = nullptr;
}
// AbstractLayerEditorWindow implementation
AbstractLayerEditorWindow::AbstractLayerEditorWindow(const char* panelName)
{
// this empty implementation is necessary for linking
}
AbstractLayerEditorWindow::~AbstractLayerEditorWindow()
{
// this empty implementation is necessary for linking
}
// LayerEditorWindowCommand implementation
const char LayerEditorWindowCommand::commandName[] = "mayaUsdLayerEditorWindow";
// plug-in callback to create the command object
void* LayerEditorWindowCommand::creator()
{
return static_cast<MPxCommand*>(new LayerEditorWindowCommand());
}
// plug-in callback to register the command syntax
MSyntax LayerEditorWindowCommand::createSyntax()
{
MSyntax syntax;
syntax.enableQuery(true);
syntax.enableEdit(true);
#define ADD_FLAG(name) syntax.addFlag(k_##name##Flag, k_##name##FlagLong)
ADD_FLAG(reload);
syntax.addFlag(k_proxyShapeFlag, k_proxyShapeFlagLong, MSyntax::kString);
ADD_FLAG(selectionLength);
ADD_FLAG(isInvalidLayer);
ADD_FLAG(isSessionLayer);
ADD_FLAG(isLayerDirty);
ADD_FLAG(isSubLayer);
ADD_FLAG(isAnonymousLayer);
ADD_FLAG(isIncomingLayer);
ADD_FLAG(layerNeedsSaving);
ADD_FLAG(layerAppearsMuted);
ADD_FLAG(layerIsMuted);
ADD_FLAG(layerIsReadOnly);
ADD_FLAG(removeSubLayer);
ADD_FLAG(saveEdits);
ADD_FLAG(discardEdits);
ADD_FLAG(addAnonymousSublayer);
ADD_FLAG(addParentLayer);
ADD_FLAG(loadSubLayers);
ADD_FLAG(muteLayer);
ADD_FLAG(printLayer);
ADD_FLAG(clearLayer);
ADD_FLAG(selectPrimsWithSpec);
// editor name
syntax.addArg(MSyntax::kString);
return syntax;
}
LayerEditorWindowCommand::LayerEditorWindowCommand()
{
//
}
bool LayerEditorWindowCommand::isUndoable() const
{
//
return false;
}
MStatus LayerEditorWindowCommand::doIt(const MArgList& argList)
{
const MString WINDOW_TITLE_NAME = "USD Layer Editor";
const MString DEAULT_EDITOR_NAME = "mayaUsdLayerEditor";
auto handler = AbstractLayerEditorCreator::instance();
if (!handler) {
return MS::kNotFound;
}
// get the name of the layer editor use
MArgParser argParser(syntax(), argList);
MString editorName = argParser.commandArgumentString(0);
if (editorName.length() == 0) {
editorName = DEAULT_EDITOR_NAME;
}
// get the pointer to that control
auto layerEditorWindow = handler->getWindow(editorName.asChar());
if (argParser.isQuery() || argParser.isEdit()) {
if (!layerEditorWindow) {
MString errorMsg;
errorMsg.format("layer editor named ^1s not found", editorName);
displayError(errorMsg);
return MS::kNotFound;
}
}
bool createOrShowWindow = false;
if (!argParser.isQuery()) {
if (argParser.isEdit()) {
if (argParser.isFlagSet(k_reloadFlag)) {
createOrShowWindow = true;
}
} else {
// create mode
createOrShowWindow = true;
}
}
MStatus st;
// call this always, to check for flags used in wrong mode
st = handleQueries(argParser, layerEditorWindow);
if (st != MS::kSuccess) {
return st;
}
// call this always, to check for -e mode missing
st = handleEdits(argParser, layerEditorWindow);
if (st != MS::kSuccess)
return st;
if (createOrShowWindow) {
if (layerEditorWindow) {
// Call -restore on existing workspace control to make it visible
// from whatever previous state it was in
MString restoreCommand;
restoreCommand.format("workspaceControl -e -restore ^1s", WORKSPACE_CONTROL_NAME);
MGlobal::executeCommand(restoreCommand);
} else {
bool doReload = argParser.isFlagSet(k_reloadFlag);
// If we're not reloading a workspace, we need to create a workspace control
if (!doReload) {
MString cmdString;
cmdString.format(
"workspaceControl"
" -label \"^1s\""
" -retain false"
" -deleteLater false"
" -loadImmediately true"
" -floating true"
" -initialWidth 400"
" -initialHeight 600"
" -requiredPlugin \"^2s\""
" \"^3s\"",
WINDOW_TITLE_NAME,
"mayaUsdPlugin",
WORKSPACE_CONTROL_NAME);
MGlobal::executeCommand(cmdString);
}
layerEditorWindow = handler->createWindow(editorName.asChar());
// Set the -uiScript (used to rebuild UI when reloading workspace)
// after creation so that it doesn't get executed
if (!doReload) {
const MString mCommandName = LayerEditorWindowCommand::commandName;
MString uiScriptCommand;
uiScriptCommand.format(
R"(workspaceControl -e -uiScript "^1s -reload" "^2s")",
mCommandName,
WORKSPACE_CONTROL_NAME);
MGlobal::executeCommand(uiScriptCommand);
}
}
if (argParser.isFlagSet(k_proxyShapeFlag)) {
MString proxyShapeName;
argParser.getFlagArgument(k_proxyShapeFlag, 0, proxyShapeName);
if (proxyShapeName.length() > 0) {
layerEditorWindow->selectProxyShape(proxyShapeName.asChar());
}
}
}
return MS::kSuccess;
}
void LayerEditorWindowCommand::cleanupOnPluginUnload()
{
// Close the workspace control, if it still exists.
auto handler = AbstractLayerEditorCreator::instance();
if (handler) {
MString closeCommand;
auto panels = handler->getAllPanelNames();
for (auto entry : panels) {
closeCommand.format("workspaceControl -e -close \"^1s\"", MString(entry.c_str()));
MGlobal::executeCommand(closeCommand);
}
}
}
MStatus LayerEditorWindowCommand::undoIt()
{
//
return MS::kSuccess;
}
MStatus LayerEditorWindowCommand::redoIt()
{
//
return MS::kSuccess;
}
MStatus LayerEditorWindowCommand::handleQueries(
const MArgParser& argParser,
AbstractLayerEditorWindow* layerEditor)
{
// this methis is written so that it'll return an error
// if a query flag is used in non-query mode.
bool notQuery = !argParser.isQuery();
MString errorMsg("Need -query mode for parameter ");
#define HANDLE_Q_FLAG(name) \
if (argParser.isFlagSet(FLAG(name))) { \
if (notQuery) { \
errorMsg += FLAG(name); \
displayError(errorMsg); \
return MS::kInvalidParameter; \
} \
setResult(layerEditor->name()); \
}
HANDLE_Q_FLAG(selectionLength)
HANDLE_Q_FLAG(isInvalidLayer)
HANDLE_Q_FLAG(isSessionLayer)
HANDLE_Q_FLAG(isLayerDirty)
HANDLE_Q_FLAG(isSubLayer)
HANDLE_Q_FLAG(isAnonymousLayer)
HANDLE_Q_FLAG(isIncomingLayer);
HANDLE_Q_FLAG(layerNeedsSaving)
HANDLE_Q_FLAG(layerAppearsMuted)
HANDLE_Q_FLAG(layerIsMuted)
HANDLE_Q_FLAG(layerIsReadOnly)
if (argParser.isFlagSet(FLAG(proxyShape)) && argParser.isQuery()) {
setResult(layerEditor->proxyShapeName().c_str());
}
return MS::kSuccess;
}
MStatus LayerEditorWindowCommand::handleEdits(
const MArgParser& argParser,
AbstractLayerEditorWindow* layerEditor)
{
//
// this method is written so that it'll return an error
// if a query flag is used in non-query mode.
bool notEdit = !argParser.isEdit();
MString errorMsg("Need -edit mode for parameter ");
#define HANDLE_E_FLAG(name) \
if (argParser.isFlagSet(FLAG(name))) { \
if (notEdit) { \
errorMsg += FLAG(name); \
displayError(errorMsg); \
return MS::kInvalidParameter; \
} \
layerEditor->name(); \
}
HANDLE_E_FLAG(removeSubLayer)
HANDLE_E_FLAG(saveEdits)
HANDLE_E_FLAG(discardEdits)
HANDLE_E_FLAG(addAnonymousSublayer)
HANDLE_E_FLAG(addParentLayer)
HANDLE_E_FLAG(loadSubLayers)
HANDLE_E_FLAG(muteLayer)
HANDLE_E_FLAG(printLayer)
HANDLE_E_FLAG(clearLayer)
HANDLE_E_FLAG(selectPrimsWithSpec)
return MS::kSuccess;
}
} // namespace MAYAUSD_NS_DEF
| 4,581 |
1,498 | <gh_stars>1000+
/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "interface/khronos/wf/wfc_server_api.h"
#include "interface/khronos/wf/wfc_client_ipc.h"
#include "interface/khronos/wf/wfc_ipc.h"
#include "interface/vcos/vcos.h"
#include "interface/khronos/include/WF/wfc.h"
#include "interface/khronos/wf/wfc_int.h"
#include "interface/khronos/include/EGL/eglext.h"
#define VCOS_LOG_CATEGORY (&wfc_client_server_api_log_category)
//#define WFC_FULL_LOGGING
#ifdef WFC_FULL_LOGGING
#define WFC_CLIENT_SERVER_API_LOGLEVEL VCOS_LOG_TRACE
#else
#define WFC_CLIENT_SERVER_API_LOGLEVEL VCOS_LOG_WARN
#endif
static VCOS_LOG_CAT_T wfc_client_server_api_log_category;
/** Implement "void foo(WFCContext context)" */
static VCOS_STATUS_T wfc_client_server_api_send_context(WFC_IPC_MSG_TYPE msg_type, WFCContext context)
{
WFC_IPC_MSG_CONTEXT_T msg;
msg.header.type = msg_type;
msg.context = context;
return wfc_client_ipc_send(&msg.header, sizeof(msg));
}
/** Implement "void foo(WFCNativeStreamType stream)" */
static VCOS_STATUS_T wfc_client_server_api_send_stream(WFC_IPC_MSG_TYPE msg_type, WFCNativeStreamType stream)
{
WFC_IPC_MSG_STREAM_T msg;
msg.header.type = msg_type;
msg.stream = stream;
return wfc_client_ipc_send(&msg.header, sizeof(msg));
}
/** Implement "foo(WFCNativeStreamType stream)" where a result is returned.
* This may either be as a return value, or via a pointer parameter.
*/
static VCOS_STATUS_T wfc_client_server_api_sendwait_stream(WFC_IPC_MSG_TYPE msg_type, WFCNativeStreamType stream,
void *result, size_t *result_len)
{
WFC_IPC_MSG_STREAM_T msg;
msg.header.type = msg_type;
msg.stream = stream;
return wfc_client_ipc_sendwait(&msg.header, sizeof(msg), result, result_len);
}
/* ========================================================================= */
VCOS_STATUS_T wfc_server_connect(void)
{
VCOS_STATUS_T status;
vcos_log_set_level(VCOS_LOG_CATEGORY, WFC_CLIENT_SERVER_API_LOGLEVEL);
vcos_log_register("wfccsapi", VCOS_LOG_CATEGORY);
status = wfc_client_ipc_init();
vcos_log_trace("%s: result %d", VCOS_FUNCTION, status);
if (status != VCOS_SUCCESS)
{
vcos_log_unregister(VCOS_LOG_CATEGORY);
}
return status;
}
/* ------------------------------------------------------------------------- */
void wfc_server_disconnect(void)
{
vcos_log_trace("%s: called", VCOS_FUNCTION);
if (wfc_client_ipc_deinit())
{
vcos_log_unregister(VCOS_LOG_CATEGORY);
}
}
/* ------------------------------------------------------------------------- */
void wfc_server_use_keep_alive(void)
{
wfc_client_ipc_use_keep_alive();
}
/* ------------------------------------------------------------------------- */
void wfc_server_release_keep_alive(void)
{
wfc_client_ipc_release_keep_alive();
}
/* ------------------------------------------------------------------------- */
uint32_t wfc_server_create_context(WFCContext context, uint32_t context_type,
uint32_t screen_or_stream_num, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_CREATE_CONTEXT_T msg;
VCOS_STATUS_T status;
uint32_t result = -1;
size_t result_len = sizeof(result);
vcos_log_trace("%s: context 0x%x type 0x%x num 0x%x pid 0x%x%08x", VCOS_FUNCTION,
context, context_type, screen_or_stream_num, pid_hi, pid_lo);
msg.header.type = WFC_IPC_MSG_CREATE_CONTEXT;
msg.context = context;
msg.context_type = context_type;
msg.screen_or_stream_num = screen_or_stream_num;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_sendwait(&msg.header, sizeof(msg), &result, &result_len);
vcos_log_trace("%s: status 0x%x, result 0x%x", VCOS_FUNCTION, status, result);
if (status != VCOS_SUCCESS)
result = -1;
return result;
}
/* ------------------------------------------------------------------------- */
void wfc_server_destroy_context(WFCContext context)
{
VCOS_STATUS_T status;
vcos_log_trace("%s: context 0x%x", VCOS_FUNCTION, context);
status = wfc_client_server_api_send_context(WFC_IPC_MSG_DESTROY_CONTEXT, context);
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
uint32_t wfc_server_commit_scene(WFCContext context, const WFC_SCENE_T *scene,
uint32_t flags, WFC_CALLBACK_T scene_taken_cb, void *scene_taken_data)
{
WFC_IPC_MSG_COMMIT_SCENE_T msg;
VCOS_STATUS_T status = VCOS_SUCCESS;
uint32_t result = VCOS_ENOSYS;
size_t result_len = sizeof(result);
uint32_t i;
vcos_log_trace("%s: context 0x%x commit %u elements %u flags 0x%x",
VCOS_FUNCTION, context, scene->commit_count, scene->element_count, flags);
for (i = 0; i < scene->element_count; i++)
{
vcos_log_trace("%s: element[%u] stream 0x%x", VCOS_FUNCTION, i, scene->elements[i].source_stream);
}
msg.header.type = WFC_IPC_MSG_COMMIT_SCENE;
msg.context = context;
msg.flags = flags;
msg.scene_taken_cb.ptr = scene_taken_cb;
msg.scene_taken_data.ptr = scene_taken_data;
memcpy(&msg.scene, scene, sizeof(*scene));
if (flags & WFC_SERVER_COMMIT_WAIT)
{
/* Caller will wait for callback, call cannot fail */
vcos_assert(scene_taken_cb != NULL);
vcos_assert(scene_taken_data != NULL);
}
else
{
/* Caller will not wait for callback, so need to at least wait for result. */
vcos_assert(scene_taken_cb == NULL);
vcos_assert(scene_taken_data == NULL);
}
status = wfc_client_ipc_sendwait(&msg.header, sizeof(msg), &result, &result_len);
/* Override the result if the status was an error */
if (status != VCOS_SUCCESS)
result = status;
return result;
}
/* ------------------------------------------------------------------------- */
void wfc_server_activate(WFCContext context)
{
VCOS_STATUS_T status;
vcos_log_trace("%s: context 0x%x", VCOS_FUNCTION, context);
status = wfc_client_server_api_send_context(WFC_IPC_MSG_ACTIVATE, context);
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_deactivate(WFCContext context)
{
VCOS_STATUS_T status;
vcos_log_trace("%s: context 0x%x", VCOS_FUNCTION, context);
status = wfc_client_server_api_send_context(WFC_IPC_MSG_DEACTIVATE, context);
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_set_deferral_stream(WFCContext context, WFCNativeStreamType stream)
{
WFC_IPC_MSG_SET_DEFERRAL_STREAM_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: context 0x%x stream 0x%x", VCOS_FUNCTION, context, stream);
msg.header.type = WFC_IPC_MSG_SET_DEFERRAL_STREAM;
msg.context = context;
msg.stream = stream;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
WFCNativeStreamType wfc_server_stream_create(WFCNativeStreamType stream, uint32_t flags, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_SS_CREATE_INFO_T msg;
VCOS_STATUS_T status;
WFCNativeStreamType result = WFC_INVALID_HANDLE;
size_t result_len = sizeof(result);
vcos_log_trace("%s: stream 0x%x flags 0x%x pid 0x%x%08x", VCOS_FUNCTION, stream, flags, pid_hi, pid_lo);
msg.header.type = WFC_IPC_MSG_SS_CREATE_INFO;
msg.stream = stream;
memset(&msg.info, 0, sizeof(msg.info));
msg.info.size = sizeof(msg.info);
msg.info.flags = flags;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_sendwait(&msg.header, sizeof(msg), &result, &result_len);
vcos_log_trace("%s: status 0x%x, result 0x%x", VCOS_FUNCTION, status, result);
if (status != VCOS_SUCCESS)
result = WFC_INVALID_HANDLE;
return result;
}
/* ------------------------------------------------------------------------- */
WFCNativeStreamType wfc_server_stream_create_info(WFCNativeStreamType stream, const WFC_STREAM_INFO_T *info, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_SS_CREATE_INFO_T msg;
uint32_t copy_size;
VCOS_STATUS_T status;
WFCNativeStreamType result = WFC_INVALID_HANDLE;
size_t result_len = sizeof(result);
if (!info)
{
vcos_log_error("%s: NULL info pointer passed", VCOS_FUNCTION);
return WFC_INVALID_HANDLE;
}
if (info->size < sizeof(uint32_t))
{
vcos_log_error("%s: invalid info pointer passed (size:%u)", VCOS_FUNCTION, info->size);
return WFC_INVALID_HANDLE;
}
vcos_log_trace("%s: stream 0x%x flags 0x%x pid 0x%x%08x", VCOS_FUNCTION, stream, info->flags, pid_hi, pid_lo);
msg.header.type = WFC_IPC_MSG_SS_CREATE_INFO;
msg.stream = stream;
copy_size = vcos_min(info->size, sizeof(msg.info));
memcpy(&msg.info, info, copy_size);
msg.info.size = copy_size;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_sendwait(&msg.header, sizeof(msg), &result, &result_len);
vcos_log_trace("%s: status 0x%x, result 0x%x", VCOS_FUNCTION, status, result);
if (status != VCOS_SUCCESS)
result = WFC_INVALID_HANDLE;
return result;
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_destroy(WFCNativeStreamType stream, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_SS_DESTROY_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x", VCOS_FUNCTION, stream);
msg.header.type = WFC_IPC_MSG_SS_DESTROY;
msg.stream = stream;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_on_rects_change(WFCNativeStreamType stream, WFC_CALLBACK_T rects_change_cb, void *rects_change_data)
{
WFC_IPC_MSG_SS_ON_RECTS_CHANGE_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x cb %p data %p", VCOS_FUNCTION, stream, rects_change_cb, rects_change_data);
msg.header.type = WFC_IPC_MSG_SS_ON_RECTS_CHANGE;
msg.stream = stream;
msg.rects_change_cb.ptr = rects_change_cb;
msg.rects_change_data.ptr = rects_change_data;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
if (!vcos_verify(status == VCOS_SUCCESS))
{
(*rects_change_cb)(rects_change_data);
}
}
/* ------------------------------------------------------------------------- */
uint32_t wfc_server_stream_get_rects(WFCNativeStreamType stream, int32_t rects[WFC_SERVER_STREAM_RECTS_SIZE])
{
uint32_t result;
VCOS_STATUS_T status;
WFC_IPC_MSG_SS_GET_RECTS_T reply;
size_t rects_len = sizeof(reply) - sizeof(WFC_IPC_MSG_HEADER_T);
vcos_log_trace("%s: stream 0x%x", VCOS_FUNCTION, stream);
memset(&reply, 0, sizeof(reply));
status = wfc_client_server_api_sendwait_stream(WFC_IPC_MSG_SS_GET_RECTS, stream, &reply.result, &rects_len);
if (status == VCOS_SUCCESS)
{
result = reply.result;
if (result == VCOS_SUCCESS)
{
memcpy(rects, reply.rects, WFC_SERVER_STREAM_RECTS_SIZE * sizeof(*rects));
vcos_log_trace("%s: rects (%d,%d,%d,%d) (%d,%d,%d,%d)", VCOS_FUNCTION,
rects[0], rects[1], rects[2], rects[3], rects[4], rects[5], rects[6], rects[7]);
}
else
{
vcos_log_error("%s: result %d", VCOS_FUNCTION, result);
}
}
else
{
vcos_log_error("%s: send msg status %d", VCOS_FUNCTION, status);
result = status;
}
return result;
}
/* ------------------------------------------------------------------------- */
bool wfc_server_stream_is_in_use(WFCNativeStreamType stream)
{
VCOS_STATUS_T status;
uint32_t result = 0;
size_t result_len = sizeof(result);
vcos_log_trace("%s: stream 0x%x", VCOS_FUNCTION, stream);
status = wfc_client_server_api_sendwait_stream(WFC_IPC_MSG_SS_IS_IN_USE, stream, &result, &result_len);
vcos_log_trace("%s: status 0x%x, result %u", VCOS_FUNCTION, status, result);
if (status != VCOS_SUCCESS)
result = 0;
return result != 0;
}
/* ------------------------------------------------------------------------- */
bool wfc_server_stream_allocate_images(WFCNativeStreamType stream, uint32_t width, uint32_t height, uint32_t nbufs)
{
WFC_IPC_MSG_SS_ALLOCATE_IMAGES_T msg;
VCOS_STATUS_T status;
uint32_t result = 0;
size_t result_len = sizeof(result);
vcos_log_trace("%s: stream 0x%x width %u height %u nbufs %u", VCOS_FUNCTION, stream, width, height, nbufs);
msg.header.type = WFC_IPC_MSG_SS_ALLOCATE_IMAGES;
msg.stream = stream;
msg.width = width;
msg.height = height;
msg.nbufs = nbufs;
status = wfc_client_ipc_sendwait(&msg.header, sizeof(msg), &result, &result_len);
vcos_log_trace("%s: status 0x%x result %u", VCOS_FUNCTION, status, result);
if (status != VCOS_SUCCESS)
result = 0;
return result;
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_signal_eglimage_data(WFCNativeStreamType stream,
uint32_t ustorage, uint32_t width, uint32_t height, uint32_t stride,
uint32_t offset, uint32_t format, uint32_t flags, bool flip)
{
WFC_IPC_MSG_SS_SIGNAL_EGLIMAGE_DATA_T msg;
VCOS_STATUS_T status;
memset(&msg, 0, sizeof msg);
msg.header.type = WFC_IPC_MSG_SS_SIGNAL_EGLIMAGE_DATA;
msg.stream = stream;
msg.ustorage = ustorage;
msg.width = width;
msg.height = height;
msg.stride = stride;
msg.offset = offset;
msg.format = format;
msg.flags = flags;
msg.flip = flip;
vcos_log_trace("%s: stream 0x%x image storage 0x%x",
VCOS_FUNCTION, stream, ustorage);
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_signal_mm_image_data(WFCNativeStreamType stream, uint32_t image_handle)
{
WFC_IPC_MSG_SS_SIGNAL_MM_IMAGE_DATA_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x image 0x%x", VCOS_FUNCTION, stream, image_handle);
msg.header.type = WFC_IPC_MSG_SS_SIGNAL_MM_IMAGE_DATA;
msg.stream = stream;
msg.image_handle = image_handle;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_signal_raw_pixels(WFCNativeStreamType stream,
uint32_t handle, uint32_t format, uint32_t width, uint32_t height,
uint32_t pitch, uint32_t vpitch)
{
WFC_IPC_MSG_SS_SIGNAL_RAW_PIXELS_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x image 0x%x format 0x%x width %u height %u"
" pitch %u vpitch %u",
VCOS_FUNCTION, stream, handle, format, width, height, pitch, vpitch);
msg.header.type = WFC_IPC_MSG_SS_SIGNAL_RAW_PIXELS;
msg.stream = stream;
msg.handle = handle;
msg.format = format;
msg.width = width;
msg.height = height;
msg.pitch = pitch;
msg.vpitch = vpitch;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_signal_image(WFCNativeStreamType stream,
const WFC_STREAM_IMAGE_T *image)
{
WFC_IPC_MSG_SS_SIGNAL_IMAGE_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x type 0x%x handle 0x%x "
" format 0x%x protection 0x%x width %u height %u "
" pitch %u vpitch %u",
VCOS_FUNCTION, stream, image->type, image->handle,
image->format, image->protection, image->width, image->height,
image->pitch, image->vpitch);
msg.header.type = WFC_IPC_MSG_SS_SIGNAL_IMAGE;
msg.stream = stream;
if vcos_verify(image->length <= sizeof(msg.image))
{
msg.image = *image;
}
else
{
/* Client is newer than VC ? */
memcpy(&msg.image, image, sizeof(msg.image));
msg.image.length = sizeof(msg.image);
}
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_register(WFCNativeStreamType stream, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_SS_REGISTER_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x pid 0x%x%08x", VCOS_FUNCTION, stream, pid_hi, pid_lo);
msg.header.type = WFC_IPC_MSG_SS_REGISTER;
msg.stream = stream;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_unregister(WFCNativeStreamType stream, uint32_t pid_lo, uint32_t pid_hi)
{
WFC_IPC_MSG_SS_UNREGISTER_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x pid 0x%x%08x", VCOS_FUNCTION, stream, pid_hi, pid_lo);
msg.header.type = WFC_IPC_MSG_SS_UNREGISTER;
msg.stream = stream;
msg.pid_lo = pid_lo;
msg.pid_hi = pid_hi;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
vcos_assert(status == VCOS_SUCCESS);
}
/* ------------------------------------------------------------------------- */
uint32_t wfc_server_stream_get_info(WFCNativeStreamType stream, WFC_STREAM_INFO_T *info)
{
uint32_t result;
VCOS_STATUS_T status;
WFC_IPC_MSG_SS_GET_INFO_T reply;
size_t info_len = sizeof(reply) - sizeof(WFC_IPC_MSG_HEADER_T);
if (!info)
{
vcos_log_error("%s: NULL info pointer passed", VCOS_FUNCTION);
return WFC_INVALID_HANDLE;
}
if (info->size < sizeof(uint32_t))
{
vcos_log_error("%s: invalid info pointer passed (size:%u)", VCOS_FUNCTION, info->size);
return WFC_INVALID_HANDLE;
}
vcos_log_trace("%s: stream 0x%x", VCOS_FUNCTION, stream);
memset(&reply, 0, sizeof(reply));
status = wfc_client_server_api_sendwait_stream(WFC_IPC_MSG_SS_GET_INFO, stream, &reply.result, &info_len);
if (status == VCOS_SUCCESS)
{
result = reply.result;
if (result == VCOS_SUCCESS)
{
uint32_t copy_size = vcos_min(info->size, reply.info.size);
memcpy(info, &reply.info, copy_size);
info->size = copy_size;
vcos_log_trace("%s: copied %u bytes", VCOS_FUNCTION, copy_size);
}
else
{
vcos_log_error("%s: result %d", VCOS_FUNCTION, result);
}
}
else
{
vcos_log_error("%s: send msg status %d", VCOS_FUNCTION, status);
result = status;
}
return result;
}
/* ------------------------------------------------------------------------- */
void wfc_server_stream_on_image_available(WFCNativeStreamType stream, WFC_CALLBACK_T image_available_cb, void *image_available_data)
{
WFC_IPC_MSG_SS_ON_IMAGE_AVAILABLE_T msg;
VCOS_STATUS_T status;
vcos_log_trace("%s: stream 0x%x cb %p data %p", VCOS_FUNCTION, stream, image_available_cb, image_available_data);
msg.header.type = WFC_IPC_MSG_SS_ON_IMAGE_AVAILABLE;
msg.stream = stream;
msg.image_available_cb.ptr = image_available_cb;
msg.image_available_data.ptr = image_available_data;
status = wfc_client_ipc_send(&msg.header, sizeof(msg));
if (!vcos_verify(status == VCOS_SUCCESS))
{
(*image_available_cb)(image_available_data);
}
}
| 8,275 |
404 | <gh_stars>100-1000
package io.github.memfis19.sample;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import io.github.memfis19.cadar.CalendarController;
import io.github.memfis19.cadar.data.entity.Event;
import io.github.memfis19.cadar.event.CalendarPrepareCallback;
import io.github.memfis19.cadar.event.DisplayEventCallback;
import io.github.memfis19.cadar.event.OnEventClickListener;
import io.github.memfis19.cadar.internal.process.EventsProcessor;
import io.github.memfis19.cadar.internal.process.EventsProcessorCallback;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.EventDecorator;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.MonthDecorator;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.WeekDecorator;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.factory.EventDecoratorFactory;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.factory.MonthDecoratorFactory;
import io.github.memfis19.cadar.internal.ui.list.adapter.decorator.factory.WeekDecoratorFactory;
import io.github.memfis19.cadar.internal.ui.list.adapter.model.ListItemModel;
import io.github.memfis19.cadar.settings.ListCalendarConfiguration;
import io.github.memfis19.cadar.view.ListCalendar;
import io.github.memfis19.sample.model.EventModel;
/**
* Created by memfis on 11/23/16.
*/
public class ListCalendarActivity extends AppCompatActivity implements CalendarPrepareCallback {
private ListCalendar listCalendar;
private List<Event> events = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_calendar_layout);
events.add(new EventModel());
listCalendar = (ListCalendar) findViewById(R.id.listCalendar);
ListCalendarConfiguration.Builder listBuilder = new ListCalendarConfiguration.Builder();
EventDecoratorFactory eventDecoratorFactory = new EventDecoratorFactory() {
@Override
public EventDecorator createEventDecorator(View parent) {
return new EventDecoratorImpl(parent);
}
};
WeekDecoratorFactory weekDecoratorFactory = new WeekDecoratorFactory() {
@Override
public WeekDecorator createWeekDecorator(View parent) {
return new WeeDecoratorImpl(parent);
}
};
MonthDecoratorFactory monthDecoratorFactory = new MonthDecoratorFactory() {
@Override
public MonthDecorator createMonthDecorator(View parent) {
return new MonthDecoratorImpl(parent);
}
};
listBuilder.setDisplayPeriod(Calendar.MONTH, 3);
listBuilder.setEventLayout(R.layout.custom_event_layout, eventDecoratorFactory);
listBuilder.setWeekLayout(R.layout.custom_week_title_layout, weekDecoratorFactory);
listBuilder.setMonthLayout(R.layout.custom_month_calendar_event_layout, monthDecoratorFactory);
// listBuilder.setEventsProcessor(new CustomEventProcessor());
listCalendar.setCalendarPrepareCallback(this);
listCalendar.prepareCalendar(listBuilder.build());
listCalendar.setOnEventClickListener(new OnEventClickListener() {
@Override
public void onEventClick(Event event, int position) {
Log.i("onEventClick", String.valueOf(event));
}
@Override
public void onSyncClick(Event event, int position) {
Log.i("onSyncClick", String.valueOf(event));
}
@Override
public void onEventLongClick(Event event, int position) {
Log.i("onEventLongClick", String.valueOf(event));
}
});
}
private class MonthDecoratorImpl implements MonthDecorator {
private ImageView monthBackground;
private TextView monthTitle;
private Custom custom;
public MonthDecoratorImpl(View parent) {
monthBackground = (ImageView) parent.findViewById(R.id.month_background);
monthTitle = (TextView) parent.findViewById(R.id.month_label);
}
@Override
public void onBindMonthView(View view, Calendar month) {
monthBackground.setImageDrawable(null);
final int backgroundId = getBackgroundId(month.get(Calendar.MONTH));
monthTitle.setText(month.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));
Picasso.with(monthTitle.getContext().getApplicationContext()).load(backgroundId).into(monthBackground, new Callback() {
@Override
public void onSuccess() {
if (Build.VERSION.SDK_INT > 13) {
monthBackground.setScrollX(0);
monthBackground.setScrollY(0);
}
}
@Override
public void onError() {
}
});
}
@NonNull
@Override
public RecyclerView.OnScrollListener getScrollListener() {
custom = new Custom();
return custom;
}
}
private class EventDecoratorImpl implements EventDecorator {
private TextView textView;
public EventDecoratorImpl(View parent) {
textView = (TextView) parent.findViewById(R.id.day_title);
}
@Override
public void onBindEventView(View view, Event event, ListItemModel previous, int position) {
view.setBackgroundColor(ContextCompat.getColor(ListCalendarActivity.this, R.color.eventBackground));
textView.setText(event.getEventTitle() + "\n" + event.getEventStartDate());
}
}
private class WeeDecoratorImpl implements WeekDecorator {
private TextView title;
public WeeDecoratorImpl(View parent) {
title = (TextView) parent.findViewById(io.github.memfis19.cadar.R.id.week_title);
}
@Override
public void onBindWeekView(View view, Pair<Calendar, Calendar> period) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(title.getContext().getString(io.github.memfis19.cadar.R.string.calendar_week));
stringBuilder.append("custom ");
stringBuilder.append(period.first.get(Calendar.WEEK_OF_YEAR));
stringBuilder.append(", ");
stringBuilder.append(DateFormat.format("dd MMM", period.first));
stringBuilder.append(" - ");
stringBuilder.append(DateFormat.format("dd MMM", period.second));
final Spannable date = new SpannableString(stringBuilder.toString());
title.setText(date);
}
}
private int getBackgroundId(int month) {
int backgroundId = io.github.memfis19.cadar.R.drawable.bkg_12_december;
if (month == Calendar.JANUARY) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_01_january;
} else if (month == Calendar.FEBRUARY) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_02_february;
} else if (month == Calendar.MARCH) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_03_march;
} else if (month == Calendar.APRIL) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_04_april;
} else if (month == Calendar.MAY) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_05_may;
} else if (month == Calendar.JUNE) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_06_june;
} else if (month == Calendar.JULY) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_07_july;
} else if (month == Calendar.AUGUST) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_08_august;
} else if (month == Calendar.SEPTEMBER) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_09_september;
} else if (month == Calendar.OCTOBER) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_10_october;
} else if (month == Calendar.NOVEMBER) {
backgroundId = io.github.memfis19.cadar.R.drawable.bkg_11_november;
}
return backgroundId;
}
private class Custom extends RecyclerView.OnScrollListener {
private View monthBackground;
Custom() {
}
public void setMonthBackground(View monthBackground) {
this.monthBackground = monthBackground;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (monthBackground != null) monthBackground.scrollBy(dx, (-1) * (dy / 10));
}
}
@Override
public void onCalendarReady(CalendarController calendar) {
listCalendar.displayEvents(events, new DisplayEventCallback<Pair<Calendar, Calendar>>() {
@Override
public void onEventsDisplayed(Pair<Calendar, Calendar> period) {
Log.d("", "");
listCalendar.refresh();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
listCalendar.releaseCalendar();
}
class CustomEventProcessor extends EventsProcessor<Pair<Calendar, Calendar>, List<Event>> {
public CustomEventProcessor() {
super(false, null, true);
}
@Override
protected void processEventsAsync(final Pair<Calendar, Calendar> target, final EventsProcessorCallback<Pair<Calendar, Calendar>, List<Event>> eventsProcessorCallback) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; ++i) {
events.add(new EventModel());
}
eventsProcessorCallback.onEventsProcessed(target, events);
}
}, 3000);
}
}
}
| 4,616 |
4,901 | /*
* 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.devtools.j2objc.ast;
import java.util.List;
import javax.lang.model.type.TypeMirror;
/**
* Type node for an intersection type in a cast expression (added in JLS8, section 4.9).
*/
public class IntersectionType extends Type {
private ChildList<Type> types = ChildList.create(Type.class, this);
public IntersectionType(TypeMirror typeMirror) {
super(typeMirror);
}
public IntersectionType(IntersectionType other) {
super(other);
types.copyFrom(other.types);
}
@Override
public Kind getKind() {
return Kind.INTERSECTION_TYPE;
}
public List<Type> types() {
return types;
}
public IntersectionType addType(Type type) {
types.add(type);
return this;
}
@Override
public boolean isIntersectionType() {
return true;
}
@Override
protected void acceptInner(TreeVisitor visitor) {
if (visitor.visit(this)) {
types.accept(visitor);
}
visitor.endVisit(this);
}
@Override
public IntersectionType copy() {
return new IntersectionType(this);
}
}
| 505 |
3,212 | /*
* 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.nifi.processors.pgp;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.pgp.service.api.PGPPublicKeyService;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.io.StreamCallback;
import org.apache.nifi.processors.pgp.exception.PGPProcessException;
import org.apache.nifi.processors.pgp.io.KeyIdentifierConverter;
import org.apache.nifi.stream.io.StreamUtils;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignature;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Verify Content using Open Pretty Good Privacy Public Keys
*/
@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
@Tags({"PGP", "GPG", "OpenPGP", "Encryption", "Signing", "RFC 4880"})
@CapabilityDescription("Verify signatures using OpenPGP Public Keys")
@SeeAlso({ DecryptContentPGP.class, EncryptContentPGP.class, SignContentPGP.class })
@WritesAttributes({
@WritesAttribute(attribute = PGPAttributeKey.LITERAL_DATA_FILENAME, description = "Filename from Literal Data"),
@WritesAttribute(attribute = PGPAttributeKey.LITERAL_DATA_MODIFIED, description = "Modified Date Time from Literal Data in milliseconds"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_CREATED, description = "Signature Creation Time in milliseconds"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_ALGORITHM, description = "Signature Algorithm including key and hash algorithm names"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_HASH_ALGORITHM_ID, description = "Signature Hash Algorithm Identifier"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_KEY_ALGORITHM_ID, description = "Signature Key Algorithm Identifier"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_KEY_ID, description = "Signature Public Key Identifier"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_TYPE_ID, description = "Signature Type Identifier"),
@WritesAttribute(attribute = PGPAttributeKey.SIGNATURE_VERSION, description = "Signature Version Number"),
})
public class VerifyContentPGP extends AbstractProcessor {
public static final Relationship SUCCESS = new Relationship.Builder()
.name("success")
.description("Signature Verification Succeeded")
.build();
public static final Relationship FAILURE = new Relationship.Builder()
.name("failure")
.description("Signature Verification Failed")
.build();
public static final PropertyDescriptor PUBLIC_KEY_SERVICE = new PropertyDescriptor.Builder()
.name("public-key-service")
.displayName("Public Key Service")
.description("PGP Public Key Service for verifying signatures with Public Key Encryption")
.identifiesControllerService(PGPPublicKeyService.class)
.required(true)
.build();
private static final Set<Relationship> RELATIONSHIPS = new HashSet<>(Arrays.asList(SUCCESS, FAILURE));
private static final List<PropertyDescriptor> DESCRIPTORS = Collections.singletonList(
PUBLIC_KEY_SERVICE
);
private static final int BUFFER_SIZE = 8192;
private static final String KEY_ID_UNKNOWN = "UNKNOWN";
/**
* Get Relationships
*
* @return Processor Relationships
*/
@Override
public Set<Relationship> getRelationships() {
return RELATIONSHIPS;
}
/**
* Get Supported Property Descriptors
*
* @return Processor Supported Property Descriptors
*/
@Override
public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return DESCRIPTORS;
}
/**
* On Trigger verifies signatures found in Flow File contents using configured properties
*
* @param context Process Context
* @param session Process Session
*/
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final PGPPublicKeyService publicKeyService = context.getProperty(PUBLIC_KEY_SERVICE).asControllerService(PGPPublicKeyService.class);
final VerifyStreamCallback callback = new VerifyStreamCallback(publicKeyService);
try {
flowFile = session.write(flowFile, callback);
flowFile = session.putAllAttributes(flowFile, callback.attributes);
final String keyId = flowFile.getAttribute(PGPAttributeKey.SIGNATURE_KEY_ID);
getLogger().info("Signature Key ID [{}] Verification Completed {}", keyId, flowFile);
session.transfer(flowFile, SUCCESS);
} catch (final RuntimeException e) {
flowFile = session.putAllAttributes(flowFile, callback.attributes);
getLogger().error("Processing Failed {}", flowFile, e);
session.transfer(flowFile, FAILURE);
}
}
private class VerifyStreamCallback implements StreamCallback {
private final PGPPublicKeyService publicKeyService;
private final Map<String, String> attributes = new HashMap<>();
private boolean verified;
private VerifyStreamCallback(final PGPPublicKeyService publicKeyService) {
this.publicKeyService = publicKeyService;
}
/**
* Process Input Stream containing binary or ASCII Armored OpenPGP messages and write literal data after verification
*
* @param inputStream Input Stream to be read
* @param outputStream Output Stream for literal data contents
* @throws IOException Thrown when unable to read or write streams
*/
@Override
public void process(final InputStream inputStream, final OutputStream outputStream) throws IOException {
final InputStream decoderInputStream = PGPUtil.getDecoderStream(inputStream);
final PGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory(decoderInputStream);
final Iterator<?> objects = pgpObjectFactory.iterator();
if (objects.hasNext()) {
processObjectFactory(objects, outputStream);
}
if (verified) {
getLogger().debug("One-Pass Signature Algorithm [{}] Verified", attributes.get(PGPAttributeKey.SIGNATURE_ALGORITHM));
} else {
final String keyId = attributes.getOrDefault(PGPAttributeKey.SIGNATURE_KEY_ID, KEY_ID_UNKNOWN);
throw new PGPProcessException(String.format("Signature Key ID [%s] Verification Failed", keyId));
}
}
private void processObjectFactory(final Iterator<?> objects, final OutputStream outputStream) throws IOException {
PGPOnePassSignature onePassSignature = null;
while (objects.hasNext()) {
final Object object = objects.next();
getLogger().debug("PGP Object Read [{}]", object.getClass().getSimpleName());
if (object instanceof PGPCompressedData) {
final PGPCompressedData compressedData = (PGPCompressedData) object;
try {
final PGPObjectFactory compressedObjectFactory = new JcaPGPObjectFactory(compressedData.getDataStream());
processObjectFactory(compressedObjectFactory.iterator(), outputStream);
} catch (final PGPException e) {
throw new PGPProcessException("Read Compressed Data Failed", e);
}
} else if (object instanceof PGPOnePassSignatureList) {
final PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) object;
onePassSignature = processOnePassSignatures(onePassSignatureList);
} else if (object instanceof PGPLiteralData) {
final PGPLiteralData literalData = (PGPLiteralData) object;
processLiteralData(literalData, outputStream, onePassSignature);
} else if (object instanceof PGPSignatureList) {
final PGPSignatureList signatureList = (PGPSignatureList) object;
processSignatures(signatureList, onePassSignature);
}
}
}
private PGPOnePassSignature processOnePassSignatures(final PGPOnePassSignatureList onePassSignatureList) {
getLogger().debug("One-Pass Signatures Found [{}]", onePassSignatureList.size());
PGPOnePassSignature initializedOnePassSignature = null;
final Iterator<PGPOnePassSignature> onePassSignatures = onePassSignatureList.iterator();
if (onePassSignatures.hasNext()) {
final PGPOnePassSignature onePassSignature = onePassSignatures.next();
setOnePassSignatureAttributes(onePassSignature);
final String keyId = KeyIdentifierConverter.format(onePassSignature.getKeyID());
final Optional<PGPPublicKey> optionalPublicKey = publicKeyService.findPublicKey(keyId);
if (optionalPublicKey.isPresent()) {
getLogger().debug("One-Pass Signature Key ID [{}] found", keyId);
final PGPPublicKey publicKey = optionalPublicKey.get();
try {
onePassSignature.init(new JcaPGPContentVerifierBuilderProvider(), publicKey);
initializedOnePassSignature = onePassSignature;
} catch (final PGPException e) {
throw new PGPProcessException(String.format("One-Pass Signature Key ID [%s] Initialization Failed", keyId), e);
}
} else {
getLogger().warn("One-Pass Signature Key ID [{}] not found in Public Key Service", keyId);
}
}
return initializedOnePassSignature;
}
private void processLiteralData(final PGPLiteralData literalData,
final OutputStream outputStream,
final PGPOnePassSignature onePassSignature) throws IOException {
setLiteralDataAttributes(literalData);
final InputStream literalInputStream = literalData.getInputStream();
if (onePassSignature == null) {
StreamUtils.copy(literalInputStream, outputStream);
} else {
processSignedStream(literalInputStream, outputStream, onePassSignature);
}
}
private void processSignatures(final PGPSignatureList signatureList, final PGPOnePassSignature onePassSignature) {
getLogger().debug("Signatures Found [{}]", signatureList.size());
final Iterator<PGPSignature> signatures = signatureList.iterator();
if (signatures.hasNext()) {
final PGPSignature signature = signatures.next();
setSignatureAttributes(signature);
if (onePassSignature == null) {
getLogger().debug("One-Pass Signature not found: Verification Failed");
} else {
try {
verified = onePassSignature.verify(signature);
} catch (final PGPException e) {
final String keyId = KeyIdentifierConverter.format(onePassSignature.getKeyID());
throw new PGPProcessException(String.format("One-Pass Signature Key ID [%s] Verification Failed", keyId), e);
}
}
}
}
private void processSignedStream(final InputStream inputStream, final OutputStream outputStream, final PGPOnePassSignature onePassSignature) throws IOException {
final String keyId = KeyIdentifierConverter.format(onePassSignature.getKeyID());
getLogger().debug("Processing Data for One-Pass Signature with Key ID [{}]", keyId);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = inputStream.read(buffer)) >= 0) {
onePassSignature.update(buffer, 0, read);
outputStream.write(buffer, 0, read);
}
}
private void setOnePassSignatureAttributes(final PGPOnePassSignature onePassSignature) {
setSignatureAlgorithm(onePassSignature.getKeyAlgorithm(), onePassSignature.getHashAlgorithm());
attributes.put(PGPAttributeKey.SIGNATURE_KEY_ID, KeyIdentifierConverter.format(onePassSignature.getKeyID()));
attributes.put(PGPAttributeKey.SIGNATURE_TYPE_ID, Integer.toString(onePassSignature.getSignatureType()));
}
private void setSignatureAttributes(final PGPSignature signature) {
setSignatureAlgorithm(signature.getKeyAlgorithm(), signature.getHashAlgorithm());
attributes.put(PGPAttributeKey.SIGNATURE_CREATED, Long.toString(signature.getCreationTime().getTime()));
attributes.put(PGPAttributeKey.SIGNATURE_KEY_ID, KeyIdentifierConverter.format(signature.getKeyID()));
attributes.put(PGPAttributeKey.SIGNATURE_TYPE_ID, Integer.toString(signature.getSignatureType()));
attributes.put(PGPAttributeKey.SIGNATURE_VERSION, Integer.toString(signature.getVersion()));
}
private void setLiteralDataAttributes(final PGPLiteralData literalData) {
attributes.put(PGPAttributeKey.LITERAL_DATA_FILENAME, literalData.getFileName());
attributes.put(PGPAttributeKey.LITERAL_DATA_MODIFIED, Long.toString(literalData.getModificationTime().getTime()));
}
private void setSignatureAlgorithm(final int keyAlgorithm, final int hashAlgorithm) {
attributes.put(PGPAttributeKey.SIGNATURE_HASH_ALGORITHM_ID, Integer.toString(hashAlgorithm));
attributes.put(PGPAttributeKey.SIGNATURE_KEY_ALGORITHM_ID, Integer.toString(keyAlgorithm));
try {
final String algorithm = PGPUtil.getSignatureName(keyAlgorithm, hashAlgorithm);
attributes.put(PGPAttributeKey.SIGNATURE_ALGORITHM, algorithm);
} catch (final PGPException e) {
getLogger().debug("Signature Algorithm Key Identifier [{}] Hash Identifier [{}] not found", keyAlgorithm, hashAlgorithm);
}
}
}
}
| 6,426 |
5,023 | # Copyright 2020 Google LLC
#
# 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.
"""libClusterfuzz package."""
import os
if not os.getenv('ROOT_DIR') and not os.getenv('GAE_ENV'):
# If ROOT_DIR isn't set by the time we import this and we're not on GAE,
# assume we're libClusterFuzz.
# Actual value does not matter, it just needs to be set.
os.environ['ROOT_DIR'] = '/tmp'
os.environ['LIB_CF'] = 'True'
this_dir = os.path.dirname(os.path.abspath(__file__))
os.environ['CONFIG_DIR_OVERRIDE'] = os.path.join(this_dir, 'lib-config')
# Other necessary env vars.
os.environ['FAIL_RETRIES'] = '1'
os.environ['FAIL_WAIT'] = '10'
| 376 |
4,348 | /***
Copyright (c) 2012 CommonsWare, LLC
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.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.wakesvc;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.JobIntentService;
import android.util.Log;
public class ScheduledService extends JobIntentService {
private static final int UNIQUE_JOB_ID=1337;
static void enqueueWork(Context ctxt) {
enqueueWork(ctxt, ScheduledService.class, UNIQUE_JOB_ID,
new Intent(ctxt, ScheduledService.class));
}
@Override
public void onHandleWork(Intent i) {
Log.d(getClass().getSimpleName(), "I ran!");
}
}
| 372 |
1,027 | <gh_stars>1000+
/**
* Function.h
*
* Small extension to the Value class that allows a value to be
* constructed with a std::function.
*
* If you want to assign a std::function to a value, the following
* piece of code won't work:
*
* Php::Value value([]() { .... });
*
* Because the passed in function would match with many of the possible
* Value constructors. For that reason we have created a small and
* simple Function class that can be used instead:
*
* Php::Function valu([]() { .... });
*
* A Php::Function is an extended Php::Value object, so can be used
* in place of Php::Values all the time. The only difference is that
* it has a different constructor
*
* @author <NAME> <<EMAIL>>
* @copyright 2015 Copernica BV
*/
/**
* Set up namespace
*/
namespace Php {
/**
* Class definition
*/
class PHPCPP_EXPORT Function : public Value
{
public:
/**
* Constructor to wrap a function that takes parameters
* @param function The C++ function to be wrapped
*/
Function(const std::function<Value(Parameters&)> &function);
/**
* Constructor to wrap a function that does not accept parameters
*
* Old C++ compilers do not see a difference between std::function
* objects based on the function signature, so these old compilers
* do not see this method.
*
* @param function The C++ function to be wrapped
*/
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 7) || __clang__
Function(const std::function<Value()> &function) : Function([function](Parameters ¶ms) -> Value {
// call original function, forget about the parameters
return function();
}) {}
#endif
/**
* Destructor
*/
virtual ~Function() {}
private:
/**
* Retrieve the class entry of the _functor class
* @return _zend_class_entry
*/
static struct _zend_class_entry *entry();
};
/**
* End namespace
*/
}
| 681 |
14,668 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/proxy_resolver/host_resolver_mojo.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/test/task_environment.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/ip_address.h"
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
#include "net/log/net_log_with_source.h"
#include "net/test/event_waiter.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
using net::test::IsError;
using net::test::IsOk;
namespace proxy_resolver {
namespace {
void Fail(int result) {
FAIL() << "Unexpected callback called with error " << result;
}
class MockMojoHostResolverRequest {
public:
MockMojoHostResolverRequest(
mojo::PendingRemote<mojom::HostResolverRequestClient> client,
base::OnceClosure error_callback)
: client_(std::move(client)), error_callback_(std::move(error_callback)) {
client_.set_disconnect_handler(base::BindOnce(
&MockMojoHostResolverRequest::OnDisconnect, base::Unretained(this)));
}
void OnDisconnect() { std::move(error_callback_).Run(); }
private:
mojo::Remote<mojom::HostResolverRequestClient> client_;
base::OnceClosure error_callback_;
};
struct HostResolverAction {
enum Action {
COMPLETE,
DROP,
RETAIN,
};
static HostResolverAction ReturnError(net::Error error) {
HostResolverAction result;
result.error = error;
return result;
}
static HostResolverAction ReturnResult(
std::vector<net::IPAddress> addresses) {
HostResolverAction result;
result.addresses = std::move(addresses);
return result;
}
static HostResolverAction DropRequest() {
HostResolverAction result;
result.action = DROP;
return result;
}
static HostResolverAction RetainRequest() {
HostResolverAction result;
result.action = RETAIN;
return result;
}
Action action = COMPLETE;
std::vector<net::IPAddress> addresses;
net::Error error = net::OK;
};
class MockMojoHostResolver : public HostResolverMojo::Impl {
public:
// Information logged from a call to ResolveDns().
struct RequestInfo {
std::string hostname;
net::NetworkIsolationKey network_isolation_key;
bool operator==(const RequestInfo& other) const {
return hostname == other.hostname &&
network_isolation_key == other.network_isolation_key;
}
};
explicit MockMojoHostResolver(
base::RepeatingClosure request_connection_error_callback)
: request_connection_error_callback_(
std::move(request_connection_error_callback)) {}
~MockMojoHostResolver() override {
EXPECT_EQ(results_returned_, actions_.size());
}
void AddAction(HostResolverAction action) {
actions_.push_back(std::move(action));
}
const std::vector<RequestInfo>& request_info() const { return request_info_; }
void ResolveDns(
const std::string& hostname,
net::ProxyResolveDnsOperation operation,
const net::NetworkIsolationKey& network_isolation_key,
mojo::PendingRemote<mojom::HostResolverRequestClient> client) override {
request_info_.push_back(RequestInfo{hostname, network_isolation_key});
ASSERT_LE(results_returned_, actions_.size());
switch (actions_[results_returned_].action) {
case HostResolverAction::COMPLETE:
mojo::Remote<mojom::HostResolverRequestClient>(std::move(client))
->ReportResult(actions_[results_returned_].error,
actions_[results_returned_].addresses);
break;
case HostResolverAction::RETAIN:
requests_.push_back(std::make_unique<MockMojoHostResolverRequest>(
std::move(client),
base::BindOnce(request_connection_error_callback_)));
break;
case HostResolverAction::DROP:
break;
}
results_returned_++;
}
private:
std::vector<HostResolverAction> actions_;
size_t results_returned_ = 0;
std::vector<RequestInfo> request_info_;
base::RepeatingClosure request_connection_error_callback_;
std::vector<std::unique_ptr<MockMojoHostResolverRequest>> requests_;
};
} // namespace
class HostResolverMojoTest : public testing::Test {
protected:
enum class ConnectionErrorSource {
REQUEST,
};
using Waiter = net::EventWaiter<ConnectionErrorSource>;
HostResolverMojoTest()
: mock_resolver_(base::BindRepeating(&Waiter::NotifyEvent,
base::Unretained(&waiter_),
ConnectionErrorSource::REQUEST)),
resolver_(&mock_resolver_) {}
int Resolve(const std::string& hostname,
const net::NetworkIsolationKey& network_isolation_key,
std::vector<net::IPAddress>* out_addresses) {
std::unique_ptr<ProxyHostResolver::Request> request =
resolver_.CreateRequest(hostname,
net::ProxyResolveDnsOperation::DNS_RESOLVE_EX,
network_isolation_key);
net::TestCompletionCallback callback;
int result = callback.GetResult(request->Start(callback.callback()));
*out_addresses = request->GetResults();
return result;
}
base::test::TaskEnvironment task_environment_;
Waiter waiter_;
MockMojoHostResolver mock_resolver_;
HostResolverMojo resolver_;
};
TEST_F(HostResolverMojoTest, Basic) {
const url::Origin kOrigin =
url::Origin::Create(GURL("https://not-example.com/"));
const net::NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
std::vector<net::IPAddress> addresses;
net::IPAddress address(1, 2, 3, 4);
addresses.push_back(address);
addresses.push_back(ConvertIPv4ToIPv4MappedIPv6(address));
mock_resolver_.AddAction(HostResolverAction::ReturnResult(addresses));
std::vector<net::IPAddress> result;
EXPECT_THAT(Resolve("example.com", kNetworkIsolationKey, &result), IsOk());
EXPECT_EQ(addresses, result);
ASSERT_EQ(1u, mock_resolver_.request_info().size());
EXPECT_EQ("example.com", mock_resolver_.request_info()[0].hostname);
EXPECT_EQ(kNetworkIsolationKey,
mock_resolver_.request_info()[0].network_isolation_key);
}
TEST_F(HostResolverMojoTest, ResolveCachedResult) {
std::vector<net::IPAddress> addresses;
net::IPAddress address(1, 2, 3, 4);
addresses.push_back(address);
addresses.push_back(ConvertIPv4ToIPv4MappedIPv6(address));
mock_resolver_.AddAction(HostResolverAction::ReturnResult(addresses));
// Load results into cache.
std::vector<net::IPAddress> result;
ASSERT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsOk());
ASSERT_EQ(1u, mock_resolver_.request_info().size());
// Expect results from cache.
result.clear();
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsOk());
EXPECT_EQ(addresses, result);
EXPECT_EQ(1u, mock_resolver_.request_info().size());
}
// Make sure the cache indexes entries by NetworkIsolationKey.
TEST_F(HostResolverMojoTest, ResolveCachedResultWithNetworkIsolationKey) {
const url::Origin kOrigin =
url::Origin::Create(GURL("https://not-example.com/"));
const net::NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
std::vector<net::IPAddress> addresses1;
net::IPAddress address1(1, 2, 3, 4);
addresses1.push_back(address1);
addresses1.push_back(ConvertIPv4ToIPv4MappedIPv6(address1));
mock_resolver_.AddAction(HostResolverAction::ReturnResult(addresses1));
// Load results into cache using kNetworkIsolationKey.
std::vector<net::IPAddress> result;
ASSERT_THAT(Resolve("example.com", kNetworkIsolationKey, &result), IsOk());
ASSERT_EQ(1u, mock_resolver_.request_info().size());
// Expect results from cache when using kNetworkIsolationKey.
result.clear();
EXPECT_THAT(Resolve("example.com", kNetworkIsolationKey, &result), IsOk());
EXPECT_EQ(addresses1, result);
EXPECT_EQ(1u, mock_resolver_.request_info().size());
// A request with an empty NetworkIsolationKey should not use results cached
// using kNetworkIsolationKey.
std::vector<net::IPAddress> addresses2;
net::IPAddress address2(2, 3, 5, 8);
addresses2.push_back(address2);
addresses2.push_back(ConvertIPv4ToIPv4MappedIPv6(address2));
mock_resolver_.AddAction(HostResolverAction::ReturnResult(addresses2));
result.clear();
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsOk());
EXPECT_EQ(addresses2, result);
EXPECT_EQ(2u, mock_resolver_.request_info().size());
// Using the empty NetworkIsolationKey again should result in the second
// cached address list.
result.clear();
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsOk());
EXPECT_EQ(addresses2, result);
EXPECT_EQ(2u, mock_resolver_.request_info().size());
// Using kNetworkIsolationKey again should result in the first cached address
// list.
result.clear();
EXPECT_THAT(Resolve("example.com", kNetworkIsolationKey, &result), IsOk());
EXPECT_EQ(addresses1, result);
EXPECT_EQ(2u, mock_resolver_.request_info().size());
}
TEST_F(HostResolverMojoTest, Multiple) {
std::vector<net::IPAddress> addresses;
addresses.emplace_back(1, 2, 3, 4);
mock_resolver_.AddAction(HostResolverAction::ReturnResult(addresses));
mock_resolver_.AddAction(
HostResolverAction::ReturnError(net::ERR_NAME_NOT_RESOLVED));
std::unique_ptr<ProxyHostResolver::Request> request1 =
resolver_.CreateRequest("example.com",
net::ProxyResolveDnsOperation::DNS_RESOLVE_EX,
net::NetworkIsolationKey());
std::unique_ptr<ProxyHostResolver::Request> request2 =
resolver_.CreateRequest("example.org",
net::ProxyResolveDnsOperation::DNS_RESOLVE_EX,
net::NetworkIsolationKey());
net::TestCompletionCallback callback1;
net::TestCompletionCallback callback2;
ASSERT_EQ(net::ERR_IO_PENDING, request1->Start(callback1.callback()));
ASSERT_EQ(net::ERR_IO_PENDING, request2->Start(callback2.callback()));
EXPECT_THAT(callback1.GetResult(net::ERR_IO_PENDING), IsOk());
EXPECT_THAT(callback2.GetResult(net::ERR_IO_PENDING),
IsError(net::ERR_NAME_NOT_RESOLVED));
EXPECT_EQ(addresses, request1->GetResults());
ASSERT_EQ(0u, request2->GetResults().size());
EXPECT_THAT(mock_resolver_.request_info(),
testing::ElementsAre(
MockMojoHostResolver::RequestInfo{"example.com",
net::NetworkIsolationKey()},
MockMojoHostResolver::RequestInfo{
"example.org", net::NetworkIsolationKey()}));
}
TEST_F(HostResolverMojoTest, Error) {
mock_resolver_.AddAction(
HostResolverAction::ReturnError(net::ERR_NAME_NOT_RESOLVED));
std::vector<net::IPAddress> result;
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsError(net::ERR_NAME_NOT_RESOLVED));
EXPECT_TRUE(result.empty());
ASSERT_EQ(1u, mock_resolver_.request_info().size());
EXPECT_EQ("example.com", mock_resolver_.request_info()[0].hostname);
}
TEST_F(HostResolverMojoTest, EmptyResult) {
mock_resolver_.AddAction(HostResolverAction::ReturnError(net::OK));
std::vector<net::IPAddress> result;
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsOk());
EXPECT_TRUE(result.empty());
ASSERT_EQ(1u, mock_resolver_.request_info().size());
}
TEST_F(HostResolverMojoTest, Cancel) {
mock_resolver_.AddAction(HostResolverAction::RetainRequest());
std::unique_ptr<ProxyHostResolver::Request> request = resolver_.CreateRequest(
"example.com", net::ProxyResolveDnsOperation::DNS_RESOLVE_EX,
net::NetworkIsolationKey());
request->Start(base::BindOnce(&Fail));
request.reset();
waiter_.WaitForEvent(ConnectionErrorSource::REQUEST);
ASSERT_EQ(1u, mock_resolver_.request_info().size());
EXPECT_EQ("example.com", mock_resolver_.request_info()[0].hostname);
}
TEST_F(HostResolverMojoTest, ImplDropsClientConnection) {
mock_resolver_.AddAction(HostResolverAction::DropRequest());
std::vector<net::IPAddress> result;
EXPECT_THAT(Resolve("example.com", net::NetworkIsolationKey(), &result),
IsError(net::ERR_FAILED));
EXPECT_TRUE(result.empty());
ASSERT_EQ(1u, mock_resolver_.request_info().size());
EXPECT_EQ("example.com", mock_resolver_.request_info()[0].hostname);
}
} // namespace proxy_resolver
| 4,917 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include <osl/diagnose.h>
#include <rtl/ustrbuf.hxx>
#include "registry/reader.hxx"
#include "registry/version.h"
#include "base.hxx"
namespace stoc_rdbtdp
{
//__________________________________________________________________________________________________
// virtual
ConstantsTypeDescriptionImpl::~ConstantsTypeDescriptionImpl()
{
delete _pMembers;
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
// XTypeDescription
//__________________________________________________________________________________________________
// virtual
TypeClass ConstantsTypeDescriptionImpl::getTypeClass()
throw( RuntimeException )
{
return TypeClass_CONSTANTS;
}
//__________________________________________________________________________________________________
// virtual
OUString ConstantsTypeDescriptionImpl::getName()
throw( RuntimeException )
{
return _aName;
}
// XConstantsTypeDescription
//__________________________________________________________________________________________________
// virtual
Sequence< Reference< XConstantTypeDescription > > SAL_CALL
ConstantsTypeDescriptionImpl::getConstants()
throw ( RuntimeException )
{
if ( !_pMembers )
{
typereg::Reader aReader(
_aBytes.getConstArray(), _aBytes.getLength(), false,
TYPEREG_VERSION_1);
sal_uInt16 nFields = aReader.getFieldCount();
Sequence< Reference< XConstantTypeDescription > > * pTempConsts
= new Sequence< Reference< XConstantTypeDescription > >( nFields );
Reference< XConstantTypeDescription > * pConsts
= pTempConsts->getArray();
while ( nFields-- )
{
rtl::OUStringBuffer aName( _aName );
aName.appendAscii( "." );
aName.append( aReader.getFieldName( nFields ) );
Any aValue( getRTValue( aReader.getFieldValue( nFields ) ) );
pConsts[ nFields ]
= new ConstantTypeDescriptionImpl( aName.makeStringAndClear(),
aValue );
}
ClearableMutexGuard aGuard( getMutex() );
if ( _pMembers )
{
aGuard.clear();
delete pTempConsts;
}
else
{
_pMembers = pTempConsts;
}
}
return *_pMembers;
}
}
| 1,134 |
65,488 | <filename>test/parser/samples/error-unmatched-closing-tag-autoclose/error.json<gh_stars>1000+
{
"code": "invalid-closing-tag",
"message": "</p> attempted to close <p> that was already automatically closed by <pre>",
"pos": 24,
"start": {
"character": 24,
"column": 0,
"line": 3
}
}
| 117 |
14,668 | // 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/crash/core/app/crash_export_thunks.h"
#include <algorithm>
#include <type_traits>
#include "base/process/process.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/crash/core/app/crashpad.h"
#include "components/crash/core/app/dump_hung_process_with_ptype.h"
#include "third_party/crashpad/crashpad/client/crashpad_client.h"
void RequestSingleCrashUpload_ExportThunk(const char* local_id) {
crash_reporter::RequestSingleCrashUploadImpl(local_id);
}
size_t GetCrashReports_ExportThunk(crash_reporter::Report* reports,
size_t reports_size) {
static_assert(std::is_pod<crash_reporter::Report>::value,
"crash_reporter::Report must be POD");
// Since this could be called across module boundaries, retrieve the full
// list of reports into this vector, and then manually copy however much fits
// into the caller's copy.
std::vector<crash_reporter::Report> crash_reports;
// The crash_reporter::GetReports function thunks here, here is delegation to
// the actual implementation.
crash_reporter::GetReportsImpl(&crash_reports);
size_t to_copy = std::min(reports_size, crash_reports.size());
for (size_t i = 0; i < to_copy; ++i)
reports[i] = crash_reports[i];
return crash_reports.size();
}
int CrashForException_ExportThunk(EXCEPTION_POINTERS* info) {
crash_reporter::GetCrashpadClient().DumpAndCrash(info);
return EXCEPTION_CONTINUE_SEARCH;
}
// This function is used in chrome_metrics_services_manager_client.cc to trigger
// changes to the upload-enabled state. This is done when the metrics services
// are initialized, and when the user changes their consent for uploads. See
// crash_reporter::SetUploadConsent for effects. The given consent value should
// be consistent with
// crash_reporter::GetCrashReporterClient()->GetCollectStatsConsent(), but it's
// not enforced to avoid blocking startup code on synchronizing them.
void SetUploadConsent_ExportThunk(bool consent) {
crash_reporter::SetUploadConsent(consent);
}
HANDLE InjectDumpForHungInput_ExportThunk(HANDLE process) {
return CreateRemoteThread(
process, nullptr, 0,
crash_reporter::internal::DumpProcessForHungInputThread, nullptr, 0,
nullptr);
}
const wchar_t* GetCrashpadDatabasePath_ExportThunk() {
return crash_reporter::GetCrashpadDatabasePathImpl();
}
void ClearReportsBetween_ExportThunk(time_t begin, time_t end) {
crash_reporter::ClearReportsBetweenImpl(begin, end);
}
bool DumpHungProcessWithPtype_ExportThunk(HANDLE process_handle,
const char* ptype) {
base::Process process(process_handle);
return crash_reporter::DumpHungProcessWithPtypeImpl(process, ptype);
}
| 1,008 |
4,959 | <filename>pyro/contrib/gp/models/gpr.py
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
import torch.distributions as torchdist
from torch.distributions import constraints
import pyro
import pyro.distributions as dist
from pyro.contrib.gp.models.model import GPModel
from pyro.contrib.gp.util import conditional
from pyro.nn.module import PyroParam, pyro_method
from pyro.util import warn_if_nan
class GPRegression(GPModel):
r"""
Gaussian Process Regression model.
The core of a Gaussian Process is a covariance function :math:`k` which governs
the similarity between input points. Given :math:`k`, we can establish a
distribution over functions :math:`f` by a multivarite normal distribution
.. math:: p(f(X)) = \mathcal{N}(0, k(X, X)),
where :math:`X` is any set of input points and :math:`k(X, X)` is a covariance
matrix whose entries are outputs :math:`k(x, z)` of :math:`k` over input pairs
:math:`(x, z)`. This distribution is usually denoted by
.. math:: f \sim \mathcal{GP}(0, k).
.. note:: Generally, beside a covariance matrix :math:`k`, a Gaussian Process can
also be specified by a mean function :math:`m` (which is a zero-value function
by default). In that case, its distribution will be
.. math:: p(f(X)) = \mathcal{N}(m(X), k(X, X)).
Given inputs :math:`X` and their noisy observations :math:`y`, the Gaussian Process
Regression model takes the form
.. math::
f &\sim \mathcal{GP}(0, k(X, X)),\\
y & \sim f + \epsilon,
where :math:`\epsilon` is Gaussian noise.
.. note:: This model has :math:`\mathcal{O}(N^3)` complexity for training,
:math:`\mathcal{O}(N^3)` complexity for testing. Here, :math:`N` is the number
of train inputs.
Reference:
[1] `Gaussian Processes for Machine Learning`,
<NAME>, <NAME>
:param torch.Tensor X: A input data for training. Its first dimension is the number
of data points.
:param torch.Tensor y: An output data for training. Its last dimension is the
number of data points.
:param ~pyro.contrib.gp.kernels.kernel.Kernel kernel: A Pyro kernel object, which
is the covariance function :math:`k`.
:param torch.Tensor noise: Variance of Gaussian noise of this model.
:param callable mean_function: An optional mean function :math:`m` of this Gaussian
process. By default, we use zero mean.
:param float jitter: A small positive term which is added into the diagonal part of
a covariance matrix to help stablize its Cholesky decomposition.
"""
def __init__(self, X, y, kernel, noise=None, mean_function=None, jitter=1e-6):
assert isinstance(
X, torch.Tensor
), "X needs to be a torch Tensor instead of a {}".format(type(X))
if y is not None:
assert isinstance(
y, torch.Tensor
), "y needs to be a torch Tensor instead of a {}".format(type(y))
super().__init__(X, y, kernel, mean_function, jitter)
noise = self.X.new_tensor(1.0) if noise is None else noise
self.noise = PyroParam(noise, constraints.positive)
@pyro_method
def model(self):
self.set_mode("model")
N = self.X.size(0)
Kff = self.kernel(self.X)
Kff.view(-1)[:: N + 1] += self.jitter + self.noise # add noise to diagonal
Lff = torch.linalg.cholesky(Kff)
zero_loc = self.X.new_zeros(self.X.size(0))
f_loc = zero_loc + self.mean_function(self.X)
if self.y is None:
f_var = Lff.pow(2).sum(dim=-1)
return f_loc, f_var
else:
return pyro.sample(
self._pyro_get_fullname("y"),
dist.MultivariateNormal(f_loc, scale_tril=Lff)
.expand_by(self.y.shape[:-1])
.to_event(self.y.dim() - 1),
obs=self.y,
)
@pyro_method
def guide(self):
self.set_mode("guide")
self._load_pyro_samples()
def forward(self, Xnew, full_cov=False, noiseless=True):
r"""
Computes the mean and covariance matrix (or variance) of Gaussian Process
posterior on a test input data :math:`X_{new}`:
.. math:: p(f^* \mid X_{new}, X, y, k, \epsilon) = \mathcal{N}(loc, cov).
.. note:: The noise parameter ``noise`` (:math:`\epsilon`) together with
kernel's parameters have been learned from a training procedure (MCMC or
SVI).
:param torch.Tensor Xnew: A input data for testing. Note that
``Xnew.shape[1:]`` must be the same as ``self.X.shape[1:]``.
:param bool full_cov: A flag to decide if we want to predict full covariance
matrix or just variance.
:param bool noiseless: A flag to decide if we want to include noise in the
prediction output or not.
:returns: loc and covariance matrix (or variance) of :math:`p(f^*(X_{new}))`
:rtype: tuple(torch.Tensor, torch.Tensor)
"""
self._check_Xnew_shape(Xnew)
self.set_mode("guide")
N = self.X.size(0)
Kff = self.kernel(self.X).contiguous()
Kff.view(-1)[:: N + 1] += self.jitter + self.noise # add noise to the diagonal
Lff = torch.linalg.cholesky(Kff)
y_residual = self.y - self.mean_function(self.X)
loc, cov = conditional(
Xnew,
self.X,
self.kernel,
y_residual,
None,
Lff,
full_cov,
jitter=self.jitter,
)
if full_cov and not noiseless:
M = Xnew.size(0)
cov = cov.contiguous()
cov.view(-1, M * M)[:, :: M + 1] += self.noise # add noise to the diagonal
if not full_cov and not noiseless:
cov = cov + self.noise
return loc + self.mean_function(Xnew), cov
def iter_sample(self, noiseless=True):
r"""
Iteratively constructs a sample from the Gaussian Process posterior.
Recall that at test input points :math:`X_{new}`, the posterior is
multivariate Gaussian distributed with mean and covariance matrix
given by :func:`forward`.
This method samples lazily from this multivariate Gaussian. The advantage
of this approach is that later query points can depend upon earlier ones.
Particularly useful when the querying is to be done by an optimisation
routine.
.. note:: The noise parameter ``noise`` (:math:`\epsilon`) together with
kernel's parameters have been learned from a training procedure (MCMC or
SVI).
:param bool noiseless: A flag to decide if we want to add sampling noise
to the samples beyond the noise inherent in the GP posterior.
:returns: sampler
:rtype: function
"""
noise = self.noise.detach()
X = self.X.clone().detach()
y = self.y.clone().detach()
N = X.size(0)
Kff = self.kernel(X).contiguous()
Kff.view(-1)[:: N + 1] += noise # add noise to the diagonal
outside_vars = {"X": X, "y": y, "N": N, "Kff": Kff}
def sample_next(xnew, outside_vars):
"""Repeatedly samples from the Gaussian process posterior,
conditioning on previously sampled values.
"""
warn_if_nan(xnew)
# Variables from outer scope
X, y, Kff = outside_vars["X"], outside_vars["y"], outside_vars["Kff"]
# Compute Cholesky decomposition of kernel matrix
Lff = torch.linalg.cholesky(Kff)
y_residual = y - self.mean_function(X)
# Compute conditional mean and variance
loc, cov = conditional(
xnew, X, self.kernel, y_residual, None, Lff, False, jitter=self.jitter
)
if not noiseless:
cov = cov + noise
ynew = torchdist.Normal(
loc + self.mean_function(xnew), cov.sqrt()
).rsample()
# Update kernel matrix
N = outside_vars["N"]
Kffnew = Kff.new_empty(N + 1, N + 1)
Kffnew[:N, :N] = Kff
cross = self.kernel(X, xnew).squeeze()
end = self.kernel(xnew, xnew).squeeze()
Kffnew[N, :N] = cross
Kffnew[:N, N] = cross
# No noise, just jitter for numerical stability
Kffnew[N, N] = end + self.jitter
# Heuristic to avoid adding degenerate points
if Kffnew.logdet() > -15.0:
outside_vars["Kff"] = Kffnew
outside_vars["N"] += 1
outside_vars["X"] = torch.cat((X, xnew))
outside_vars["y"] = torch.cat((y, ynew))
return ynew
return lambda xnew: sample_next(xnew, outside_vars)
| 3,971 |
665 | /* compact_vector.h -*- C++ -*-
<NAME>, 3 March 2009
Copyright (c) 2009 <NAME>. All rights reserved.
This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
An optimized class for holding a variable length unbounded vector. If the
vector is below a certain threshold, then the data will all be stored
internally. Otherwise, the data is stored externally and a pointer is
kept.
Conforms to the interface of std::vector and has iterator validity
guarantees that are at least as strong.
*/
#pragma once
#include <limits>
#include <vector>
#include "mldb/arch/exception.h"
#include "mldb/compiler/compiler.h"
#include "mldb/utils/move.h"
#include <ostream>
#include <iterator>
#include <algorithm>
#include <utility>
#include <initializer_list>
#include <stdint.h>
#include <cstring>
// GCC 9 gives warnings on unaligned addresses of packed member even
// when they are actually aligned.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
namespace MLDB {
template<typename Data,
size_t Internal_ = 0,
typename Size = uint32_t,
bool Safe = true,
typename Pointer = Data *,
class Allocator = std::allocator<Data> >
class compact_vector {
public:
typedef Data * iterator;
typedef const Data * const_iterator;
typedef Pointer pointer;
typedef Size size_type;
typedef Data value_type;
typedef Data & reference;
typedef const Data & const_reference;
static constexpr size_t Internal = Internal_;
static constexpr bool IS_NOTHROW_DESTRUCTIBLE = std::is_nothrow_destructible<Data>::value;
static constexpr bool IS_NOTHROW_MOVE_CONSTRUCTIBLE = std::is_nothrow_move_constructible<Data>::value;
constexpr compact_vector()
: ext{0}, size_(0), is_internal_(true)
{
#if 0
using namespace std;
cerr << __PRETTY_FUNCTION__ << endl;
cerr << "sizeof(this) = " << sizeof(*this) << endl;
cerr << "sizeof(Pointer) = " << sizeof(Pointer) << endl;
cerr << "sizeof(Data) = " << sizeof(Data) << endl;
#endif
}
template<class ForwardIterator>
compact_vector(ForwardIterator first,
ForwardIterator last)
: compact_vector()
{
init_copy(first, last, std::distance(first, last));
}
compact_vector(std::initializer_list<Data> list)
: compact_vector()
{
init_copy(list.begin(), list.end(), list.size());
}
compact_vector(size_t initialSize, const Data & element = Data())
: compact_vector()
{
init(initialSize);
Data * p = data();
try {
while (size_ < initialSize) {
new (p + size_) Data(element);
++size_;
}
} catch (...) {
clear();
throw;
}
}
~compact_vector()
noexcept(IS_NOTHROW_DESTRUCTIBLE)
{
clear();
}
compact_vector(const compact_vector & other)
: compact_vector()
{
init_copy(other.begin(), other.end(), other.size());
}
compact_vector(compact_vector && other)
noexcept(IS_NOTHROW_MOVE_CONSTRUCTIBLE && IS_NOTHROW_DESTRUCTIBLE)
: size_(other.size_), is_internal_(other.is_internal_)
{
if (other.is_internal_) {
uninitialized_move_and_destroy(other.internal(),
other.internal() + other.size_,
internal());
}
else {
ext.pointer_ = other.ext.pointer_;
ext.capacity_ = other.ext.capacity_;
other.ext.pointer_ = 0;
other.ext.capacity_ = 0;
}
other.size_ = 0;
other.is_internal_ = true;
}
compact_vector & operator = (const compact_vector & other)
{
compact_vector new_me(other);
swap(new_me);
return *this;
}
compact_vector & operator = (compact_vector && other)
{
compact_vector new_me(other);
swap(new_me);
return *this;
}
void swap(compact_vector & other)
noexcept(IS_NOTHROW_MOVE_CONSTRUCTIBLE
&& IS_NOTHROW_DESTRUCTIBLE)
{
// Both external: easy case (swapping only)
if (!(is_internal() || other.is_internal())) {
swap_size(other);
Size t = ext.capacity_;
ext.capacity_ = other.ext.capacity_;
other.ext.capacity_ = t;
Pointer t2 = ext.pointer_;
ext.pointer_ = other.ext.pointer_;
other.ext.pointer_ = t2;
return;
}
// Both internal: swap internal elements
if (is_internal() && other.is_internal()) {
using std::swap;
// Swap common internal elements
for (size_type i = 0; i < size() && i < other.size(); ++i)
swap(internal()[i], other.internal()[i]);
// Copy leftovers
for (size_type i = size(); i < other.size(); ++i) {
new (internal() + i) Data(std::move(other.internal()[i]));
other.internal()[i].~Data();
}
for (size_type i = other.size(); i < size(); ++i) {
new (other.internal() + i) Data(std::move(internal()[i]));
internal()[i].~Data();
}
swap_size(other);
return;
}
// Do it the other way around
if (!is_internal()) {
other.swap(*this);
return;
}
// This one is internal and the other is external.
// We need to get the old pointer, then move over the internal
// elements.
Pointer p = other.ext.pointer_;
Size capacity = other.ext.capacity_;
other.is_internal_ = true;
// Initialize and copy the internal elements for the other one
uninitialized_move_and_destroy(internal(), internal() + size_,
other.internal());
is_internal_ = false;
swap_size(other);
ext.pointer_ = p;
ext.capacity_ = capacity;
}
void clear()
noexcept(IS_NOTHROW_DESTRUCTIBLE)
{
if (size_ > 0) {
Data * p = data();
for (size_type i = 0; i < size_; ++i)
p[i].~Data();
}
if (!is_internal()) {
bool debug MLDB_UNUSED = false;
using namespace std;
#if COMPACT_VECTOR_DEBUG
if (debug)
cerr << "deallocating " << ext.capacity_ << " elements at "
<< ext.pointer_ << " for " << this << endl;
#endif
allocator.deallocate(ext.pointer_, ext.capacity_);
is_internal_ = true;
}
size_ = 0;
}
void reserve(size_t new_capacity)
{
if (capacity() >= new_capacity) return;
size_t to_alloc = std::max<size_t>(capacity() * 2, new_capacity);
to_alloc = std::min<size_t>(to_alloc, max_size());
compact_vector new_me;
new_me.init_move(begin(), end(), to_alloc);
swap(new_me);
}
void resize(size_t new_size, const Data & new_element = Data())
{
if (size_ == new_size) return;
if (size_ < new_size) {
// expand
reserve(new_size);
while (size_ < new_size) {
new (data() + size_) Data(new_element);
++size_;
}
return;
}
// contract
if (!is_internal() && new_size <= Internal) {
// Need to convert to internal representation
compact_vector new_me;
new_me.init_move(begin(), begin() + new_size, new_size);
swap(new_me);
return;
}
while (size_ > new_size) {
data()[size_ - 1].~Data();
--size_;
}
}
template<typename... Args>
void emplace_back(Args&&... args)
{
if (size_ >= capacity())
reserve(std::max<size_t>(size_ * 2, 1));
new (data() + size_) Data(std::forward<Args>(args)...);
++size_;
}
void push_back(Data&& d)
{
emplace_back(std::move(d));
}
void push_back(const Data & d)
{
emplace_back(d);
}
void pop_back()
{
if (Safe && empty())
throw MLDB::Exception("popping back empty compact vector");
#if 0 // save space when making smaller
if (size_ == Internal + 1) {
// Need to convert representation
compact_vector new_me(begin(), begin() + Internal, Internal);
swap(new_me);
return;
}
#endif
data()[size_ - 1].~Data();
--size_;
}
iterator insert(iterator pos, std::initializer_list<Data> list)
{
return insert(pos, list.begin(), list.end());
}
template <class ForwardIterator>
iterator insert(iterator pos,
ForwardIterator f, ForwardIterator l)
{
size_type nelements = std::distance(f, l);
iterator result = start_insert(pos, nelements);
// copy the new elements
std::copy(f, l, result);
return result;
}
iterator insert(iterator pos, const Data & x)
{
return insert(pos, 1, x);
}
iterator insert(iterator pos, size_type n, const Data & x)
{
iterator result = start_insert(pos, n);
std::fill(result, result + n, x);
return result;
}
template<typename... Args>
iterator emplace(iterator pos, Args&&... args)
{
iterator result = start_insert(pos, 1);
*result = Data(std::forward<Data>(args)...);
return result;
}
iterator erase(iterator pos)
{
return erase(pos, pos + 1);
}
iterator erase(iterator first, iterator last)
{
if (Safe) {
if (first > last)
throw MLDB::Exception("compact_vector::erase(): last before first");
if (first < begin() || last > end())
throw MLDB::Exception("compact_vector::erase(): iterators not ours");
}
int firstindex = first - begin();
int n = last - first;
if (n == 0) return first;
size_t new_size = size_ - n;
if (!is_internal() && new_size <= Internal) {
/* If we become small enough to be internal, then we need to copy
to avoid becoming smaller */
compact_vector new_me;
new_me.init(new_size);
Pointer newp = new_me.data();
std::uninitialized_copy(std::make_move_iterator(begin()),
std::make_move_iterator(first),
newp);
std::uninitialized_copy(std::make_move_iterator(last),
std::make_move_iterator(end()),
newp + (first - begin()));
new_me.size_ = new_size;
swap(new_me);
return begin() + firstindex;
}
/* Move the elements (TODO: swap instead of copy) */
std::copy(last, end(), first);
/* Delete those at the end */
while (size_ > new_size) {
data()[size_ - 1].~Data();
--size_;
}
return begin() + firstindex;
}
MLDB_ALWAYS_INLINE Data & operator [] (Size index)
{
if (Safe) check_index(index);
return data()[index];
}
MLDB_ALWAYS_INLINE const Data & operator [] (Size index) const
{
if (Safe) check_index(index);
return data()[index];
}
Data & at(Size index)
{
check_index(index);
return data()[index];
}
const Data & at(Size index) const
{
check_index(index);
return data()[index];
}
Data & front()
{
return operator [] (0);
}
const Data & front() const
{
return operator [] (0);
}
Data & back()
{
return operator [] (size_ - 1);
}
const Data & back() const
{
return operator [] (size_ - 1);
}
iterator begin() { return iterator(data()); }
constexpr const_iterator cbegin() const { return const_iterator(data()); }
constexpr const_iterator begin() const { return cbegin(); }
iterator end() { return iterator(data() + size_); }
constexpr const_iterator cend() const { return const_iterator(data() + size_); }
constexpr const_iterator end() const { return cend(); }
constexpr size_type size() const { return size_; }
constexpr bool empty() const { return size_ == 0; }
constexpr size_type capacity() const { return is_internal() ? Internal : ext.capacity_; }
size_type max_size() const
{
return std::numeric_limits<Size>::max();
}
Data * unsafe_raw_data() { return data(); }
const Data * unsafe_raw_data() const { return data(); }
private:
union {
struct {
char internal_[sizeof(Data) * Internal];
} MLDB_PACKED itl; //__attribute__((__aligned__((sizeof(Data))))) itl;
struct {
Pointer pointer_;
Size capacity_;
} MLDB_PACKED ext;
};
struct {
Size size_: 8 * sizeof(Size) - 1;
Size is_internal_ : 1;
} MLDB_PACKED;
constexpr bool is_internal() const { return is_internal_; }
Data * internal() { return (Data *)(itl.internal_); }
constexpr const Data * internal() const { return (Data *)(itl.internal_); }
Data * data() { return is_internal() ? internal() : ext.pointer_; }
constexpr const Data * data() const { return is_internal() ? internal() : ext.pointer_; }
void check_index(size_type index) const
{
if (index >= size_)
throw MLDB::Exception("compact_vector: index out of range");
}
void init(size_t to_alloc)
{
size_ = 0;
if (to_alloc > max_size())
throw MLDB::Exception("compact_vector can't grow that big");
if (to_alloc > Internal) {
is_internal_ = false;
ext.pointer_ = allocator.allocate(to_alloc);
ext.capacity_ = to_alloc;
}
else is_internal_ = true;
}
template<class InputIterator>
void init_copy(InputIterator first, InputIterator last, size_t to_alloc)
{
init(to_alloc);
Data * p = data();
// Copy the objects across into the uninitialized memory
for (; first != last; ++first, ++p, ++size_) {
if (Safe && size_ > to_alloc)
throw MLDB::Exception("compact_vector: internal logic error in init()");
new (p) Data(*first);
}
}
template<class InputIterator>
void init_move(InputIterator first, InputIterator last, size_t to_alloc)
noexcept(IS_NOTHROW_MOVE_CONSTRUCTIBLE)
{
init(to_alloc);
Data * p = data();
// Move the objects across into the uninitialized memory
for (; first != last; ++first, ++p, ++size_) {
if (Safe && size_ > to_alloc) {
::fprintf(stderr, "compact_vector: internal logic error in init()");
std::terminate();
}
new (p) Data(std::move_if_noexcept(*first));
}
}
void swap_size(compact_vector & other)
{
Size t = size_;
size_ = other.size_;
other.size_ = t;
}
/** Insert n objects at position index */
iterator start_insert(iterator pos, size_type n)
{
if (n == 0) return pos;
int index = pos - begin();
if (Safe && (index < 0 || index > size_))
throw MLDB::Exception("compact_vector insert: invalid index");
using namespace std;
bool debug MLDB_UNUSED = false;
#if COMPACT_VECTOR_DEBUG
if (debug)
cerr << "start_insert: index = " << index << " n = " << n
<< " size() = " << size() << " capacity() = "
<< capacity() << endl;
#endif
if (size() + n > capacity()) {
reserve(size() + n);
#if COMPACT_VECTOR_DEBUG
if (debug)
cerr << "after reserve: index = " << index << " n = " << n
<< " size() = " << size() << " capacity() = "
<< capacity() << endl;
#endif
}
#if COMPACT_VECTOR_DEBUG
if (debug)
cerr << "data() = " << data() << endl;
#endif
// New element
for (unsigned i = 0; i < n; ++i, ++size_) {
#if COMPACT_VECTOR_DEBUG
if (debug)
cerr << "i = " << i << " n = " << n << " size_ = " << size_
<< endl;
#endif
new (data() + size_) Data();
}
// Move elements to the end
for (int i = size_ - 1; i >= index + (int)n; --i)
data()[i] = std::move(data()[i - n]);
return begin() + index;
}
static Allocator allocator;
} MLDB_ALIGNED((alignof(Data)));
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
Allocator
compact_vector<Data, Internal, Size, Safe, Pointer, Allocator>::allocator;
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator == (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return cv1.size() == cv2.size()
&& std::equal(cv1.begin(), cv1.end(), cv2.begin());
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator != (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return ! operator == (cv1, cv2);
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator < (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return std::lexicographical_compare(cv1.begin(), cv1.end(),
cv2.begin(), cv2.end());
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator <= (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return (cv1 == cv2 || cv1 < cv2);
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator > (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return cv2 < cv1;
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
bool
operator >= (const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv1,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv2)
{
return cv1 == cv2 || cv2 < cv1;
}
template<class Data, size_t Internal, class Size, bool Safe,
class Pointer, class Allocator>
std::ostream &
operator << (std::ostream & stream,
const compact_vector<Data, Internal, Size, Safe, Pointer, Allocator> & cv)
{
stream << "{ ";
std::copy(cv.begin(), cv.end(), std::ostream_iterator<Data>(stream, " "));
return stream << " }";
}
template<typename D, size_t I, typename S, bool Sf, typename P, class A>
void make_vector_set(compact_vector<D, I, S, Sf, P, A> & vec)
{
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}
} // namespace MLDB
#pragma GCC diagnostic pop
| 9,259 |
749 | <gh_stars>100-1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper script to bump the current version."""
import argparse
import re
import subprocess
from packaging.version import Version
from plexapi import const
SUPPORTED_BUMP_TYPES = ["patch", "minor", "major"]
def _bump_release(release, bump_type):
"""Return a bumped release tuple consisting of 3 numbers."""
major, minor, patch = release
if bump_type == "patch":
patch += 1
elif bump_type == "minor":
minor += 1
patch = 0
elif bump_type == "major":
major += 1
minor = 0
patch = 0
return major, minor, patch
def bump_version(version, bump_type):
"""Return a new version given a current version and action."""
new_release = _bump_release(version.release, bump_type)
temp = Version("0")
temp._version = version._version._replace(release=new_release)
return Version(str(temp))
def write_version(version):
"""Update plexapi constant file with new version."""
with open("plexapi/const.py") as f:
content = f.read()
version_names = ["MAJOR", "MINOR", "PATCH"]
version_values = str(version).split(".", 2)
for n, v in zip(version_names, version_values):
version_line = f"{n}_VERSION = "
content = re.sub(f"{version_line}.*\n", f"{version_line}{v}\n", content)
with open("plexapi/const.py", "wt") as f:
content = f.write(content)
def main():
"""Execute script."""
parser = argparse.ArgumentParser(description="Bump version of plexapi")
parser.add_argument(
"bump_type",
help="The type of version bump to perform",
choices=SUPPORTED_BUMP_TYPES,
)
parser.add_argument(
"--commit", action="store_true", help="Create a version bump commit"
)
parser.add_argument(
"--tag", action="store_true", help="Tag the commit with the release version"
)
arguments = parser.parse_args()
if arguments.tag and not arguments.commit:
parser.error("--tag requires use of --commit")
if arguments.commit and subprocess.run(["git", "diff", "--quiet"]).returncode == 1:
print("Cannot use --commit because git is dirty")
return
current = Version(const.__version__)
bumped = bump_version(current, arguments.bump_type)
assert bumped > current, "Bumped version is not newer than old version"
write_version(bumped)
if not arguments.commit:
return
subprocess.run(["git", "commit", "-nam", f"Release {bumped}"])
if arguments.tag:
subprocess.run(["git", "tag", str(bumped), "-m", f"Release {bumped}"])
def test_bump_version():
"""Make sure it all works."""
import pytest
assert bump_version(Version("4.7.0"), "patch") == Version("4.7.1")
assert bump_version(Version("4.7.0"), "minor") == Version("4.8.0")
assert bump_version(Version("4.7.3"), "minor") == Version("4.8.0")
assert bump_version(Version("4.7.0"), "major") == Version("5.0.0")
assert bump_version(Version("4.7.3"), "major") == Version("5.0.0")
assert bump_version(Version("5.0.0"), "major") == Version("6.0.0")
if __name__ == "__main__":
main()
| 1,225 |
8,624 | <reponame>VladislavLobakh/dom-to-image-extended<filename>bower_components/ocrad-bower/ocrad-0.23-pre1/ucs.h
/* GNU Ocrad - Optical Character Recognition program
Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
2012, 2013 <NAME>.
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 3 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/>.
*/
namespace UCS {
enum { IEXCLAM = 0x00A1, // inverted exclamation mark
COPY = 0x00A9, // copyright sign
FEMIORD = 0x00AA, // feminine ordinal indicator
LDANGLE = 0x00AB, // left-pointing double angle quotation mark
NOT = 0x00AC, // not sign
REG = 0x00AE, // registered sign
DEG = 0x00B0, // degree sign
PLUSMIN = 0x00B1, // plus-minus sign
POW2 = 0x00B2, // superscript two
POW3 = 0x00B3, // superscript three
MICRO = 0x00B5, // micro sign
PILCROW = 0x00B6, // pilcrow sign
MIDDOT = 0x00B7, // middle dot
POW1 = 0x00B9, // superscript one
MASCORD = 0x00BA, // masculine ordinal indicator
RDANGLE = 0x00BB, // right-pointing double angle quotation mark
IQUEST = 0x00BF, // inverted question mark
CAGRAVE = 0x00C0, // latin capital letter a with grave
CAACUTE = 0x00C1, // latin capital letter a with acute
CACIRCU = 0x00C2, // latin capital letter a with circumflex
CATILDE = 0x00C3, // latin capital letter a with tilde
CADIAER = 0x00C4, // latin capital letter a with diaeresis
CARING = 0x00C5, // latin capital letter a with ring above
CCCEDI = 0x00C7, // latin capital letter c with cedilla
CEGRAVE = 0x00C8, // latin capital letter e with grave
CEACUTE = 0x00C9, // latin capital letter e with acute
CECIRCU = 0x00CA, // latin capital letter e with circumflex
CEDIAER = 0x00CB, // latin capital letter e with diaeresis
CIGRAVE = 0x00CC, // latin capital letter i with grave
CIACUTE = 0x00CD, // latin capital letter i with acute
CICIRCU = 0x00CE, // latin capital letter i with circumflex
CIDIAER = 0x00CF, // latin capital letter i with diaeresis
CNTILDE = 0x00D1, // latin capital letter n with tilde
COGRAVE = 0x00D2, // latin capital letter o with grave
COACUTE = 0x00D3, // latin capital letter o with acute
COCIRCU = 0x00D4, // latin capital letter o with circumflex
COTILDE = 0x00D5, // latin capital letter o with tilde
CODIAER = 0x00D6, // latin capital letter o with diaeresis
CUGRAVE = 0x00D9, // latin capital letter u with grave
CUACUTE = 0x00DA, // latin capital letter u with acute
CUCIRCU = 0x00DB, // latin capital letter u with circumflex
CUDIAER = 0x00DC, // latin capital letter u with diaeresis
CYACUTE = 0x00DD, // latin capital letter y with acute
SSSHARP = 0x00DF, // latin small letter sharp s (german)
SAGRAVE = 0x00E0, // latin small letter a with grave
SAACUTE = 0x00E1, // latin small letter a with acute
SACIRCU = 0x00E2, // latin small letter a with circumflex
SATILDE = 0x00E3, // latin small letter a with tilde
SADIAER = 0x00E4, // latin small letter a with diaeresis
SARING = 0x00E5, // latin small letter a with ring above
SCCEDI = 0x00E7, // latin small letter c with cedilla
SEGRAVE = 0x00E8, // latin small letter e with grave
SEACUTE = 0x00E9, // latin small letter e with acute
SECIRCU = 0x00EA, // latin small letter e with circumflex
SEDIAER = 0x00EB, // latin small letter e with diaeresis
SIGRAVE = 0x00EC, // latin small letter i with grave
SIACUTE = 0x00ED, // latin small letter i with acute
SICIRCU = 0x00EE, // latin small letter i with circumflex
SIDIAER = 0x00EF, // latin small letter i with diaeresis
SNTILDE = 0x00F1, // latin small letter n with tilde
SOGRAVE = 0x00F2, // latin small letter o with grave
SOACUTE = 0x00F3, // latin small letter o with acute
SOCIRCU = 0x00F4, // latin small letter o with circumflex
SOTILDE = 0x00F5, // latin small letter o with tilde
SODIAER = 0x00F6, // latin small letter o with diaeresis
DIV = 0x00F7, // division sign
SUGRAVE = 0x00F9, // latin small letter u with grave
SUACUTE = 0x00FA, // latin small letter u with acute
SUCIRCU = 0x00FB, // latin small letter u with circumflex
SUDIAER = 0x00FC, // latin small letter u with diaeresis
SYACUTE = 0x00FD, // latin small letter y with acute
SYDIAER = 0x00FF, // latin small letter y with diaeresis
CGBREVE = 0X011E, // latin capital letter g with breve
SGBREVE = 0x011F, // latin small letter g with breve
CIDOT = 0x0130, // latin capital letter i with dot above
SINODOT = 0x0131, // latin small letter i dotless
CSCEDI = 0x015E, // latin capital letter s with cedilla
SSCEDI = 0x015F, // latin small letter s with cedilla
CSCARON = 0x0160, // latin capital letter s with caron
SSCARON = 0x0161, // latin small letter s with caron
CZCARON = 0x017D, // latin capital letter z with caron
SZCARON = 0x017E, // latin small letter z with caron
EURO = 0x20AC // symbole euro
};
int base_letter( const int code );
int compose( const int letter, const int accent );
bool isalnum( const int code );
bool isalpha( const int code );
bool isdigit( const int code );
bool ishigh( const int code ); // high chars like "A1bp|"
bool islower( const int code );
bool islower_ambiguous( const int code );
bool islower_small( const int code );
bool islower_small_ambiguous( const int code );
bool isspace( const int code );
bool isupper( const int code );
bool isvowel( int code );
unsigned char map_to_byte( const int code );
const char * ucs_to_utf8( const int code );
int to_nearest_digit( const int code );
int to_nearest_letter( const int code );
int toupper( const int code );
} // end namespace UCS
| 2,699 |
387 | /*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.test.vm.threads;
import gov.nasa.jpf.util.test.TestJPF;
import org.junit.Test;
/**
* signal test (wait/notify)
*/
public class WaitTest extends TestJPF
{
int counter;
boolean cond;
boolean done;
@Test public void testVerySimpleWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testVerySimpleWait()");
synchronized (this) {
try {
System.out.println("waiting");
wait(100L);
System.out.println("timed out");
} catch (InterruptedException ix) {
throw new RuntimeException("got interrupted");
}
}
}
}
@Test public void testSimpleWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testSimpleWait()");
Runnable notifier = new Runnable() {
@Override
public void run() {
synchronized (WaitTest.this) {
System.out.println("notifying");
cond = true;
WaitTest.this.notify();
}
}
};
Thread t = new Thread(notifier);
cond = false;
synchronized (this) {
t.start();
try {
System.out.println("waiting");
wait();
System.out.println("notified");
if (!cond) {
throw new RuntimeException("'cond' not set, premature wait return");
}
} catch (InterruptedException ix) {
throw new RuntimeException("got interrupted");
}
}
}
}
@Test public void testSyncRunWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testSyncRunWait()");
Runnable waiter = new Runnable() {
@Override
public synchronized void run() {
System.out.println("thread-0 running");
try {
wait(); // needs to be first insn
System.out.println("thread-0 notified");
} catch (InterruptedException ix) {
throw new RuntimeException("thread-0 got interrupted");
}
}
};
Thread t = new Thread(waiter);
t.setDaemon(true); // to make sure we don't get a deadlock
t.start();
synchronized (waiter) {
System.out.println("main notifying");
waiter.notify();
}
}
}
@Test public void testTimeoutWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testTimeoutWait()");
Runnable notifier = new Runnable() {
@Override
public void run() {
synchronized (WaitTest.this) {
System.out.println("notifying");
cond = true;
WaitTest.this.notify();
}
}
};
Thread t = new Thread(notifier);
cond = false;
synchronized (this) {
if (false) {
t.start();
}
try {
System.out.println("waiting");
wait(1);
if (cond) {
System.out.println("got notified");
} else {
System.out.println("wait timed out");
}
} catch (InterruptedException ix) {
throw new RuntimeException("got interrupted");
}
}
}
}
@Test public void testLoopedWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testLoopedWait()");
Runnable notifier = new Runnable() {
@Override
public void run() {
while (!done) {
synchronized (WaitTest.this) {
System.out.println("notifying");
cond = true;
WaitTest.this.notify();
}
}
}
};
Thread t = new Thread(notifier);
cond = false;
done = false;
t.start();
synchronized (this) {
for (int i = 0; i < 2; i++) {
try {
System.out.println("waiting "); //System.out.println(i);
wait();
System.out.println("notified "); //System.out.println(i);
if (!cond) {
throw new RuntimeException("'cond' not set, premature wait return");
}
cond = false;
} catch (InterruptedException ix) {
throw new RuntimeException("got interrupted");
}
}
done = true;
}
}
}
@Test public void testInterruptedWait () {
if (verifyNoPropertyViolation()) {
System.out.println("running testInterruptedWait()");
final Thread current = Thread.currentThread();
Runnable notifier = new Runnable() {
@Override
public void run() {
synchronized (WaitTest.this) {
System.out.println("interrupting");
cond = true;
current.interrupt();
}
}
};
Thread t = new Thread(notifier);
cond = false;
synchronized (this) {
t.start();
try {
System.out.println("waiting");
wait();
System.out.println("notified");
throw new RuntimeException("notified, not interrupted");
} catch (InterruptedException ix) {
System.out.println("interrupted");
//System.out.println(cond);
if (!cond) {
throw new RuntimeException("'cond' not set, premature wait return");
}
}
}
}
}
class Waiter implements Runnable {
String name;
boolean waiting;
boolean done1;
Waiter (String name) {
this.name = name;
waiting = false;
done1 = false;
}
@Override
public void run () {
synchronized (WaitTest.this) {
try {
System.out.print(name); System.out.println(" waiting");
waiting = true;
WaitTest.this.wait();
System.out.print(name); System.out.println(" notified");
done1 = true;
} catch (InterruptedException ix) {
throw new RuntimeException("waiter was interrupted");
}
}
}
}
/**
* that's a misnomer, since this one executes almost all of signal handling (except of mixed
* wait/timeout-wait and timeout joins) it should be called 'testAlmostAll'
*
*/
@Test public void testNotifyAll () {
if (verifyNoPropertyViolation()) {
System.out.println("running testNotifyAll()");
Waiter waiter1 = new Waiter("waiter1");
Thread t1 = new Thread(waiter1);
t1.start();
while (!waiter1.waiting) {
Thread.yield();
}
Waiter waiter2 = new Waiter("waiter2");
Thread t2 = new Thread(waiter2);
t2.start();
while (!waiter2.waiting) {
Thread.yield();
}
synchronized (this) {
System.out.println("main notifying all waiters..");
notifyAll();
System.out.println("..done");
}
try {
t1.join();
} catch (InterruptedException ix) {
throw new RuntimeException("main interrupted while waiting for thread1 to finish");
}
try {
t2.join();
} catch (InterruptedException ix) {
throw new RuntimeException("main interrupted while waiting for thread2 to finish");
}
synchronized (this) {
if (!waiter1.done1) {
throw new RuntimeException("waiter1 was not done");
}
if (!waiter2.done1) {
throw new RuntimeException("waiter2 was not done");
}
}
}
}
}
| 3,552 |
2,151 | <gh_stars>1000+
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef FXJS_CJS_UTIL_H_
#define FXJS_CJS_UTIL_H_
#include <string>
#include <vector>
#include "fxjs/JS_Define.h"
// Return values for ParseDataType() below.
#define UTIL_INT 0
#define UTIL_DOUBLE 1
#define UTIL_STRING 2
class CJS_Util : public CJS_Object {
public:
static void DefineJSObjects(CFXJS_Engine* pEngine);
explicit CJS_Util(v8::Local<v8::Object> pObject);
~CJS_Util() override;
static WideString printx(const WideString& cFormat,
const WideString& cSource);
JS_STATIC_METHOD(printd, CJS_Util);
JS_STATIC_METHOD(printf, CJS_Util);
JS_STATIC_METHOD(printx, CJS_Util);
JS_STATIC_METHOD(scand, CJS_Util);
JS_STATIC_METHOD(byteToChar, CJS_Util);
private:
friend class CJS_Util_ParseDataType_Test;
static int ObjDefnID;
static const char kName[];
static const JSMethodSpec MethodSpecs[];
static int ParseDataType(std::wstring* sFormat);
CJS_Return printd(CJS_Runtime* pRuntime,
const std::vector<v8::Local<v8::Value>>& params);
CJS_Return printf(CJS_Runtime* pRuntime,
const std::vector<v8::Local<v8::Value>>& params);
CJS_Return printx(CJS_Runtime* pRuntime,
const std::vector<v8::Local<v8::Value>>& params);
CJS_Return scand(CJS_Runtime* pRuntime,
const std::vector<v8::Local<v8::Value>>& params);
CJS_Return byteToChar(CJS_Runtime* pRuntime,
const std::vector<v8::Local<v8::Value>>& params);
};
#endif // FXJS_CJS_UTIL_H_
| 741 |
1,132 | <filename>Scores.h
// <NAME>, copyright Jul 2005
// . the Scores class is a vector to weight Words scores by
// . this was originally made to extract the news article from a web page
// and discard the words in menu sections and other cruft.
// . words are weighted by the number of neighboring words in their "sections"
// that are not in hyperlinks.
// . "sections" are determined by table/tr/td/div/... etc tags
// . m_scores is 1-1 with the words in the supplied "words" class
#ifndef _SCORES_H_
#define _SCORES_H_
#include "Words.h"
// if you change this you must also change the shift logic in Phrases.cpp
// for setting the "minScore"
#define NORM_WORD_SCORE 128
#define SCORES_LOCALBUFSIZE 20
class Scores {
public:
Scores();
~Scores();
void reset();
// if indexContentSectionsOnly is true, only the words in the most
// relevant scores will have positive scores, all other words are
// discarded.
//bool set ( class Words *words , bool indexContentSectionsOnly );
bool set ( class Words *words ,
class Sections *sections ,
int32_t titleRecVersion ,
// this is true to zero-out terms in the menus, otherwise
// we assign them a minimal score of 1
bool eliminateMenus ,
// provide it with a buffer to prevent a malloc
char *buf = NULL ,
int32_t bufSize = 0 ,
int32_t minIndexableWords = -1 );
//char m_localBuf [ MAX_WORDS*8*10 ];
char m_localBuf[SCORES_LOCALBUFSIZE];
char *m_buf;
int32_t m_bufSize;
bool m_needsFree;
private:
// returns false and sets g_errno on error
bool set ( class Words *words ,
class Sections *sections ,
int32_t titleRecVersion ,
bool scoreBySection ,
bool indexContentSectionOnly ,
int32_t minSectionScore ,
int32_t minAvgWordScore ,
int32_t minIndexableWords ,
// these are for weighting top part of news articles
int32_t numTopWords ,
float topWordsWeight ,
float topSentenceWeight ,
int32_t maxWordsInSentence ,
char *buf = NULL ,
int32_t bufSize = 0 ) ;
public:
int32_t getMemUsed () { return m_bufSize; };
int32_t getScore ( int32_t i ) { return m_scores[i]; };
// private:
bool setScoresBySection ( class Words *words ,
bool indexContentSectionOnly ,
int32_t minSectionScore ,
int32_t minAvgWordScore );
// percent to weight word scores by... actually from 0 to 128
// for speed reasons
int32_t *m_scores;
//int32_t *m_rerankScores;
// these are printed out by PageParser.cpp in TermTable.cpp
bool m_scoreBySection ;
bool m_indexContentSectionOnly ;
int32_t m_minSectionScore ;
int32_t m_minAvgWordScore ;
int32_t m_minIndexableWords ;
int32_t m_numTopWords ;
float m_topWordsWeight ;
float m_topSentenceWeight ;
int32_t m_maxWordsInSentence ;
};
#endif
| 1,516 |
303 | <filename>java/jog/libraries/jog/jog_stdlib.java
//=============================================================================
// Jog Standard Library
//=============================================================================
//=============================================================================
// ArrayList
//=============================================================================
class ArrayList<DataType>
{
DataType[] data;
int size;
ArrayList()
{
this(10);
}
ArrayList( int capacity )
{
assert( capacity>=1, "Initial ArrayList capacity must be at least 1." );
data = new DataType[capacity];
}
Iterator<DataType> iterator()
{
return new ArrayListIterator<DataType>(this);
}
int size() { return size; }
void ensureCapacity( int min_capacity )
{
if (data.length >= min_capacity) return;
int new_cap = data.length * 2;
if (new_cap < min_capacity) new_cap = min_capacity;
DataType[] new_data = new DataType[new_cap];
for (int i=0; i<size; ++i) { new_data[i] = data[i]; }
data = new_data;
}
boolean add( DataType value )
{
ensureCapacity(size+1);
data[size++] = value;
return true;
}
DataType get( int index )
{
assert( index>=0 && index<size, "ArrayList get() index out of bounds." );
return data[index];
}
}
//=============================================================================
// Iterator<DataType>
//=============================================================================
interface Iterator<DataType>
{
boolean hasNext();
DataType next();
void remove();
}
class ArrayListIterator<DataType> implements Iterator<DataType>
{
ArrayList<DataType> list;
int next_index;
ArrayListIterator( ArrayList<DataType> list )
{
this.list = list;
}
boolean hasNext() { return next_index < list.size(); }
DataType next() { return list.get(next_index++); }
void remove() { }
}
//=============================================================================
// Math
//=============================================================================
class Math
{
static Random random_gen = new Random();
static double PI = acos(-1.0);
native static double abs( double n );
native static float abs( float n );
native static int abs( int n );
native static long abs( long n );
native static double cos( double radians );
native static double sin( double radians );
native static double tan( double radians );
native static double acos( double n );
native static double asin( double n );
native static double atan( double slope );
native static double atan2( double y, double x );
native static double pow( double n, double power );
native static double sqrt( double n );
native static double min( double n, double m );
native static float min( float n, float m );
native static int min( int n, int m );
native static long min( long n, long m );
native static double max( double n, double m );
native static float max( float n, float m );
native static int max( int n, int m );
native static long max( long n, long m );
native static double ceil( double n );
native static double floor( double n );
static double random() { return random_gen.nextDouble(); }
}
//=============================================================================
// Number + associated
// - Byte, Double, Float, Integer, Long, Short, Boolean, Character
//=============================================================================
abstract class Number
{
abstract byte byteValue();
abstract double doubleValue();
abstract float floatValue();
abstract int intValue();
abstract long longValue();
abstract short shortValue();
}
class Byte extends Number
{
static String toString( byte b )
{
return Integer.toString(b);
}
// PROPERTIES
byte value;
// METHODS
public Byte( byte value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
String toString() { return toString(value); }
}
class Double extends Number
{
// CLASS METHODS
static String toString( double n )
{
// This simple implementation prints out the full number with
// exactly 4 digits after the decimal point. It uses
// a 'long' to store the whole and fractional parts of the
// number, so numbers larger than +/- 2E63 will not convert
// correctly.
boolean is_negative = false;
if (n < 0)
{
is_negative = true;
n = -n;
}
long whole = (long) Math.floor(n);
n = n - Math.floor(n);
n *= 10000.0;
if (n - Math.floor(n) >= 0.5) n += 1.0; // round off
long decimal = (long) Math.floor(n);
String whole_st = Long.toString(whole);
if (is_negative) whole_st = "-" + whole_st;
String decimal_st = Long.toString(decimal);
// Kludge
if (decimal < 1000) decimal_st = "0" + decimal_st;
if (decimal < 100) decimal_st = "0" + decimal_st;
if (decimal < 10) decimal_st = "0" + decimal_st;
while (decimal_st.length() < 4) decimal_st += "0";
return whole_st + "." + decimal_st;
}
// PROPERTIES
double value;
// METHODS
public Double( double value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
String toString() { return toString(value); }
}
class Float extends Number
{
// CLASS METHODS
static String toString( float n ) { return Double.toString(n); }
// PROPERTIES
float value;
// METHODS
public Float( float value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
String toString() { return toString(value); }
}
class Integer extends Number
{
// CLASS METHODS
static String toString( int n )
{
if (n == 0) return "0";
if (n == 0x80000000) return "-2147483648";
StringBuilder buffer = new StringBuilder();
boolean is_negative = false;
if (n < 0)
{
is_negative = true;
n = -n;
}
while (n > 0)
{
buffer.append( (char)((n%10)+'0') );
n /= 10;
}
if (is_negative) buffer.append('-');
return buffer.reverse().toString();
}
// PROPERTIES
int value;
// METHODS
public Integer( int value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
public String toString()
{
return toString(value);
}
}
class Long extends Number
{
// CLASS METHODS
static String toString( long n )
{
if (n == 0) return "0";
if (n == 0x8000000000000000L) return "-9223372036854775808";
StringBuilder buffer = new StringBuilder();
boolean is_negative = false;
if (n < 0)
{
is_negative = true;
n = -n;
}
while (n > 0)
{
buffer.append( (char)((n%10)+'0') );
n /= 10;
}
if (is_negative) buffer.append('-');
return buffer.reverse().toString();
}
// PROPERTIES
long value;
// METHODS
public Long( long value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
public String toString()
{
return toString(value);
}
}
class Short extends Number
{
// CLASS METHODS
static String toString( short n ) { return Integer.toString(n); }
// PROPERTIES
short value;
// METHODS
public Short( short value )
{
this.value = value;
}
byte byteValue() { return (byte) value; }
double doubleValue() { return (double) value; }
float floatValue() { return (float) value; }
int intValue() { return (int) value; }
long longValue() { return (long) value; }
short shortValue() { return (short) value; }
String toString() { return toString(value); }
}
class Boolean
{
// CLASS METHODS
static String toString( boolean b )
{
if (b) return "true";
return "false";
}
// PROPERTIES
boolean value;
// METHODS
public Boolean( boolean value )
{
this.value = value;
}
boolean booleanValue() { return value; }
String toString() { return toString(value); }
}
class Character
{
static String[] ascii_strings =
{
"", "", "", "", "", "", "", "",
"\t", "\n", "", "", "\r", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
" ", "!", "\"", "#", "$", "%", "&", "'",
"(", ")", "*", "+", ",", "-", ".", "/",
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", ":", ";", "<", "=", ">", "?",
"@", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "[", "\\", "]", "^", "_",
"`", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z", "{", "|", "}", "~", ""
};
// CLASS METHODS
static String toString( char ch )
{
if (ch < 128)
{
String result = ascii_strings[ch];
if (result == null)
{
result = new String( new char[]{ch} );
ascii_strings[ch] = result;
}
return result;
}
else
{
return new String( new char[]{ch} );
}
}
// PROPERTIES
char value;
// METHODS
public Character( char value )
{
this.value = value;
}
char charValue() { return value; }
String toString() { return toString(value); }
}
class Object
{
public Object() { }
public String toString() { return "(An Object)"; }
static public void print( boolean n ) { System.out.print(n); }
static public void print( char ch ) { System.out.print(ch); }
static public void print( double n ) { System.out.print(n); }
static public void print( int n ) { System.out.print(n); }
static public void print( long n ) { System.out.print(n); }
static public void print( Object obj )
{
if (obj == null) System.out.print("null");
else System.out.print(obj.toString());
}
static public void print( String st ) { System.out.print(st); }
static public void println() { System.out.println(); }
static public void println( boolean n ) { System.out.println(n); }
static public void println( char ch ) { System.out.println(ch); }
static public void println( double n ) { System.out.println(n); }
static public void println( int n ) { System.out.println(n); }
static public void println( long n ) { System.out.println(n); }
static public void println( Object obj )
{
if (obj == null) System.out.println("null");
else System.out.println(obj.toString());
}
static public void println( String st ) { System.out.println(st); }
}
class String
{
// Note: the native layer assumes these two properties are defined as they are.
char[] data;
int hash_code;
public String( char[] data )
{
this( data, data.length );
}
public String( char[] data, int count )
{
this.data = new char[count];
for (int i=0; i<count; ++i)
{
char ch = data[i];
hash_code = (hash_code << 1) + ch;
this.data[i] = ch;
}
}
public String toString()
{
return this;
}
public int length()
{
return data.length;
}
public String concat( String other )
{
if (other == null) return concat("null");
char[] new_data = new char[data.length + other.data.length];
int c = data.length;
for (int i=0; i<c; ++i) new_data[i] = data[i];
int c2 = other.data.length;
for (int i=0; i<c2; ++i) new_data[c++] = other.data[i];
return new String(new_data);
}
public boolean equals( Object other_object )
{
if (this == other_object) return true;
String other = other_object.toString();
if (other == null || this.data.length != other.data.length) return false;
int count = data.length;
for (int i=0; i<count; ++i)
{
if (data[i] != other.data[i]) return false;
}
return true;
}
public boolean equalsIgnoreCase( Object other_object )
{
if (this == other_object) return true;
String other = other_object.toString();
if (other == null || this.data.length != other.data.length) return false;
int count = data.length;
for (int i=0; i<count; ++i)
{
char ch1 = data[i];
char ch2 = other.data[i];
if (ch1 >= 'A' && ch1 <= 'Z') ch1 += ('a'-'A');
if (ch2 >= 'A' && ch2 <= 'Z') ch2 += ('a'-'A');
if (ch1 != ch2) return false;
}
return true;
}
char charAt(int index) { return data[index]; }
int compareTo( String other )
{
if (this == other) return 0;
int count = data.length;
if (count > other.data.length) count = other.data.length;
for (int i=0; i<count; ++i)
{
char ch1 = data[i];
char ch2 = other.data[i];
if (ch1 != ch2)
{
if (ch1 > ch2) return 1;
else return -1;
}
}
if (data.length > other.data.length) return 1;
if (data.length < other.data.length) return -1;
return 0;
}
int compareToIgnoreCase(String other)
{
if (this == other) return 0;
int count = data.length;
if (count > other.data.length) count = other.data.length;
for (int i=0; i<count; ++i)
{
char ch1 = data[i];
char ch2 = other.data[i];
if (ch1 >= 'A' && ch1 <= 'Z') ch1 += ('a'-'A');
if (ch2 >= 'A' && ch2 <= 'Z') ch2 += ('a'-'A');
if (ch1 != ch2)
{
if (ch1 > ch2) return 1;
else return -1;
}
}
if (data.length > other.data.length) return 1;
if (data.length < other.data.length) return -1;
return 0;
}
boolean endsWith( String suffix )
{
int i = indexOf( suffix );
if (i == -1) return false;
return (i == data.length - suffix.data.length);
}
int hashCode() { return hash_code; }
int indexOf( int ch ) { return indexOf( ch, 0 ); }
int indexOf( int ch, int i1 )
{
int count = data.length;
for (int i=i1; i<count; ++i)
{
if (data[i] == ch) return i;
}
return -1;
}
int indexOf( String st ) { return indexOf( st, 0 ); }
int indexOf( String st, int i1 )
{
int count = data.length - (st.data.length - 1);
int ch1 = st.data[0];
for (int i=i1; i<count; ++i)
{
if (data[i] == ch1)
{
if (regionMatches( false, i, st, 0, st.data.length ))
{
return i;
}
}
}
return -1;
}
String intern() { return this; } // dummy implementation
boolean isEmpty() { return data.length == 0; }
int lastIndexOf(int ch) { return lastIndexOf(ch,data.length-1); }
int lastIndexOf( int ch, int i2 )
{
for (int i=i2; i>=0; --i)
{
if (data[i] == ch) return i;
}
return -1;
}
int lastIndexOf( String st ) { return lastIndexOf(st,data.length-1); }
int lastIndexOf( String st, int i2 )
{
int ch1 = st.data[0];
for (int i=i2; i>=0; --i)
{
if (data[i] == ch1)
{
if (regionMatches(false, i, st, 0, st.data.length))
{
return i;
}
}
}
return -1;
}
boolean regionMatches( boolean ignoreCase, int this_offset,
String other, int other_offset, int count )
{
if (this_offset < 0 || other_offset < 0) return false;
if (this_offset + count > data.length) return false;
if (other_offset + count > other.data.length) return false;
for (int i=0; i<count; ++i)
{
char ch1 = data[this_offset+i];
char ch2 = other.data[other_offset+i];
if (ignoreCase)
{
if (ch1 >= 'A' && ch1 <= 'Z') ch1 += ('a'-'A');
if (ch2 >= 'A' && ch2 <= 'Z') ch2 += ('a'-'A');
}
if (ch1 != ch2) return false;
}
return true;
}
boolean regionMatches( int this_offset, String other, int other_offset, int count )
{
return regionMatches( false, this_offset, other, other_offset, count );
}
String replace( char old_char, char new_char )
{
StringBuilder buffer = new StringBuilder();
int count = data.length;
for (int i=0; i<count; ++i)
{
char ch = data[i];
if (ch == old_char) ch = new_char;
buffer.append(ch);
}
return buffer.toString();
}
String replace( String target, String replacement )
{
// Note: Jog parameters changed from CharSequence to String.
StringBuilder buffer = new StringBuilder();
String remaining = this;
while (remaining.data.length > 0)
{
int i = remaining.indexOf(target);
if (i >= 0)
{
buffer.append( remaining.substring(0,i) );
buffer.append( replacement );
remaining = remaining.substring(i+target.data.length);
}
else
{
buffer.append( remaining );
break;
}
}
return buffer.toString();
}
String replaceAll( String target, String replacement )
{
// Note: target considered a string instead of a regex.
return replace(target,replacement);
}
String replaceFirst( String target, String replacement )
{
// Note: target considered a string instead of a regex.
int i = indexOf(target);
if (i >= 0)
{
return substring(0,i) + replacement + substring(i+target.data.length);
}
else
{
return this;
}
}
String[] split( String splitter )
{
ArrayList<String> strings = new ArrayList<String>();
String remaining = this;
while (remaining.data.length > 0)
{
int i = remaining.indexOf(splitter);
if (i >= 0)
{
strings.add( remaining.substring(0,i) );
remaining = remaining.substring( i + splitter.data.length );
}
else
{
strings.add( remaining );
break;
}
}
String[] results = new String[ strings.size() ];
for (int i=0; i<results.length; ++i)
{
results[i] = strings.get(i);
}
return results;
}
boolean startsWith( String prefix )
{
return indexOf(prefix) == 0;
}
boolean startsWith( String prefix, int offset )
{
return indexOf(prefix,offset) == offset;
}
String substring( int i1 )
{
return substring( i1, data.length );
}
String substring( int i1, int i2_exclusive )
{
StringBuilder buffer = new StringBuilder();
for (int i=i1; i<i2_exclusive; ++i)
{
buffer.append(data[i]);
}
return buffer.toString();
}
char[] toCharArray()
{
int count = data.length;
char[] result = new char[count];
for (int i=0; i<count; ++i)
{
result[i] = data[i];
}
return result;
}
String toLowerCase()
{
StringBuilder buffer = new StringBuilder();
int count = data.length;
for (int i=0; i<count; ++i)
{
char ch = data[i];
if (ch >= 'A' && ch <= 'Z') ch += ('a'-'A');
buffer.append(ch);
}
return buffer.toString();
}
String toUpperCase()
{
StringBuilder buffer = new StringBuilder();
int count = data.length;
for (int i=0; i<count; ++i)
{
char ch = data[i];
if (ch >= 'a' && ch <= 'z') ch += ('A'-'a');
buffer.append(ch);
}
return buffer.toString();
}
String trim()
{
String result = this;
while (result.data.length > 0 && result.data[0] == ' ')
{
result = result.substring(1);
}
while (result.data.length > 0 && result.data[result.data.length-1] == ' ')
{
result = result.substring(0,result.data.length-1);
}
return result;
}
/*
static String valueOf(boolean b)
{
}
static String valueOf(char c)
{
}
static String valueOf(char[] data)
{
}
static String valueOf(char[] data, int offset, int count)
{
}
static String valueOf(double d)
{
}
static String valueOf(float f)
{
}
static String valueOf(int i)
{
}
static String valueOf(long l)
{
}
static String valueOf(Object obj)
{
}
*/
}
class StringBuilder
{
char[] data;
int size;
public StringBuilder()
{
data = new char[16];
}
public StringBuilder( int capacity )
{
data = new char[capacity];
}
public StringBuilder( String initial_contents )
{
this( initial_contents.length() );
size = initial_contents.length();
for (int i=0; i<size; ++i) data[i] = initial_contents.data[i];
}
public String toString()
{
return new String(data,size);
}
public void ensureCapacity( int min_capacity )
{
if (data.length >= min_capacity) return;
int new_cap = data.length * 2 + 2;
if (min_capacity > new_cap) new_cap = min_capacity;
char[] new_data = new char[new_cap];
for (int i=0; i<size; ++i) new_data[i] = data[i];
data = new_data;
}
public StringBuilder append( String st )
{
int count = st.length();
ensureCapacity( size + count );
for (int i=0; i<count; ++i)
{
data[size++] = st.data[i];
}
return this;
}
public StringBuilder append( char ch )
{
ensureCapacity( size + 1 );
data[size++] = ch;
return this;
}
public StringBuilder reverse()
{
int i1=0, i2=size-1;
while (i1 < i2)
{
char temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
++i1;
--i2;
}
return this;
}
}
class PrintWriter
{
void print( boolean n ) { print( Boolean.toString(n) ); }
native void print( char ch );
void print( double n ) { print( Double.toString(n) ); }
void print( int n ) { print( Integer.toString(n) ); }
void print( long n ) { print( Long.toString(n) ); }
native void print( String st );
void println() { print('\n'); }
void println( boolean n ) { print(n); print('\n'); }
void println( char ch ) { print(ch); print('\n'); }
void println( double n ) { print(n); print('\n'); }
void println( int n ) { print(n); print('\n'); }
void println( long n ) { print(n); print('\n'); }
void println( String st ) { print(st); print('\n'); }
}
class Random
{
long seed;
Random()
{
this( System.currentTimeMillis() );
}
Random( long seed )
{
this.seed = seed;
}
int next( int bits )
{
seed = (seed * 0x5DEECE66DL + 11L) & ((1L << 48) - 1L);
return (int)(seed >>> (48 - bits));
}
boolean nextBoolean() { return next(1) == 1; }
void nextBytes( byte[] bytes )
{
for (int i=0; i<bytes.length; ++i) bytes[i] = (byte) next(8);
}
double nextDouble()
{
return (((long)next(26) << 27) + next(27)) / (double)(1L << 53);
}
float nextFloat()
{
return next(24) / ((float)(1 << 24));
}
/*
double next_next_gaussian;
boolean have_next_next_guassian;
public double nextGaussian()
{
clear the have next flag in setSeed()
if (have_next_next_guassian)
{
have_next_next_guassian = false;
return next_next_gaussian;
}
else
{
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
next_next_gaussian = v2 * multiplier;
have_next_next_guassian = true;
return v1 * multiplier;
}
}
*/
int nextInt() { return next(32); }
public int nextInt( int limit )
{
assert( limit > 0, "nextInt() parameter is non-positive." );
return (int)(nextDouble() * limit);
}
public long nextLong() { return ((long)next(32) << 32) + next(32); }
public void setSeed( long seed )
{
this.seed = seed;
}
}
class System
{
static PrintWriter out;
static
{
out = new PrintWriter();
}
native static long currentTimeMillis();
}
| 9,502 |
386 | /**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.qq.tars.support.om;
public interface OmConstants {
String PropWaitTime = "req.queue.waitingtime";
String PropHeapUsed = "jvm.memory.heap.used";
String PropHeapCommitted = "jvm.memory.heap.committed";
String PropHeapMax = "jvm.memory.heap.max";
String PropThreadCount = "jvm.thread.num";
String PropGcCount = "jvm.gc.num.";
String PropGcTime = "jvm.gc.time.";
String AdminServant = "AdminObj";
}
| 353 |
374 | <reponame>RonRahaman/nekRS<gh_stars>100-1000
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef hypre_THREADING_HEADER
#define hypre_THREADING_HEADER
#ifdef HYPRE_USING_OPENMP
HYPRE_Int hypre_NumThreads( void );
HYPRE_Int hypre_NumActiveThreads( void );
HYPRE_Int hypre_GetThreadNum( void );
void hypre_SetNumThreads(HYPRE_Int nt);
#else
#define hypre_NumThreads() 1
#define hypre_NumActiveThreads() 1
#define hypre_GetThreadNum() 0
#define hypre_SetNumThreads(x)
#endif
void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n );
#endif
| 288 |
788 | <filename>stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/AsyncEventQueueType.java
/*
* 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.usergrid.corepersistence.asyncevents;
public enum AsyncEventQueueType {
REGULAR ("regular"), UTILITY("utility"), DELETE("delete");
private String displayName;
AsyncEventQueueType(String displayName) {
this.displayName = displayName;
}
@Override
public String toString() {
return displayName;
}
}
| 365 |
335 | {
"word": "Vote",
"definitions": [
"A formal indication of a choice between two or more candidates or courses of action, expressed typically through a ballot or a show of hands.",
"An act of giving or registering a vote.",
"The choice expressed collectively by a body of electors or by a specified group.",
"The right to register a choice in an election."
],
"parts-of-speech": "Noun"
} | 139 |
571 | package camelinaction;
import javax.sql.DataSource;
import org.apache.camel.CamelContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class OrderCreateTable {
public OrderCreateTable(CamelContext camelContext) {
DataSource ds = camelContext.getRegistry().lookupByNameAndType("myDataSource", DataSource.class);
JdbcTemplate jdbc = new JdbcTemplate(ds);
try {
jdbc.execute("drop table riders_order");
} catch (Exception e) {
// ignore as the table may not already exists
}
jdbc.execute("create table riders_order "
+ "( customer_id varchar(10), ref_no varchar(10), part_id varchar(10), amount varchar(10) )");
}
}
| 295 |
3,227 | // Copyright (c) 2016 CNRS and LIRIS' Establishments (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME> <<EMAIL>>
//
#ifndef GMAP_TEST_INSERTIONS_H
#define GMAP_TEST_INSERTIONS_H
#include <CGAL/Generalized_map_operations.h>
template<typename GMAP>
bool check_number_of_cells_3(GMAP& gmap, unsigned int nbv, unsigned int nbe,
unsigned int nbf, unsigned int nbvol,
unsigned int nbcc);
template<typename GMAP>
bool test_vertex_insertion(GMAP& gmap)
{
typename GMAP::Dart_handle d1, d2, d3;
trace_test_begin();
d1 = gmap.create_dart();
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 2, 1, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.create_dart(); gmap.template sew<1>(d1, d1);
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 2, 1, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 3, 2, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
gmap.template sew<1>(d1, gmap.template alpha<0>(d1));
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
d2 = gmap.make_edge();
gmap.template sew<2>(d1, d2);
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 3, 2, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
d2 = gmap.make_edge();
gmap.template sew<2>(d1, d2);
gmap.template sew<1>(d1, gmap.template alpha<0>(d1));
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
d2 = gmap.make_edge();
gmap.template sew<2>(d1, d2);
gmap.template sew<1>(d1, gmap.template alpha<0>(d1));
gmap.template sew<1>(d2, gmap.template alpha<0>(d2));
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(3);
d2 = gmap.template alpha<0,1>(d1);
d3 = gmap.template alpha<1>(d1);
gmap.insert_cell_0_in_cell_1(d1);
gmap.insert_cell_0_in_cell_1(d2);
gmap.insert_cell_0_in_cell_1(d3);
if ( !check_number_of_cells_3(gmap, 6, 6, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(3);
d2 = gmap.make_combinatorial_polygon(3);
gmap.template sew<3>(d1, d2);
d2 = gmap.template alpha<0,1>(d1);
d3 = gmap.template alpha<1>(d1);
gmap.insert_cell_0_in_cell_1(d1);
gmap.insert_cell_0_in_cell_1(d2);
gmap.insert_cell_0_in_cell_1(d3);
if ( !check_number_of_cells_3(gmap, 6, 6, 1, 2, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(3);
d2 = gmap.make_combinatorial_polygon(3);
gmap.template sew<2>(d1, d2);
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 5, 6, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(3);
d2 = gmap.make_combinatorial_polygon(3);
gmap.template sew<2>(d1, d2);
gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1>(d1));
gmap.insert_cell_0_in_cell_1(gmap.template alpha<1>(d1));
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 7, 8, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_hexahedron();
d2 = gmap.make_combinatorial_hexahedron();
gmap.template sew<3>(d1, d2);
gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1,0,1>(d1));
gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1>(d1));
gmap.insert_cell_0_in_cell_1(gmap.template alpha<1>(d1));
gmap.insert_cell_0_in_cell_1(d1);
if ( !check_number_of_cells_3(gmap, 16, 24, 11, 2, 1) )
return false;
gmap.clear();
return true;
}
template<typename GMAP>
bool test_edge_insertion(GMAP& gmap)
{
typename GMAP::Dart_handle d1, d2, d3;
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0));
if ( !check_number_of_cells_3(gmap, 4, 5, 2, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
d2 = gmap.make_combinatorial_polygon(4);
gmap.template sew<3>(d1, d2);
gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0));
if ( !check_number_of_cells_3(gmap, 4, 5, 2, 2, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
d2 = gmap.make_combinatorial_polygon(4);
gmap.template sew<2>(d1, d2);
gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0));
if ( !check_number_of_cells_3(gmap, 6, 8, 3, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.create_dart();
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
gmap.template sew<1>(d1, gmap.alpha(d1, 0));
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_edge();
d2 = gmap.make_edge();
gmap.template sew<3>(d1, d2);
gmap.template sew<1>(d1, gmap.alpha(d1, 0));
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 2, 2, 1, 2, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 5, 5, 1, 1, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
d2 = gmap.make_combinatorial_polygon(4);
gmap.template sew<3>(d1, d2);
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 5, 5, 1, 2, 1) )
return false;
gmap.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
d2 = gmap.make_combinatorial_polygon(4);
gmap.template sew<2>(d1, d2);
gmap.insert_dangling_cell_1_in_cell_2(d1);
if ( !check_number_of_cells_3(gmap, 7, 8, 2, 1, 1) )
return false;
gmap.clear();
return true;
}
template<typename GMAP>
bool test_face_insertion(GMAP& gmap)
{
typename GMAP::Dart_handle d1, d2, d3;
std::vector<typename GMAP::Dart_handle> v;
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(4);
v.push_back(d1);
v.push_back(gmap.alpha(v[0],0,1));
v.push_back(gmap.alpha(v[1],0,1));
v.push_back(gmap.alpha(v[2],0,1));
gmap.insert_cell_2_in_cell_3(v.begin(),v.end());
if ( !check_number_of_cells_3(gmap, 4, 4, 2, 1, 1) )
return false;
gmap.clear(); v.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_polygon(3);
d2 = gmap.make_combinatorial_polygon(3);
gmap.template sew<2>(d1, d2);
v.push_back(d1);
v.push_back(gmap.alpha(v[0],0,1));
v.push_back(gmap.alpha(v[1],0,1));
gmap.insert_cell_2_in_cell_3(v.begin(),v.end());
if ( !check_number_of_cells_3(gmap, 4, 5, 3, 2, 1) )
return false;
gmap.clear(); v.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_hexahedron();
d2 = gmap.alpha(d1,2);
v.push_back(d2);
v.push_back(gmap.alpha(v[0],0,1,2,1));
v.push_back(gmap.alpha(v[1],0,1,2,1));
v.push_back(gmap.alpha(v[2],0,1,2,1));
gmap.insert_cell_2_in_cell_3(v.begin(),v.end());
if ( !check_number_of_cells_3(gmap, 8, 12, 7, 2, 1) )
return false;
gmap.clear(); v.clear();
trace_test_begin();
d1 = gmap.make_combinatorial_hexahedron();
d2 = gmap.make_combinatorial_hexahedron();
gmap.template sew<3>(d1,d2);
d3 = gmap.alpha(d1, 2);
gmap.template remove_cell<2>(d1);
v.push_back(d3);
v.push_back(gmap.alpha(v[0],0,1,2,1));
v.push_back(gmap.alpha(v[1],0,1,2,1));
v.push_back(gmap.alpha(v[2],0,1,2,1));
gmap.insert_cell_2_in_cell_3(v.begin(),v.end());
if ( !check_number_of_cells_3(gmap, 12, 20, 11, 2, 1) )
return false;
GMAP gmap2;
d1 = gmap2.make_combinatorial_hexahedron();
d2 = gmap2.make_combinatorial_hexahedron();
gmap2.template sew<3>(d1,d2);
if ( !gmap.is_isomorphic_to(gmap2, false, false, false) )
{
std::cout<<"Error: gmap and gmap2 are not isomorphic (after insertion/removal).\n";
assert(false);
return false;
}
if (CGAL::degree<GMAP, 0>(gmap2, d1)!=4)
{
std::cout<<"Error: 0-degree is wrong: "<<CGAL::degree<GMAP, 0>(gmap2, d1)<<" instead of 4."<<std::endl;
assert(false);
return false;
}
if (CGAL::degree<GMAP, 1>(gmap2, d1)!=3)
{
std::cout<<"Error: 1-degree is wrong: "<<CGAL::degree<GMAP, 1>(gmap2, d1)<<" instead of 3."<<std::endl;
assert(false);
return false;
}
if (CGAL::degree<GMAP, 2>(gmap2, d1)!=2)
{
std::cout<<"Error: 2-degree is wrong: "<<CGAL::degree<GMAP, 2>(gmap2, d1)<<" instead of 2."<<std::endl;
assert(false);
return false;
}
if (CGAL::codegree<GMAP, 1>(gmap2, d1)!=2)
{
std::cout<<"Error: 1-codegree is wrong: "<<CGAL::codegree<GMAP, 1>(gmap2, d1)<<" instead of 2."<<std::endl;
assert(false);
return false;
}
if (CGAL::codegree<GMAP, 2>(gmap2, d1)!=4)
{
std::cout<<"Error: 2-codegree is wrong: "<<CGAL::codegree<GMAP, 2>(gmap2, d1)<<" instead of 4."<<std::endl;
assert(false);
return false;
}
if (CGAL::codegree<GMAP, 3>(gmap2, d1)!=6)
{
std::cout<<"Error: 3-codegree is wrong: "<<CGAL::codegree<GMAP, 3>(gmap2, d1)<<" instead of 6."<<std::endl;
assert(false);
return false;
}
gmap.clear(); v.clear();
return true;
}
#endif // GMAP_TEST_INSERTIONS_H
| 4,729 |
1,338 | <gh_stars>1000+
/*
* Copyright 2010, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
/*
* Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
* Copyright (c) 1996-1999 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <net_datalink.h>
#include <ByteOrder.h>
#include <KernelExport.h>
#include <NetUtilities.h>
#include <memory.h>
#include <netinet6/in6.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ipv6_utils.h"
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
#define SPRINTF(x) ((size_t)sprintf x)
/*! Convert IPv6 binary address into presentation (printable) format.
Author: <NAME>, 1996.
\return pointer to dst string if address as been printed
\return NULL if the buffer is too short
*/
const char *
ip6_sprintf(const in6_addr *srcaddr, char *dst, size_t size)
{
/*
* Note that int32_t and int16_t need only be "at least" large enough
* to contain a value of the specified size. On some systems, like
* Crays, there is no such thing as an integer variable with 16 bits.
* Keep this in mind if you think this function should have been coded
* to use pointer overlays. All the world's not a VAX.
*/
char tmp[INET6_ADDRSTRLEN], *tp;
struct { int base, len; } best, cur;
uint16 words[NS_IN6ADDRSZ / NS_INT16SZ];
int i;
const uint8 *src = srcaddr->s6_addr;
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
memset(words, '\0', sizeof words);
for (i = 0; i < NS_IN6ADDRSZ; i++)
words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
best.base = -1;
best.len = 0;
cur.base = -1;
cur.len = 0;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
if (words[i] == 0) {
if (cur.base == -1)
cur.base = i, cur.len = 1;
else
cur.len++;
} else {
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
cur.base = -1;
}
}
}
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
}
if (best.base != -1 && best.len < 2)
best.base = -1;
/*
* Format the result.
*/
tp = tmp;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base &&
i < (best.base + best.len)) {
if (i == best.base)
*tp++ = ':';
continue;
}
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0)
*tp++ = ':';
/* Is this address an encapsulated IPv4? */
#if 0
if (i == 6 && best.base == 0 && (best.len == 6 ||
(best.len == 7 && words[7] != 0x0001) ||
(best.len == 5 && words[5] == 0xffff))) {
if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp)))
return (NULL);
tp += strlen(tp);
break;
}
#endif
tp += SPRINTF((tp, "%x", words[i]));
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) ==
(NS_IN6ADDRSZ / NS_INT16SZ))
*tp++ = ':';
*tp++ = '\0';
/*
* Check for overflow, copy, and we're done.
*/
if ((size_t)(tp - tmp) > size)
return NULL;
strcpy(dst, tmp);
return dst;
}
| 1,534 |
701 | """
Classes from the 'DocumentCamera' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
ICDocCamScanCache = _Class("ICDocCamScanCache")
ICDocCamScanCacheItem = _Class("ICDocCamScanCacheItem")
ICDocCamRenamePrompt = _Class("ICDocCamRenamePrompt")
ICDocCamRectangleResultsQueue = _Class("ICDocCamRectangleResultsQueue")
DCPDFGenerator = _Class("DCPDFGenerator")
ICDocCamRetakeTransitionAnimator = _Class("ICDocCamRetakeTransitionAnimator")
ICDocCamUtilities = _Class("ICDocCamUtilities")
ICDocCamThumbnailZoomTransitionAnimator = _Class(
"ICDocCamThumbnailZoomTransitionAnimator"
)
DCLocalization = _Class("DCLocalization")
ZhangHeFilter = _Class("ZhangHeFilter")
DCNotesSPI = _Class("DCNotesSPI")
ICDocCamDebugMovieController = _Class("ICDocCamDebugMovieController")
DCMarkupUtilities = _Class("DCMarkupUtilities")
ICDocCamProcessingBlocker = _Class("ICDocCamProcessingBlocker")
ICDocCamImageCache = _Class("ICDocCamImageCache")
ICDocCamDocumentInfoCollection = _Class("ICDocCamDocumentInfoCollection")
ICDocCamDocumentInfo = _Class("ICDocCamDocumentInfo")
DCAccessibility = _Class("DCAccessibility")
DCColorDummyClass = _Class("DCColorDummyClass")
ICDocCamViewControllerMeshTransform = _Class("ICDocCamViewControllerMeshTransform")
VNDocumentCameraScan = _Class("VNDocumentCameraScan")
DCLRUCache = _Class("DCLRUCache")
DCAtomicLRUCache = _Class("DCAtomicLRUCache")
DCCachesDirectory = _Class("DCCachesDirectory")
DCActivityItemSource = _Class("DCActivityItemSource")
DCDocumentInfoCollectionActivityItemSource = _Class(
"DCDocumentInfoCollectionActivityItemSource"
)
DCMarkupActivityItem = _Class("DCMarkupActivityItem")
DCDispatchAfterHandler = _Class("DCDispatchAfterHandler")
DCDispatchAfterBlocks = _Class("DCDispatchAfterBlocks")
ICDocCamCVPixelBufferUtilities = _Class("ICDocCamCVPixelBufferUtilities")
DCScannedDocument = _Class("DCScannedDocument")
ICDocCamImageQuad = _Class("ICDocCamImageQuad")
ICDocCamImageFilters = _Class("ICDocCamImageFilters")
ICDocCamSpinner = _Class("ICDocCamSpinner")
DCLongRunningTaskController = _Class("DCLongRunningTaskController")
DCDocumentCameraViewServiceSessionRequest = _Class(
"DCDocumentCameraViewServiceSessionRequest"
)
DCUtilities = _Class("DCUtilities")
DCDocumentCameraViewServiceSession = _Class("DCDocumentCameraViewServiceSession")
ICDocCamPhotoCaptureDelegate = _Class("ICDocCamPhotoCaptureDelegate")
DCSandboxExtension = _Class("DCSandboxExtension")
DCMarkupPresenter = _Class("DCMarkupPresenter")
ICDocCamImageSequenceAnalyzer = _Class("ICDocCamImageSequenceAnalyzer")
ICDocCamImageSequenceFrame = _Class("ICDocCamImageSequenceFrame")
ICDocCamPhysicalCaptureNotifier = _Class("ICDocCamPhysicalCaptureNotifier")
DCDocCamPDFGenerator = _Class("DCDocCamPDFGenerator")
ICDocCamRecropTransitionAnimator = _Class("ICDocCamRecropTransitionAnimator")
DCSelectorDelayer = _Class("DCSelectorDelayer")
DCSettings = _Class("DCSettings")
WhiteboardFilter = _Class("WhiteboardFilter")
ICDocCamThumbnailViewLayoutAttributes = _Class("ICDocCamThumbnailViewLayoutAttributes")
ICDocCamThumbnailCollectionViewLayout = _Class("ICDocCamThumbnailCollectionViewLayout")
ICDocCamReorderingThumbnailCollectionViewLayout = _Class(
"ICDocCamReorderingThumbnailCollectionViewLayout"
)
DCMarkupActivity = _Class("DCMarkupActivity")
ICDocCamPhysicalCaptureRecognizer = _Class("ICDocCamPhysicalCaptureRecognizer")
ICDocCamImageQuadEditPanGestureRecognizer = _Class(
"ICDocCamImageQuadEditPanGestureRecognizer"
)
ICDocCamImageQuadEditKnobAccessibilityElement = _Class(
"ICDocCamImageQuadEditKnobAccessibilityElement"
)
ICDocCamImageQuadEditOverlay = _Class("ICDocCamImageQuadEditOverlay")
ICDocCamThumbnailContainerView = _Class("ICDocCamThumbnailContainerView")
ICDocCamImageQuadEditImageView = _Class("ICDocCamImageQuadEditImageView")
DCCircularProgressView = _Class("DCCircularProgressView")
ICDocCamOverlayView = _Class("ICDocCamOverlayView")
ICDocCamExtractedThumbnailContainerView = _Class(
"ICDocCamExtractedThumbnailContainerView"
)
DCNotesTextureBackgroundView = _Class("DCNotesTextureBackgroundView")
DCNotesTextureView = _Class("DCNotesTextureView")
ICDocCamFilterViewControllerInvisibleRootView = _Class(
"ICDocCamFilterViewControllerInvisibleRootView"
)
ICDocCamPreviewView = _Class("ICDocCamPreviewView")
DCSinglePixelLineView = _Class("DCSinglePixelLineView")
DCSinglePixelVerticalLineView = _Class("DCSinglePixelVerticalLineView")
DCSinglePixelHorizontalLineView = _Class("DCSinglePixelHorizontalLineView")
ICDocCamThumbnailDecorationView = _Class("ICDocCamThumbnailDecorationView")
ICDocCamExtractedDocumentThumbnailCell = _Class(
"ICDocCamExtractedDocumentThumbnailCell"
)
ICDocCamThumbnailCell = _Class("ICDocCamThumbnailCell")
ICDocCamZoomablePageContentImageView = _Class("ICDocCamZoomablePageContentImageView")
ICDocCamSaveButton = _Class("ICDocCamSaveButton")
ICDocCamFilterButton = _Class("ICDocCamFilterButton")
ICDocCamShutterButton = _Class("ICDocCamShutterButton")
DCProgressViewController = _Class("DCProgressViewController")
ICDocCamNonRotatableViewController = _Class("ICDocCamNonRotatableViewController")
ICDocCamViewController = _Class("ICDocCamViewController")
DCDocumentCameraViewController = _Class("DCDocumentCameraViewController")
DCDocumentCameraViewController_ViewService = _Class(
"DCDocumentCameraViewController_ViewService"
)
DCDocumentCameraViewController_InProcess = _Class(
"DCDocumentCameraViewController_InProcess"
)
ICDocCamImageQuadEditViewController = _Class("ICDocCamImageQuadEditViewController")
ICDocCamFilterViewController = _Class("ICDocCamFilterViewController")
VNDocumentCameraViewController = _Class("VNDocumentCameraViewController")
VNDocumentCameraViewController_InProcess = _Class(
"VNDocumentCameraViewController_InProcess"
)
VNDocumentCameraViewController_ViewService = _Class(
"VNDocumentCameraViewController_ViewService"
)
ICDocCamZoomablePageContentViewController = _Class(
"ICDocCamZoomablePageContentViewController"
)
ICDocCamPageContentViewController = _Class("ICDocCamPageContentViewController")
ICDocCamExtractedDocumentViewController = _Class(
"ICDocCamExtractedDocumentViewController"
)
DCActivityViewController = _Class("DCActivityViewController")
DCDocumentCameraRemoteViewController = _Class("DCDocumentCameraRemoteViewController")
ICDocCamThumbnailCollectionViewController = _Class(
"ICDocCamThumbnailCollectionViewController"
)
ICDocCamNavigationController = _Class("ICDocCamNavigationController")
DCDocumentEditorViewController = _Class("DCDocumentEditorViewController")
ICDocCamExtractedDocumentNavigationController = _Class(
"ICDocCamExtractedDocumentNavigationController"
)
| 2,038 |
308 | # PACKAGE IMPORTS FOR EXTERNAL USAGE
from tests.integration_tests.s3_dataset_test import TestDataset
from tests.integration_tests.ema_train_integration_test import EMAIntegrationTest
from tests.integration_tests.lr_test import LRTest
_all__ = [TestDataset, EMAIntegrationTest, LRTest]
| 96 |
5,766 | //
// DynamicDateTime.h
//
// Library: Data
// Package: DataCore
// Module: DynamicDateTime
//
// Definition of the Date and Time cast operators for Poco::Dynamic::Var.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_DynamicDateTime_INCLUDED
#define Data_DynamicDateTime_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Date.h"
#include "Poco/Data/Time.h"
#include "Poco/Dynamic/Var.h"
namespace Poco {
namespace Data {
class Date;
class Time;
} } // namespace Poco::Data
namespace Poco {
namespace Dynamic {
template <> Data_API Var::operator Poco::Data::Date () const;
template <> Data_API Var::operator Poco::Data::Time () const;
} } // namespace Poco::Dynamic
#endif // Data_DynamicDateTime_INCLUDED
| 283 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-mcf5-43h4-p6vc",
"modified": "2022-05-13T01:41:45Z",
"published": "2022-05-13T01:41:45Z",
"aliases": [
"CVE-2017-10278"
],
"details": "Vulnerability in the Oracle Tuxedo component of Oracle Fusion Middleware (subcomponent: Security). Supported versions that are affected are 11.1.1, 12.1.1, 12.1.3 and 12.2.2. Difficult to exploit vulnerability allows unauthenticated attacker with network access via Jolt to compromise Oracle Tuxedo. Successful attacks of this vulnerability can result in unauthorized access to critical data or complete access to all Oracle Tuxedo accessible data as well as unauthorized update, insert or delete access to some of Oracle Tuxedo accessible data and unauthorized ability to cause a partial denial of service (partial DOS) of Oracle Tuxedo. CVSS 3.0 Base Score 7.0 (Confidentiality, Integrity and Availability impacts). CVSS Vector: (CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:L/A:L).",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:L/A:L"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-10278"
},
{
"type": "WEB",
"url": "http://www.oracle.com/technetwork/security-advisory/alert-cve-2017-10269-4021872.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/101870"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 633 |
593 | #if defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif
// 24 x 24 gridicons_external
const unsigned char gridicons_external[] PROGMEM = { /* 0X01,0X01,0XB4,0X00,0X40,0X00, */
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xE0, 0x1F, 0xFF, 0xE0, 0x1F, 0xFF, 0xE1,
0xF8, 0x0F, 0xE0, 0xF8, 0x07, 0xE4, 0x7F, 0xE7,
0xE6, 0x3F, 0xE7, 0xE7, 0x1F, 0xE7, 0xE7, 0x8F,
0xE7, 0xFF, 0xC7, 0xE7, 0xFF, 0xE3, 0xE7, 0xF9,
0xF7, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7,
0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF,
0xE7, 0xF8, 0x00, 0x07, 0xFC, 0x00, 0x0F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
| 459 |
1,033 | <filename>graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/autoconfigure/tools/Query.java<gh_stars>1000+
package graphql.kickstart.autoconfigure.tools;
import graphql.kickstart.tools.GraphQLQueryResolver;
/** @author <NAME> */
public class Query implements GraphQLQueryResolver {
public String echo(String string) {
return string;
}
}
| 116 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h>
#include <EMotionFX/CommandSystem/Source/CommandManager.h>
#include <EMotionFX/Source/AnimGraphNodeGroup.h>
#include <Tests/AnimGraphFixture.h>
namespace EMotionFX
{
TEST_F(AnimGraphFixture, AnimGraphAddMassNodeGroupTests)
{
CommandSystem::CommandManager commandManager;
MCore::CommandGroup commandGroup("Add anim graph node groups");
AZStd::string result;
AZStd::string commandString;
for (AZ::u32 i = 0; i < 100; ++i)
{
commandString = AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"NodeGroup%s\"", m_animGraph->GetID(), AZStd::to_string(i).c_str());
commandGroup.AddCommandString(commandString);
}
EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommandGroup(commandGroup, result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 100);
EXPECT_TRUE(CommandSystem::GetCommandManager()->Undo(result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 0);
EXPECT_TRUE(CommandSystem::GetCommandManager()->Redo(result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 100);
}
TEST_F(AnimGraphFixture, AnimGraphRemoveMassNodeGroupTests)
{
AZStd::string nodeGroupName;
for (AZ::u32 i = 0; i < 100; ++i)
{
EMotionFX::AnimGraphNodeGroup* nodeGroup = aznew AnimGraphNodeGroup();
nodeGroupName = AZStd::string::format("NodeGroup%s", AZStd::to_string(i).c_str());
nodeGroup->SetName(nodeGroupName.c_str());
m_animGraph->AddNodeGroup(nodeGroup);
}
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 100);
CommandSystem::CommandManager commandManager;
MCore::CommandGroup commandGroup("Remove anim graph node groups");
AZStd::string result;
AZStd::string commandString;
for (AZ::u32 i = 0; i < 100; ++i)
{
commandString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"NodeGroup%s\"", m_animGraph->GetID(), AZStd::to_string(i).c_str());
commandGroup.AddCommandString(commandString);
}
EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommandGroup(commandGroup, result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 0);
EXPECT_TRUE(CommandSystem::GetCommandManager()->Undo(result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 100);
EXPECT_TRUE(CommandSystem::GetCommandManager()->Redo(result));
EXPECT_EQ(m_animGraph->GetNumNodeGroups(), 0);
}
} // namespace EMotionFX
| 1,230 |
2,151 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/signin/unified_consent_helper.h"
#include "build/buildflag.h"
#include "chrome/test/base/testing_profile.h"
#include "components/signin/core/browser/scoped_account_consistency.h"
#include "components/signin/core/browser/scoped_unified_consent.h"
#include "components/signin/core/browser/signin_buildflags.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// On Dice platforms, unified consent can only be enabled for Dice profiles.
TEST(UnifiedConsentHelperTest, DiceDisabled) {
// Disable Dice.
signin::ScopedAccountConsistencyDiceFixAuthErrors dice_fix_auth_errors;
content::TestBrowserThreadBundle thread_bundle;
TestingProfile profile;
for (signin::UnifiedConsentFeatureState state :
{signin::UnifiedConsentFeatureState::kDisabled,
signin::UnifiedConsentFeatureState::kEnabledNoBump,
signin::UnifiedConsentFeatureState::kEnabledWithBump}) {
signin::ScopedUnifiedConsent scoped_state(state);
EXPECT_EQ(signin::UnifiedConsentFeatureState::kDisabled,
GetUnifiedConsentFeatureState(&profile));
EXPECT_FALSE(IsUnifiedConsentEnabled(&profile));
EXPECT_FALSE(IsUnifiedConsentBumpEnabled(&profile));
}
}
#endif
// Checks that the feature state for the profile is the same as the global
// feature state.
TEST(UnifiedConsentHelperTest, FeatureState) {
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Enable Dice.
signin::ScopedAccountConsistencyDice dice;
#endif
content::TestBrowserThreadBundle thread_bundle;
TestingProfile profile;
// Unified consent is disabled by default.
EXPECT_EQ(signin::UnifiedConsentFeatureState::kDisabled,
GetUnifiedConsentFeatureState(&profile));
// The feature state for the profile is the same as the global feature state.
{
signin::ScopedUnifiedConsent scoped_disabled(
signin::UnifiedConsentFeatureState::kDisabled);
EXPECT_EQ(signin::UnifiedConsentFeatureState::kDisabled,
GetUnifiedConsentFeatureState(&profile));
EXPECT_FALSE(IsUnifiedConsentEnabled(&profile));
EXPECT_FALSE(IsUnifiedConsentBumpEnabled(&profile));
}
{
signin::ScopedUnifiedConsent scoped_no_bump(
signin::UnifiedConsentFeatureState::kEnabledNoBump);
EXPECT_EQ(signin::UnifiedConsentFeatureState::kEnabledNoBump,
GetUnifiedConsentFeatureState(&profile));
EXPECT_TRUE(IsUnifiedConsentEnabled(&profile));
EXPECT_FALSE(IsUnifiedConsentBumpEnabled(&profile));
}
{
signin::ScopedUnifiedConsent scoped_bump(
signin::UnifiedConsentFeatureState::kEnabledWithBump);
EXPECT_EQ(signin::UnifiedConsentFeatureState::kEnabledWithBump,
GetUnifiedConsentFeatureState(&profile));
EXPECT_TRUE(IsUnifiedConsentEnabled(&profile));
EXPECT_TRUE(IsUnifiedConsentBumpEnabled(&profile));
}
}
| 1,093 |
583 | #include "validate_node.hpp"
#include <string>
namespace opossum {
ValidateNode::ValidateNode() : AbstractLQPNode(LQPNodeType::Validate) {}
std::string ValidateNode::description(const DescriptionMode mode) const { return "[Validate]"; }
std::shared_ptr<LQPUniqueConstraints> ValidateNode::unique_constraints() const {
return _forward_left_unique_constraints();
}
std::shared_ptr<AbstractLQPNode> ValidateNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const {
return ValidateNode::make();
}
bool ValidateNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const {
return true;
}
} // namespace opossum
| 231 |
13,566 | package com.external.connections;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
// Parent type for all API connections that need to be created during datasource create method.
public abstract class APIConnection implements ExchangeFilterFunction {
} | 66 |
4,262 | <reponame>rikvb/camel
/*
* 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.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.ganglia.GangliaComponent;
/**
* Send metrics to Ganglia monitoring system.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface GangliaComponentBuilderFactory {
/**
* Ganglia (camel-ganglia)
* Send metrics to Ganglia monitoring system.
*
* Category: monitoring
* Since: 2.15
* Maven coordinates: org.apache.camel:camel-ganglia
*
* @return the dsl builder
*/
static GangliaComponentBuilder ganglia() {
return new GangliaComponentBuilderImpl();
}
/**
* Builder for the Ganglia component.
*/
interface GangliaComponentBuilder
extends
ComponentBuilder<GangliaComponent> {
/**
* Minumum time in seconds before Ganglia will purge the metric value if
* it expires. Set to 0 and the value will remain in Ganglia
* indefinitely until a gmond agent restart.
*
* The option is a: <code>int</code> type.
*
* Default: 0
* Group: producer
*
* @param dmax the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder dmax(int dmax) {
doSetProperty("dmax", dmax);
return this;
}
/**
* The group that the metric belongs to.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: java
* Group: producer
*
* @param groupName the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder groupName(java.lang.String groupName) {
doSetProperty("groupName", groupName);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The name to use for the metric.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: metric
* Group: producer
*
* @param metricName the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder metricName(java.lang.String metricName) {
doSetProperty("metricName", metricName);
return this;
}
/**
* Send the UDP metric packets using MULTICAST or UNICAST.
*
* The option is a:
* <code>info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode</code> type.
*
* Default: MULTICAST
* Group: producer
*
* @param mode the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder mode(
info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode mode) {
doSetProperty("mode", mode);
return this;
}
/**
* Prefix the metric name with this string and an underscore.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param prefix the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder prefix(java.lang.String prefix) {
doSetProperty("prefix", prefix);
return this;
}
/**
* The slope.
*
* The option is a:
* <code>info.ganglia.gmetric4j.gmetric.GMetricSlope</code>
* type.
*
* Default: BOTH
* Group: producer
*
* @param slope the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder slope(
info.ganglia.gmetric4j.gmetric.GMetricSlope slope) {
doSetProperty("slope", slope);
return this;
}
/**
* Spoofing information IP:hostname.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param spoofHostname the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder spoofHostname(
java.lang.String spoofHostname) {
doSetProperty("spoofHostname", spoofHostname);
return this;
}
/**
* Maximum time in seconds that the value can be considered current.
* After this, Ganglia considers the value to have expired.
*
* The option is a: <code>int</code> type.
*
* Default: 60
* Group: producer
*
* @param tmax the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder tmax(int tmax) {
doSetProperty("tmax", tmax);
return this;
}
/**
* If using multicast, set the TTL of the packets.
*
* The option is a: <code>int</code> type.
*
* Default: 5
* Group: producer
*
* @param ttl the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder ttl(int ttl) {
doSetProperty("ttl", ttl);
return this;
}
/**
* The type of value.
*
* The option is a:
* <code>info.ganglia.gmetric4j.gmetric.GMetricType</code>
* type.
*
* Default: STRING
* Group: producer
*
* @param type the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder type(
info.ganglia.gmetric4j.gmetric.GMetricType type) {
doSetProperty("type", type);
return this;
}
/**
* Any unit of measurement that qualifies the metric, e.g. widgets,
* litres, bytes. Do not include a prefix such as k (kilo) or m (milli),
* other tools may scale the units later. The value should be unscaled.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param units the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder units(java.lang.String units) {
doSetProperty("units", units);
return this;
}
/**
* Use the wire format of Ganglia 3.1.0 and later versions. Set this to
* false to use Ganglia 3.0.x or earlier.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param wireFormat31x the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder wireFormat31x(boolean wireFormat31x) {
doSetProperty("wireFormat31x", wireFormat31x);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* To use the shared configuration.
*
* The option is a:
* <code>org.apache.camel.component.ganglia.GangliaConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default GangliaComponentBuilder configuration(
org.apache.camel.component.ganglia.GangliaConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
}
class GangliaComponentBuilderImpl
extends
AbstractComponentBuilder<GangliaComponent>
implements
GangliaComponentBuilder {
@Override
protected GangliaComponent buildConcreteComponent() {
return new GangliaComponent();
}
private org.apache.camel.component.ganglia.GangliaConfiguration getOrCreateConfiguration(
org.apache.camel.component.ganglia.GangliaComponent component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.ganglia.GangliaConfiguration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "dmax": getOrCreateConfiguration((GangliaComponent) component).setDmax((int) value); return true;
case "groupName": getOrCreateConfiguration((GangliaComponent) component).setGroupName((java.lang.String) value); return true;
case "lazyStartProducer": ((GangliaComponent) component).setLazyStartProducer((boolean) value); return true;
case "metricName": getOrCreateConfiguration((GangliaComponent) component).setMetricName((java.lang.String) value); return true;
case "mode": getOrCreateConfiguration((GangliaComponent) component).setMode((info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode) value); return true;
case "prefix": getOrCreateConfiguration((GangliaComponent) component).setPrefix((java.lang.String) value); return true;
case "slope": getOrCreateConfiguration((GangliaComponent) component).setSlope((info.ganglia.gmetric4j.gmetric.GMetricSlope) value); return true;
case "spoofHostname": getOrCreateConfiguration((GangliaComponent) component).setSpoofHostname((java.lang.String) value); return true;
case "tmax": getOrCreateConfiguration((GangliaComponent) component).setTmax((int) value); return true;
case "ttl": getOrCreateConfiguration((GangliaComponent) component).setTtl((int) value); return true;
case "type": getOrCreateConfiguration((GangliaComponent) component).setType((info.ganglia.gmetric4j.gmetric.GMetricType) value); return true;
case "units": getOrCreateConfiguration((GangliaComponent) component).setUnits((java.lang.String) value); return true;
case "wireFormat31x": getOrCreateConfiguration((GangliaComponent) component).setWireFormat31x((boolean) value); return true;
case "autowiredEnabled": ((GangliaComponent) component).setAutowiredEnabled((boolean) value); return true;
case "configuration": ((GangliaComponent) component).setConfiguration((org.apache.camel.component.ganglia.GangliaConfiguration) value); return true;
default: return false;
}
}
}
} | 5,984 |
892 | <filename>advisories/unreviewed/2022/05/GHSA-9q2j-c74h-2vcr/GHSA-9q2j-c74h-2vcr.json
{
"schema_version": "1.2.0",
"id": "GHSA-9q2j-c74h-2vcr",
"modified": "2022-05-02T06:14:48Z",
"published": "2022-05-02T06:14:48Z",
"aliases": [
"CVE-2010-0698"
],
"details": "SQL injection vulnerability in backoffice/login.asp in Dynamicsoft WSC CMS 2.2 allows remote attackers to execute arbitrary SQL commands via the Password parameter. NOTE: some of these details are obtained from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0698"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/56406"
},
{
"type": "WEB",
"url": "http://packetstormsecurity.org/1002-exploits/wsccms-sql.txt"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/38698"
},
{
"type": "WEB",
"url": "http://www.exploit-db.com/exploits/11507"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/38335"
}
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 606 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "Ra.Stdafx.h"
using namespace std;
using namespace Common;
using namespace Reliability::ReconfigurationAgentComponent;
::FABRIC_SERVICE_PARTITION_ACCESS_STATUS AccessStatus::ConvertToPublicAccessStatus(AccessStatus::Enum toConvert)
{
switch(toConvert)
{
case AccessStatus::TryAgain:
return FABRIC_SERVICE_PARTITION_ACCESS_STATUS_RECONFIGURATION_PENDING;
case AccessStatus::NotPrimary:
return FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY;
case AccessStatus::NoWriteQuorum:
return FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NO_WRITE_QUORUM;
case AccessStatus::Granted:
return FABRIC_SERVICE_PARTITION_ACCESS_STATUS_GRANTED;
default:
Common::Assert::CodingError("Unknown Access Status");
}
}
namespace Reliability
{
namespace ReconfigurationAgentComponent
{
namespace AccessStatus
{
void AccessStatus::WriteToTextWriter(TextWriter & w, AccessStatus::Enum const & val)
{
w << ToString(val);
}
ENUM_STRUCTURED_TRACE(AccessStatus, TryAgain, LastValidEnum);
}
}
}
wstring AccessStatus::ToString(AccessStatus::Enum accessStatus)
{
switch (accessStatus)
{
case TryAgain:
return L"TryAgain";
case NotPrimary:
return L"NotPrimary";
case NoWriteQuorum:
return L"NoWriteQuorum";
case Granted:
return L"Granted";
default:
Common::Assert::CodingError("Unknown Access Status");
}
}
| 768 |
5,169 | <filename>Specs/CrystalExpressSDK-CN/1.8.1/CrystalExpressSDK-CN.podspec.json
{
"name": "CrystalExpressSDK-CN",
"version": "1.8.1",
"summary": "SDK library for Crystal Express Ad China.",
"homepage": "http://demo.intowow.com/",
"license": {
"type": "Copyright",
"text": " Copyright (c) 2015 Intowow. All rights reserved.\n\n"
},
"authors": {
"intowow Co., Ltd": "http://www.intowow.com/"
},
"source": {
"http": "https://s3.cn-north-1.amazonaws.com.cn/intowow-sdk/ios/cocoapods/cn/libCrystalExpressSDK-CN-1.8.1.zip"
},
"platforms": {
"ios": "7.0"
},
"vendored_libraries": "libCrystalExpressSDK-CN-1.8.1.a",
"preserve_paths": "libCrystalExpressSDK-CN-1.8.1.a",
"source_files": "Sources/*.{h,m}",
"public_header_files": "Sources/*.h",
"resources": "Resources/*",
"dependencies": {
"AFNetworking": [
"~> 2.3"
],
"AFDownloadRequestOperation": [
],
"SocketRocket": [
],
"SSZipArchive": [
],
"NJKWebViewProgress": [
],
"MTStatusBarOverlay": [
"~> 0.9"
],
"Reachability": [
]
},
"libraries": [
"sqlite3",
"c++",
"z"
],
"frameworks": [
"AdSupport",
"AVFoundation",
"CFNetwork",
"CoreMedia",
"CoreTelephony",
"MessageUI",
"MobileCoreServices",
"SystemConfiguration",
"CoreLocation"
]
}
| 638 |
2,251 | <reponame>hjred/stride
#ifndef setjmp_h
#define setjmp_h
#include "../NativePath.h"
#undef jmp_buf
//we oversize our jmp_buf for safety
typedef void* jmp_buf[64];
#endif | 78 |
1,645 | import os
import sys, getopt, argparse
import logging
from random import randint,random,uniform
import json
import urllib
PREDICT_TEMPLATE = 'http://%ENDPOINT%/js/predict?json=%JSON%&consumer_key=%KEY%&jsonpCallback=j'
class ReplayCreate(object):
def __init__(self):
self.features = []
def get_key(self,filename):
with open(filename) as f:
for line in f:
line = line.rstrip()
j = json.loads(line)
self.key = j[0]["key"]
def parse_features(self,features):
for f in features:
j = json.loads(f)
self.features.append(j)
def construct_json(self):
j = {}
for f in self.features:
if f["type"] == "numeric":
fval = uniform(f["min"],f["max"])
j[f["name"]] = fval
return json.dumps(j)
def create_replay(self,endpoint,filename,num):
with open(filename,"w") as f:
for i in range (0,num):
jStr = self.construct_json()
jEncoded = urllib.quote_plus(jStr)
url = PREDICT_TEMPLATE.replace("%ENDPOINT%",endpoint).replace("%KEY%",self.key).replace("%JSON%",jEncoded)+"\n"
f.write(url)
if __name__ == '__main__':
import logging
logger = logging.getLogger()
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(name)s : %(message)s', level=logging.DEBUG)
logger.setLevel(logging.INFO)
parser = argparse.ArgumentParser(prog='create_replay')
parser.add_argument('--endpoint', help='endpoint for seldon server', default="seldon-server")
parser.add_argument('--key', help='file containing output of seldon-cli keys call', required=True)
parser.add_argument('--replay', help='replay file to create', required=True)
parser.add_argument('--num', help='number of actions and recommendation pair calls to create', required=False, type=int, default=1000)
parser.add_argument('--feature', help='feature to add ', required=True, action='append')
args = parser.parse_args()
opts = vars(args)
rc = ReplayCreate()
rc.get_key(args.key)
rc.parse_features(args.feature)
rc.create_replay(args.endpoint,args.replay,args.num)
| 987 |
458 | <filename>core/engine/src/ServiceDescription.h<gh_stars>100-1000
/*
* Copyright 2016 <NAME> <<EMAIL>>
*
* 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.
*/
/*
* This file is part of ngrest: http://github.com/loentar/ngrest
*/
#ifndef NGREST_SERVICEDESCRIPTION_H
#define NGREST_SERVICEDESCRIPTION_H
#include <string>
#include <vector>
namespace ngrest {
/**
* @brief operation parameter description
*/
struct ParameterDescription
{
/**
* @brief type of operation parameter
*/
enum class Type
{
Unknown,
Undefined,
String,
Number,
Boolean,
Array,
Object,
Any
};
std::string name; //!< parameter name
Type type; //!< type of parameter
bool nullable; //!< can be null
};
/**
* @brief operation description
*/
struct OperationDescription
{
std::string name; //!< service operation
std::string location; //!< by default = name, can be "add?a={a}&b={b}" or "get/{id}" or "put"
int method; //!< method depending on transport
std::string methodStr; //!< method depending on transport in string form
bool asynchronous; //!< is operation asynchronous
std::string description; //!< text description of the operation
std::string details; //!< text details of the operation
std::vector<ParameterDescription> parameters; //!< parameters
ParameterDescription::Type result; //!< type of result value
bool resultNullable; //!< result can be null
};
/**
* @brief service description
*/
struct ServiceDescription
{
std::string name; //!< service name
std::string location; //!< by default = name
std::string description; //!< text description of the service
std::string details; //!< text details of the service
std::vector<OperationDescription> operations; //!< service operations
};
} // namespace ngrest
#endif // NGREST_SERVICEDESCRIPTION_H
| 1,132 |
812 | <gh_stars>100-1000
/*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2021 The PWM 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 password.pwm.config.stored;
import password.pwm.PwmConstants;
import password.pwm.bean.DomainID;
import password.pwm.bean.UserIdentity;
import password.pwm.config.AppConfig;
import password.pwm.config.PwmSetting;
import password.pwm.config.PwmSettingCategory;
import password.pwm.config.PwmSettingSyntax;
import password.pwm.config.PwmSettingTemplateSet;
import password.pwm.config.value.LocalizedStringArrayValue;
import password.pwm.config.value.PasswordValue;
import password.pwm.config.value.StoredValue;
import password.pwm.config.value.StringArrayValue;
import password.pwm.config.value.StringValue;
import password.pwm.config.value.ValueFactory;
import password.pwm.config.value.ValueTypeConverter;
import password.pwm.error.ErrorInformation;
import password.pwm.error.PwmError;
import password.pwm.error.PwmOperationalException;
import password.pwm.error.PwmUnrecoverableException;
import password.pwm.util.PasswordData;
import password.pwm.util.java.CollectionUtil;
import password.pwm.util.java.JavaHelper;
import password.pwm.util.java.PwmExceptionLoggingConsumer;
import password.pwm.util.java.StringUtil;
import password.pwm.util.java.TimeDuration;
import password.pwm.util.logging.PwmLogger;
import password.pwm.util.secure.BCrypt;
import password.pwm.util.secure.HmacAlgorithm;
import password.pwm.util.secure.PwmRandom;
import password.pwm.util.secure.SecureEngine;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public abstract class StoredConfigurationUtil
{
private static final PwmLogger LOGGER = PwmLogger.forClass( StoredConfigurationUtil.class );
public static List<String> profilesForSetting(
final DomainID domainID,
final PwmSetting pwmSetting,
final StoredConfiguration storedConfiguration
)
{
if ( !pwmSetting.getCategory().hasProfiles() && pwmSetting.getSyntax() != PwmSettingSyntax.PROFILE )
{
throw new IllegalArgumentException( "cannot build profile list for non-profile setting " + pwmSetting.toString() );
}
final PwmSetting profileSetting;
if ( pwmSetting.getSyntax() == PwmSettingSyntax.PROFILE )
{
profileSetting = pwmSetting;
}
else
{
profileSetting = pwmSetting.getCategory().getProfileSetting().orElseThrow( IllegalStateException::new );
}
return profilesForProfileSetting( domainID, profileSetting, storedConfiguration );
}
public static List<String> profilesForCategory(
final DomainID domainID,
final PwmSettingCategory category,
final StoredConfiguration storedConfiguration
)
{
final PwmSetting profileSetting = category.getProfileSetting().orElseThrow( IllegalStateException::new );
return profilesForProfileSetting( domainID, profileSetting, storedConfiguration );
}
private static List<String> profilesForProfileSetting(
final DomainID domainID,
final PwmSetting profileSetting,
final StoredConfiguration storedConfiguration
)
{
final StoredConfigKey key = StoredConfigKey.forSetting( profileSetting, null, domainID );
final StoredValue storedValue = StoredConfigurationUtil.getValueOrDefault( storedConfiguration, key );
final List<String> settingValues = ValueTypeConverter.valueToStringArray( storedValue );
return settingValues.stream()
.filter( value -> StringUtil.notEmpty( value ) )
.collect( Collectors.toUnmodifiableList() );
}
public static StoredConfiguration copyConfigAndBlankAllPasswords( final StoredConfiguration storedConfig )
throws PwmUnrecoverableException
{
final StoredConfigurationModifier modifier = StoredConfigurationModifier.newModifier( storedConfig );
final Consumer<StoredConfigKey> valueModifier = PwmExceptionLoggingConsumer.wrapConsumer( storedConfigItemKey ->
{
if ( storedConfigItemKey.getRecordType() == StoredConfigKey.RecordType.SETTING )
{
final PwmSetting pwmSetting = storedConfigItemKey.toPwmSetting();
if ( pwmSetting.getSyntax() == PwmSettingSyntax.PASSWORD )
{
final Optional<ValueMetaData> valueMetaData = storedConfig.readSettingMetadata( storedConfigItemKey );
final UserIdentity userIdentity = valueMetaData.map( ValueMetaData::getUserIdentity ).orElse( null );
final PasswordValue passwordValue = new PasswordValue( new PasswordData( PwmConstants.LOG_REMOVED_VALUE_REPLACEMENT ) );
modifier.writeSetting( storedConfigItemKey, passwordValue, userIdentity );
}
}
} );
CollectionUtil.iteratorToStream( storedConfig.keys() )
.filter( ( key ) -> key.isRecordType( StoredConfigKey.RecordType.SETTING ) )
.forEach( valueModifier );
final Optional<String> pwdHash = storedConfig.readConfigProperty( ConfigurationProperty.PASSWORD_HASH );
if ( pwdHash.isPresent() )
{
modifier.writeConfigProperty( ConfigurationProperty.PASSWORD_HASH, PwmConstants.LOG_REMOVED_VALUE_REPLACEMENT );
}
return modifier.newStoredConfiguration();
}
public static List<String> validateValues( final StoredConfiguration storedConfiguration )
{
final Function<StoredConfigKey, Stream<String>> validateSettingFunction = storedConfigItemKey ->
{
final PwmSetting pwmSetting = storedConfigItemKey.toPwmSetting();
final String profileID = storedConfigItemKey.getProfileID();
final Optional<StoredValue> loopValue = storedConfiguration.readStoredValue( storedConfigItemKey );
if ( loopValue.isPresent() )
{
try
{
final List<String> errors = loopValue.get().validateValue( pwmSetting );
for ( final String loopError : errors )
{
return Stream.of( pwmSetting.toMenuLocationDebug( storedConfigItemKey.getProfileID(), PwmConstants.DEFAULT_LOCALE ) + " - " + loopError );
}
}
catch ( final Exception e )
{
LOGGER.error( () -> "unexpected error during validate value for "
+ pwmSetting.toMenuLocationDebug( profileID, PwmConstants.DEFAULT_LOCALE ) + ", error: "
+ e.getMessage(), e );
}
}
return Stream.empty();
};
final Instant startTime = Instant.now();
final List<String> errorStrings = CollectionUtil.iteratorToStream( storedConfiguration.keys() )
.filter( key -> key.isRecordType( StoredConfigKey.RecordType.SETTING ) )
.flatMap( validateSettingFunction )
.collect( Collectors.toList() );
LOGGER.trace( () -> "StoredConfiguration validator completed", () -> TimeDuration.fromCurrent( startTime ) );
return Collections.unmodifiableList( errorStrings );
}
public static boolean verifyPassword( final StoredConfiguration storedConfiguration, final String password )
{
if ( !hasPassword( storedConfiguration ) )
{
return false;
}
final Optional<String> passwordHash = storedConfiguration.readConfigProperty( ConfigurationProperty.PASSWORD_HASH );
return passwordHash.isPresent() && BCrypt.testAnswer( password, passwordHash.get(), new AppConfig( storedConfiguration ) );
}
public static boolean hasPassword( final StoredConfiguration storedConfiguration )
{
final Optional<String> passwordHash = storedConfiguration.readConfigProperty( ConfigurationProperty.PASSWORD_HASH );
return passwordHash.isPresent();
}
public static void setPassword( final StoredConfigurationModifier storedConfiguration, final String password )
throws PwmOperationalException, PwmUnrecoverableException
{
if ( StringUtil.isEmpty( password ) )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.CONFIG_FORMAT_ERROR, null, new String[]
{
"can not set blank password",
}
) );
}
final String trimmedPassword = password.trim();
if ( trimmedPassword.length() < 1 )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.CONFIG_FORMAT_ERROR, null, new String[]
{
"can not set blank password",
}
) );
}
final String passwordHash = BCrypt.hashPassword( password );
storedConfiguration.writeConfigProperty( ConfigurationProperty.PASSWORD_HASH, passwordHash );
}
public static void initNewRandomSecurityKey( final StoredConfigurationModifier modifier )
throws PwmUnrecoverableException
{
final StoredConfigKey key = StoredConfigKey.forSetting( PwmSetting.PWM_SECURITY_KEY, null, DomainID.systemId() );
if ( !isDefaultValue( modifier.newStoredConfiguration(), key ) )
{
return;
}
modifier.writeSetting(
key,
new PasswordValue( new PasswordData( PwmRandom.getInstance().alphaNumericString( 1024 ) ) ),
null
);
LOGGER.debug( () -> "initialized new random security key" );
}
public static Map<String, String> makeDebugMap(
final StoredConfiguration storedConfiguration,
final Collection<StoredConfigKey> interestedItems,
final Locale locale
)
{
return Collections.unmodifiableMap( interestedItems.stream()
.filter( key -> !key.isRecordType( StoredConfigKey.RecordType.PROPERTY ) )
.sorted()
.collect( Collectors.toMap(
key -> key.getLabel( locale ),
key -> StoredConfigurationUtil.getValueOrDefault( storedConfiguration, key ).toDebugString( locale ),
( u, v ) ->
{
throw new IllegalStateException( String.format( "duplicate key %s", u ) );
},
LinkedHashMap::new
) ) );
}
public static Set<StoredConfigKey> allPossibleSettingKeysForConfiguration(
final StoredConfiguration storedConfiguration
)
{
final List<DomainID> allDomainIds = new ArrayList<>( StoredConfigurationUtil.domainList( storedConfiguration ) );
allDomainIds.add( DomainID.systemId() );
return allDomainIds.stream()
.flatMap( domainID -> allPossibleSettingKeysForDomain( storedConfiguration, domainID ) )
.collect( Collectors.toUnmodifiableSet() );
}
private static Stream<StoredConfigKey> allPossibleSettingKeysForDomain(
final StoredConfiguration storedConfiguration,
final DomainID domainID
)
{
final Function<PwmSetting, Stream<StoredConfigKey>> function = loopSetting ->
{
if ( loopSetting.getCategory().hasProfiles() )
{
return StoredConfigurationUtil.profilesForSetting( domainID, loopSetting, storedConfiguration )
.stream()
.map( profileId -> StoredConfigKey.forSetting( loopSetting, profileId, domainID ) )
.collect( Collectors.toList() )
.stream();
}
else
{
return Stream.of( StoredConfigKey.forSetting( loopSetting, null, domainID ) );
}
};
return PwmSetting.sortedValues().stream()
.filter( ( setting ) -> domainID.inScope( setting.getCategory().getScope() ) )
.flatMap( function )
.collect( Collectors.toUnmodifiableSet() )
.stream();
}
public static Set<StoredConfigKey> changedValues (
final StoredConfiguration originalConfiguration,
final StoredConfiguration modifiedConfiguration
)
{
final Instant startTime = Instant.now();
final Predicate<StoredConfigKey> hashTester = key ->
{
final Optional<String> hash1 = originalConfiguration.readStoredValue( key ).map( StoredValue::valueHash );
final Optional<String> hash2 = modifiedConfiguration.readStoredValue( key ).map( StoredValue::valueHash );
return !hash1.equals( hash2 );
};
final Set<StoredConfigKey> deltaReferences = Stream.concat(
CollectionUtil.iteratorToStream( originalConfiguration.keys() ),
CollectionUtil.iteratorToStream( modifiedConfiguration.keys() ) )
.distinct()
.filter( hashTester )
.collect( Collectors.toUnmodifiableSet() );
LOGGER.trace( () -> "generated " + deltaReferences.size() + " changeLog items via compare", () -> TimeDuration.fromCurrent( startTime ) );
return deltaReferences;
}
public static StoredValue getValueOrDefault(
final StoredConfiguration storedConfiguration,
final StoredConfigKey key
)
{
final Optional<StoredValue> storedValue = storedConfiguration.readStoredValue( key );
if ( storedValue.isPresent() )
{
return storedValue.get();
}
switch ( key.getRecordType() )
{
case SETTING:
{
final PwmSettingTemplateSet templateSet = storedConfiguration.getTemplateSet().get( key.getDomainID() );
return key.toPwmSetting().getDefaultValue( templateSet );
}
case LOCALE_BUNDLE:
{
return new LocalizedStringArrayValue( Collections.emptyMap() );
}
case PROPERTY:
return new StringValue( "" );
default:
JavaHelper.unhandledSwitchStatement( key );
}
throw new IllegalStateException();
}
public static List<DomainID> domainList( final StoredConfiguration storedConfiguration )
{
return storedConfiguration.getTemplateSet().keySet().stream()
.filter( domain -> !Objects.equals( domain, DomainID.systemId() ) )
.sorted()
.collect( Collectors.toUnmodifiableList() );
}
public static StoredConfiguration copyProfileID(
final StoredConfiguration oldStoredConfiguration,
final DomainID domainID,
final PwmSettingCategory category,
final String sourceID,
final String destinationID,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
if ( !category.hasProfiles() )
{
throw PwmUnrecoverableException.newException(
PwmError.ERROR_INVALID_CONFIG, "can not copy profile ID for category " + category + ", category does not have profiles" );
}
final PwmSetting profileSetting = category.getProfileSetting().orElseThrow( IllegalStateException::new );
final List<String> existingProfiles = StoredConfigurationUtil.profilesForSetting( domainID, profileSetting, oldStoredConfiguration );
if ( !existingProfiles.contains( sourceID ) )
{
throw PwmUnrecoverableException.newException(
PwmError.ERROR_INVALID_CONFIG, "can not copy profile ID for category, source profileID '" + sourceID + "' does not exist" );
}
if ( existingProfiles.contains( destinationID ) )
{
throw PwmUnrecoverableException.newException(
PwmError.ERROR_INVALID_CONFIG, "can not copy profile ID for category, destination profileID '" + destinationID + "' already exists" );
}
final Collection<PwmSettingCategory> interestedCategories = PwmSettingCategory.associatedProfileCategories( category );
final StoredConfigurationModifier modifier = StoredConfigurationModifier.newModifier( oldStoredConfiguration );
for ( final PwmSettingCategory interestedCategory : interestedCategories )
{
for ( final PwmSetting pwmSetting : interestedCategory.getSettings() )
{
final StoredConfigKey existingKey = StoredConfigKey.forSetting( pwmSetting, sourceID, domainID );
final Optional<StoredValue> existingValue = oldStoredConfiguration.readStoredValue( existingKey );
if ( existingValue.isPresent() )
{
final StoredConfigKey destinationKey = StoredConfigKey.forSetting( pwmSetting, destinationID, domainID );
modifier.writeSetting( destinationKey, existingValue.get(), userIdentity );
}
}
}
{
final List<String> newProfileIDList = new ArrayList<>( existingProfiles );
newProfileIDList.add( destinationID );
final StoredConfigKey key = StoredConfigKey.forSetting( profileSetting, null, domainID );
final StoredValue value = new StringArrayValue( newProfileIDList );
modifier.writeSetting( key, value, userIdentity );
}
return modifier.newStoredConfiguration();
}
public static StoredConfiguration copyDomainID(
final StoredConfiguration oldStoredConfiguration,
final String source,
final String destination,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
final Instant startTime = Instant.now();
final DomainID sourceID = DomainID.create( source );
final DomainID destinationID = DomainID.create( destination );
final List<DomainID> existingProfiles = StoredConfigurationUtil.domainList( oldStoredConfiguration );
if ( !existingProfiles.contains( sourceID ) )
{
throw PwmUnrecoverableException.newException(
PwmError.ERROR_INVALID_CONFIG, "can not copy domain ID, source domainID '" + sourceID + "' does not exist" );
}
if ( existingProfiles.contains( destinationID ) )
{
throw PwmUnrecoverableException.newException(
PwmError.ERROR_INVALID_CONFIG, "can not copy domain ID for category, destination domainID '" + destinationID + "' already exists" );
}
final StoredConfigurationModifier modifier = StoredConfigurationModifier.newModifier( oldStoredConfiguration );
CollectionUtil.iteratorToStream( modifier.newStoredConfiguration().keys() )
.filter( key -> key.getDomainID().equals( sourceID ) )
.forEach( key ->
{
final StoredConfigKey newKey = key.withNewDomain( destinationID );
final StoredValue storedValue = oldStoredConfiguration.readStoredValue( key ).orElseThrow();
try
{
modifier.writeSetting( newKey, storedValue, userIdentity );
}
catch ( final PwmUnrecoverableException e )
{
throw new IllegalStateException( "unexpected error copying domain setting values: " + e.getMessage() );
}
} );
{
final StoredConfigKey key = StoredConfigKey.forSetting( PwmSetting.DOMAIN_LIST, null, DomainID.systemId() );
final List<String> domainList = new ArrayList<>( ValueTypeConverter.valueToStringArray( StoredConfigurationUtil.getValueOrDefault( oldStoredConfiguration, key ) ) );
domainList.add( destination );
final StoredValue value = new StringArrayValue( domainList );
modifier.writeSetting( key, value, userIdentity );
}
LOGGER.trace( () -> "copied " + modifier.modifications() + " domain settings from '" + source + "' to '" + destination + "' domain",
() -> TimeDuration.fromCurrent( startTime ) );
return modifier.newStoredConfiguration();
}
public static String valueHash( final StoredConfiguration storedConfiguration )
{
final Instant startTime = Instant.now();
final StringBuilder sb = new StringBuilder();
CollectionUtil.iteratorToStream( storedConfiguration.keys() )
.map( storedConfiguration::readStoredValue )
.flatMap( Optional::stream )
.forEach( v -> sb.append( v.valueHash() ) );
final String output;
try
{
output = SecureEngine.hmac( HmacAlgorithm.HMAC_SHA_512, storedConfiguration.getKey(), sb.toString() );
}
catch ( final PwmUnrecoverableException e )
{
throw new IllegalStateException( e );
}
LOGGER.trace( () -> "calculated StoredConfiguration hash: " + output, () -> TimeDuration.fromCurrent( startTime ) );
return output;
}
public static boolean isDefaultValue( final StoredConfiguration storedConfiguration, final StoredConfigKey key )
{
if ( !key.isRecordType( StoredConfigKey.RecordType.SETTING ) )
{
throw new IllegalArgumentException( "key must be for SETTING type" );
}
final Optional<StoredValue> existingValue = storedConfiguration.readStoredValue( key );
if ( existingValue.isEmpty() )
{
return true;
}
return ValueFactory.isDefaultValue( storedConfiguration.getTemplateSet().get( key.getDomainID( ) ), key.toPwmSetting(), existingValue.get() );
}
}
| 9,249 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices
*/
#import <ProtocolBuffer/PBCodable.h>
@interface GEOMapQueryCollectionResponse : PBCodable {
}
- (void)writeTo:(id)to; // 0x428d
- (BOOL)readFrom:(id)from; // 0x41dd
- (id)dictionaryRepresentation; // 0x41c1
- (id)description; // 0x4151
- (void)dealloc; // 0x4125
@end
| 162 |
479 | <reponame>OscarPellicer/probreg<gh_stars>100-1000
#ifndef __probreg_point_to_plane_h__
#define __probreg_point_to_plane_h__
#include "types.h"
#include <utility>
namespace probreg {
typedef std::pair<Vector6, Float> Pt2PlResult;
Pt2PlResult computeTwistForPointToPlane(const MatrixX3& model,
const MatrixX3& target,
const MatrixX3& target_normal,
const Vector& weight);
}
#endif | 269 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMEOS_MEMORY_USERSPACE_SWAP_USERSPACE_SWAP_RENDERER_INITIALIZATION_IMPL_H_
#define CHROMEOS_MEMORY_USERSPACE_SWAP_USERSPACE_SWAP_RENDERER_INITIALIZATION_IMPL_H_
#include "base/callback_forward.h"
#include "base/files/scoped_file.h"
#include "chromeos/chromeos_export.h"
#include "mojo/public/cpp/bindings/generic_pending_receiver.h"
namespace chromeos {
namespace memory {
namespace userspace_swap {
class CHROMEOS_EXPORT UserspaceSwapRendererInitializationImpl {
public:
UserspaceSwapRendererInitializationImpl();
UserspaceSwapRendererInitializationImpl(
const UserspaceSwapRendererInitializationImpl&) = delete;
UserspaceSwapRendererInitializationImpl& operator=(
const UserspaceSwapRendererInitializationImpl&) = delete;
~UserspaceSwapRendererInitializationImpl();
static bool UserspaceSwapSupportedAndEnabled();
// PreSandboxSetup() is responsible for creating any resources that might be
// needed before we enter the sandbox.
bool PreSandboxSetup();
// TransferFDsOrCleanup should be called after the sandbox has been entered.
// |bind_host_receiver_callback| will be invoked to bind a mojo interface
// between the renderer process and its browser process host.
void TransferFDsOrCleanup(
base::OnceCallback<void(mojo::GenericPendingReceiver)>
bind_host_receiver_callback);
private:
int uffd_errno_ = 0;
base::ScopedFD uffd_;
int mmap_errno_ = 0;
uint64_t swap_area_ = 0;
uint64_t swap_area_len_ = 0;
};
} // namespace userspace_swap
} // namespace memory
} // namespace chromeos
#endif // CHROMEOS_MEMORY_USERSPACE_SWAP_USERSPACE_SWAP_RENDERER_INITIALIZATION_IMPL_H_
| 627 |
1,760 | <reponame>nocrizwang/USACO
/**
* Description: The centroid of a tree of size $N$ is a vertex such that
* after removing it, all resulting subtrees have size at most $\frac{N}{2}.$
* Supports updates in the form ``add 1 to all verts $v$ such that $dist(x,v)\le y$."
* Time: O(N\log N) build, O(\log N) update and query
* Memory: O(N\log N)
* Source: own
* Verification:
* solves https://dmoj.ca/problem/dmopc19c7p6
* https://codeforces.com/contest/342/problem/E
* Triway Cup 2019 G
*/
void ad(vi& a, int b) { ckmin(b,sz(a)-1); if (b>=0) a[b]++; }
void prop(vi& a) { R0F(i,sz(a)-1) a[i] += a[i+1]; }
template<int SZ> struct Centroid {
vi adj[SZ]; void ae(int a,int b){adj[a].pb(b),adj[b].pb(a);}
bool done[SZ]; // processed as centroid yet
int N,sub[SZ],cen[SZ],lev[SZ]; // subtree size, centroid anc
int dist[32-__builtin_clz(SZ)][SZ]; // dists to all ancs
vi stor[SZ], STOR[SZ];
void dfs(int x, int p) { sub[x] = 1;
each(y,adj[x]) if (!done[y] && y != p)
dfs(y,x), sub[x] += sub[y];
}
int centroid(int x) {
dfs(x,-1);
for (int sz = sub[x];;) {
pi mx = {0,0};
each(y,adj[x]) if (!done[y] && sub[y] < sub[x])
ckmax(mx,{sub[y],y});
if (mx.f*2 <= sz) return x;
x = mx.s;
}
}
void genDist(int x, int p, int lev) {
dist[lev][x] = dist[lev][p]+1;
each(y,adj[x]) if (!done[y] && y != p) genDist(y,x,lev); }
void gen(int CEN, int _x) { // CEN = centroid above x
int x = centroid(_x); done[x] = 1; cen[x] = CEN;
sub[x] = sub[_x]; lev[x] = (CEN == -1 ? 0 : lev[CEN]+1);
dist[lev[x]][x] = 0;
stor[x].rsz(sub[x]),STOR[x].rsz(sub[x]+1);
each(y,adj[x]) if (!done[y]) genDist(y,x,lev[x]);
each(y,adj[x]) if (!done[y]) gen(x,y);
}
void init(int _N) { N = _N; FOR(i,1,N+1) done[i] = 0;
gen(-1,1); } // start at vert 1
void upd(int x, int y) {
int cur = x, pre = -1;
R0F(i,lev[x]+1) {
ad(stor[cur],y-dist[i][x]);
if (pre != -1) ad(STOR[pre],y-dist[i][x]);
if (i > 0) pre = cur, cur = cen[cur];
}
} // call propAll() after all updates
void propAll() { FOR(i,1,N+1) prop(stor[i]), prop(STOR[i]); }
int query(int x) { // get value at vertex x
int cur = x, pre = -1, ans = 0;
R0F(i,lev[x]+1) { // if pre != -1, subtract those from
ans += stor[cur][dist[i][x]]; // same subtree
if (pre != -1) ans -= STOR[pre][dist[i][x]];
if (i > 0) pre = cur, cur = cen[cur];
}
return ans;
}
};
| 1,187 |
424 | import time
import sublime
import sublime_plugin
import fnmatch
import os
from ..lib import omnisharp
from ..lib import helpers
class OmniSharpAddReference(sublime_plugin.TextCommand):
def run(self, edit):
parentpath = sublime.active_window().folders()[0]
matches = []
for root, dirnames, filenames in os.walk(parentpath):
if 'bin' not in root or 'obj' not in root:
for filename in fnmatch.filter(filenames, '*.dll'):
matches.append(os.path.join(root, filename))
def on_done(i):
if i is not -1:
params = {'reference': matches[i]}
omnisharp.get_response(
self.view, '/addreference', self._process_addref, params)
if len(matches) > 0:
sublime.active_window().show_quick_panel(matches, on_done)
else:
sublime.status_message('No libraries found to add reference to')
def _process_addref(self, data):
sublime.status_message(data['Message'])
def is_enabled(self):
return helpers.is_csharp(self.view)
| 478 |
11,396 | <gh_stars>1000+
# Generated by Django 2.2.11 on 2020-07-08 18:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.expressions
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('main', '0123_drop_hg_support'),
]
operations = [
migrations.CreateModel(
name='ExecutionEnvironment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(default=None, editable=False)),
('modified', models.DateTimeField(default=None, editable=False)),
('description', models.TextField(blank=True, default='')),
('image', models.CharField(help_text='The registry location where the container is stored.', max_length=1024, verbose_name='image location')),
('managed_by_tower', models.BooleanField(default=False, editable=False)),
(
'created_by',
models.ForeignKey(
default=None,
editable=False,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="{'class': 'executionenvironment', 'model_name': 'executionenvironment', 'app_label': 'main'}(class)s_created+",
to=settings.AUTH_USER_MODEL,
),
),
(
'credential',
models.ForeignKey(
blank=True,
default=None,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='executionenvironments',
to='main.Credential',
),
),
(
'modified_by',
models.ForeignKey(
default=None,
editable=False,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="{'class': 'executionenvironment', 'model_name': 'executionenvironment', 'app_label': 'main'}(class)s_modified+",
to=settings.AUTH_USER_MODEL,
),
),
(
'organization',
models.ForeignKey(
blank=True,
default=None,
help_text='The organization used to determine access to this execution environment.',
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name='executionenvironments',
to='main.Organization',
),
),
(
'tags',
taggit.managers.TaggableManager(
blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'
),
),
],
options={
'ordering': (django.db.models.expressions.OrderBy(django.db.models.expressions.F('organization_id'), nulls_first=True), 'image'),
'unique_together': {('organization', 'image')},
},
),
migrations.AddField(
model_name='activitystream',
name='execution_environment',
field=models.ManyToManyField(blank=True, to='main.ExecutionEnvironment'),
),
migrations.AddField(
model_name='organization',
name='default_environment',
field=models.ForeignKey(
blank=True,
default=None,
help_text='The default execution environment for jobs run by this organization.',
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to='main.ExecutionEnvironment',
),
),
migrations.AddField(
model_name='unifiedjob',
name='execution_environment',
field=models.ForeignKey(
blank=True,
default=None,
help_text='The container image to be used for execution.',
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='unifiedjobs',
to='main.ExecutionEnvironment',
),
),
migrations.AddField(
model_name='unifiedjobtemplate',
name='execution_environment',
field=models.ForeignKey(
blank=True,
default=None,
help_text='The container image to be used for execution.',
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='unifiedjobtemplates',
to='main.ExecutionEnvironment',
),
),
]
| 2,986 |
1,900 | <gh_stars>1000+
/*
* Copyright Terracotta, 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 org.ehcache.clustered.common.internal.store;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
public class CustomLoaderBasedObjectInputStream extends ObjectInputStream {
private final ClassLoader loader;
public CustomLoaderBasedObjectInputStream(InputStream in, ClassLoader loader) throws IOException {
super(in);
this.loader = loader;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
try {
final ClassLoader cl = loader == null ? Thread.currentThread().getContextClassLoader() : loader;
if (cl == null) {
return super.resolveClass(desc);
} else {
try {
return Class.forName(desc.getName(), false, cl);
} catch (ClassNotFoundException e) {
return super.resolveClass(desc);
}
}
} catch (SecurityException ex) {
return super.resolveClass(desc);
}
}
}
| 511 |
4,842 | <gh_stars>1000+
package com.gpmall.user.dto;
import com.gpmall.commons.result.AbstractRequest;
import com.gpmall.commons.tool.exception.ValidateException;
import com.gpmall.user.constants.SysRetCodeConstants;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
/**
* 腾讯课堂搜索【咕泡学院】
* 官网:www.gupaoedu.com
* 风骚的Mic 老师
* create-date: 2019/7/23-12:48
*/
@Data
public class UserRegisterRequest extends AbstractRequest {
private String userName;
private String userPwd;
private String email;
@Override
public void requestCheck() {
if(StringUtils.isBlank(userName)||StringUtils.isBlank(userPwd)){
throw new ValidateException(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode(),SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage());
}
}
}
| 347 |
1,056 | <reponame>timfel/netbeans<filename>platform/o.n.core/test/qa-functional/src/gui/propertyeditors/PropertyType_Color.java
/*
* 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 gui.propertyeditors;
import org.netbeans.jellytools.properties.ColorProperty;
import org.netbeans.jellytools.properties.PropertySheetOperator;
import org.netbeans.jellytools.properties.editors.ColorCustomEditorOperator;
import org.netbeans.junit.NbTestSuite;
/**
* Tests of Color Property Editor.
*
* @author Mar<EMAIL>.Miri<EMAIL>
*/
public class PropertyType_Color extends PropertyEditorsTest {
public String propertyName_L;
public String propertyValue_L;
public String propertyValueExpectation_L;
public boolean waitDialog = false;
/** Creates a new instance of PropertyType_Boolean */
public PropertyType_Color(String testName) {
super(testName);
}
public void setUp(){
propertyName_L = "Color";
super.setUp();
}
public static NbTestSuite suite() {
NbTestSuite suite = new NbTestSuite();
suite.addTest(new PropertyType_Color("verifyCustomizer"));
suite.addTest(new PropertyType_Color("testCustomizerCancel"));
suite.addTest(new PropertyType_Color("testCustomizerOk"));
suite.addTest(new PropertyType_Color("testByInPlace"));
suite.addTest(new PropertyType_Color("testByInPlaceInvalid"));
return suite;
}
public void testCustomizerOk() {
propertyValue_L = "50,50,50";
propertyValueExpectation_L = "["+propertyValue_L+"]";
waitDialog = false;
setByCustomizerOk(propertyName_L, true);
}
public void testCustomizerCancel(){
propertyValue_L = "100,100,100";
propertyValueExpectation_L = "["+propertyValue_L+"]";
waitDialog = false;
setByCustomizerCancel(propertyName_L, false);
}
public void testByInPlace(){
propertyValue_L = "20,10,100";
propertyValueExpectation_L = "["+propertyValue_L+"]";
waitDialog = false;
setByInPlace(propertyName_L, propertyValue_L, true);
}
public void testByInPlaceInvalid(){
propertyValue_L = "xx color";
propertyValueExpectation_L = propertyValue_L;
waitDialog = true;
setByInPlace(propertyName_L, propertyValue_L, false);
}
public void verifyCustomizer(){
verifyCustomizer(propertyName_L);
}
public void setCustomizerValue() {
ColorCustomEditorOperator customizer = new ColorCustomEditorOperator(propertyCustomizer);
int first_comma = propertyValue_L.indexOf(',');
int second_comma = propertyValue_L.indexOf(',',first_comma+1);
int r = new Integer(propertyValue_L.substring(0,first_comma)).intValue();
int g = new Integer(propertyValue_L.substring(first_comma+1, second_comma)).intValue();
int b = new Integer(propertyValue_L.substring(second_comma+1)).intValue();
customizer.setRGBValue(r,g,b);
}
public void verifyPropertyValue(boolean expectation) {
verifyExpectationValue(propertyName_L,expectation, propertyValueExpectation_L, propertyValue_L, waitDialog);
}
public String getValue(String propertyName) {
String returnValue;
PropertySheetOperator propertiesTab = new PropertySheetOperator(propertiesWindow);
returnValue = new ColorProperty(propertiesTab, propertyName_L).getValue();
err.println("GET VALUE = [" + returnValue + "].");
// hack for color poperty, this action expects, that right value is displayed as tooltip
// returnValue = new Property(propertiesTab, propertyName_L).valueButtonOperator().getToolTipText();
// err.println("GET VALUE TOOLTIP = [" + returnValue + "].");
return returnValue;
}
public void verifyCustomizerLayout() {
ColorCustomEditorOperator customizer = new ColorCustomEditorOperator(propertyCustomizer);
customizer.verify();
customizer.btOK();
customizer.btCancel();
}
/** Test could be executed internaly in Forte without XTest
* @param args arguments from command line
*/
public static void main(String[] args) {
//junit.textui.TestRunner.run(new NbTestSuite(PropertyType_Color.class));
junit.textui.TestRunner.run(suite());
}
}
| 1,942 |
710 | package com.dpizarro.uipicker.library.blur;
/*
* Copyright (C) 2015 <NAME>
*
* 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.
*/
public class PickerUIBlur {
/**
* Minimum valid value of Blur radius.
*/
public static final int MIN_BLUR_RADIUS = 1;
/**
* Minimum valid value of down scale factor.
*/
public static final float MIN_DOWNSCALE = 1.0f;
/**
* Maximum valid value of Blur radius.
*/
private static final int MAX_BLUR_RADIUS = 25;
/**
* Maximum valid value of down scale factor.
*/
private static final float MAX_DOWNSCALE = 6.0f;
/**
* Default behaviour of blur
*/
public static boolean DEFAULT_USE_BLUR = true;
/**
* Default use of renderscript algorithm
*/
public static boolean DEFAULT_USE_BLUR_RENDERSCRIPT = false;
/**
* Default Blur radius used for the background
*/
public static int DEFAULT_BLUR_RADIUS = 15;
/**
* Default Down scale factor to reduce blurring time and memory allocation.
*/
public static float DEFAULT_DOWNSCALE_FACTOR = 5.0f;
/**
* Default alpha to apply in blurred image
*/
public static int CONSTANT_DEFAULT_ALPHA = 100;
/**
* Validates if the radius value chosen is valid.
*
* @param value Radius value selected
* @return Returns 'true' if the value is between {@link PickerUIBlur#MAX_BLUR_RADIUS} and
* {@link
* PickerUIBlur#MIN_BLUR_RADIUS}
*/
public static boolean isValidBlurRadius(int value) {
return value >= MIN_BLUR_RADIUS && value <= MAX_BLUR_RADIUS;
}
/**
* Validates if the scale chosen is valid.
*
* @param value Scale value selected
* @return Returns 'true' if the value is between {@link PickerUIBlur#MAX_DOWNSCALE} and {@link
* PickerUIBlur#MIN_DOWNSCALE}
*/
public static boolean isValidDownscale(float value) {
return value >= MIN_DOWNSCALE && value <= MAX_DOWNSCALE;
}
}
| 903 |
716 | <reponame>akopich/orbit
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CLIENT_MODEL_SAMPLING_DATA_POST_PROCESSOR_H_
#define CLIENT_MODEL_SAMPLING_DATA_POST_PROCESSOR_H_
#include "ClientData/CallstackData.h"
#include "ClientData/CaptureData.h"
#include "ClientData/ModuleManager.h"
#include "ClientData/PostProcessedSamplingData.h"
namespace orbit_client_model {
orbit_client_data::PostProcessedSamplingData CreatePostProcessedSamplingData(
const orbit_client_data::CallstackData& callstack_data,
const orbit_client_data::CaptureData& capture_data,
const orbit_client_data::ModuleManager& module_manager, bool generate_summary = true);
} // namespace orbit_client_model
#endif // CLIENT_MODEL_SAMPLING_DATA_POST_PROCESSOR_H_
| 287 |
369 | /*
* Copyright © 2016 <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.cdap.cdap.app.runtime.spark;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Timer;
import io.cdap.cdap.api.metrics.MetricsContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
/**
* A {@link ScheduledReporter} reports which reports Metrics collected by the {@link SparkMetricsSink} to
* {@link MetricsContext}.
*/
final class SparkMetricsReporter extends ScheduledReporter {
private static final Logger LOG = LoggerFactory.getLogger(SparkMetricsReporter.class);
private final MetricsContext metricsContext;
SparkMetricsReporter(MetricRegistry registry,
TimeUnit rateUnit,
TimeUnit durationUnit,
MetricFilter filter) {
super(registry, "spark-reporter", filter, rateUnit, durationUnit);
this.metricsContext = SparkRuntimeContextProvider.get().getProgramMetrics();
}
/**
* Called periodically by the polling thread. We are only interested in the Gauges.
*
* @param gauges all of the gauges in the registry
* @param counters all of the counters in the registry
* @param histograms all of the histograms in the registry
* @param meters all of the meters in the registry
* @param timers all of the timers in the registry
*/
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers) {
//For now we only use gauge as all the metrics needed are there. We might consider using more in future.
if (!gauges.isEmpty()) {
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
// for some cases the gauge value is Integer so a typical casting fails. Hence, first cast to Number and then
// get the value as a long
String metricName = entry.getKey();
// NOTE : Stripping uniqueId from the metricName , as we already have runId in context.
// Currently Spark metric-names are of the format "local-124433533.x.y.z" , we remove local-124433533 and
// convert this to x.y.z
String[] metricNameParts = metricName.split("\\.", 2);
if (metricNameParts.length == 2) {
metricName = metricNameParts[1];
}
try {
long value = ((Number) entry.getValue().getValue()).longValue();
metricsContext.gauge(metricName, value);
} catch (Exception e) {
// In older Spark version, there is race getting the gauge value, which result in exception.
// Since this is just metrics collection for Spark metrics, simply ignore it.
LOG.debug("Exception raised when collecting Spark metrics {}", entry.getKey(), e);
}
}
}
}
}
| 1,305 |
780 | package integration;
import com.codeborne.selenide.ex.ElementShould;
import com.codeborne.selenide.logevents.EventsCollector;
import com.codeborne.selenide.logevents.SelenideLogger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.CollectionCondition.sizeGreaterThan;
import static com.codeborne.selenide.Condition.exactText;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
import static com.codeborne.selenide.Selenide.$$x;
import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
final class SelenideLoggerTest extends IntegrationTest {
private static final String LISTENER = "SelenideLoggerTest";
private final EventsCollector collector = new EventsCollector();
@BeforeEach
void setUp() {
openFile("page_with_selects_without_jquery.html");
SelenideLogger.addListener(LISTENER, collector);
}
@AfterEach
void tearDown() {
SelenideLogger.removeListener(LISTENER);
}
@Test
void val() {
$(By.name("password")).val("<PASSWORD>");
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"By.name: password\") val(sherlyn)");
assertThat(collector.events().get(0).getElement()).isEqualTo("By.name: password");
assertThat(collector.events().get(0).getStatus()).isEqualTo(PASS);
assertThat(collector.events().get(0).getSubject()).isEqualTo("val(sherlyn)");
assertThat(collector.events().get(0).getError()).isNull();
assertThat(collector.events().get(0).getDuration()).isBetween(0L, 10_000L);
}
@Test
void shouldHaveText() {
assertThatThrownBy(() -> $("h1").shouldHave(exactText("A wrong header")))
.isInstanceOf(ElementShould.class);
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"h1\") should have(exact text 'A wrong header')");
}
@Test
void shouldHaveSize() {
$$("h1").shouldHave(size(2));
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"h1\") should have(size(2))");
}
@Test
void filterShouldHaveSize() {
$$("h1").filterBy(visible).shouldHave(size(2));
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"h1.filter(visible)\") should have(size(2))");
}
@Test
void findAllShouldHaveSize() {
$("body").findAll("h1").shouldHave(sizeGreaterThan(0));
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"body/h1\") should have(size > 0)");
}
@Test
void findElements() {
assertThat($("body").findElements(By.tagName("h1")).size()).isEqualTo(2);
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"body\") find elements(By.tagName: h1)");
}
@Test
void collectionByXpath() {
$$x("//h1").shouldHave(size(2));
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"By.xpath: //h1\") should have(size(2))");
}
@Test
void collectionByXpathGetText() {
assertThat($$x("//h1").first().getText()).isEqualTo("Page with selects");
assertThat(collector.events()).hasSize(1);
assertThat(collector.events().get(0)).hasToString("$(\"By.xpath: //h1[0]\") get text()");
}
}
| 1,373 |
1,014 | <reponame>MobileAir/FinanceDatabase
{
"GMFI.JK": {
"short_name": "Garuda Maintenance Facility Aer",
"long_name": "PT Garuda Maintenance Facility Aero Asia Tbk",
"summary": "PT Garuda Maintenance Facility Aero Asia Tbk provides various aircraft maintenance, repair, and overhaul (MRO) services for aircraft, engines, and components in Africa, Asia, Australia, America, Europe, and Oceania. The company operates through three segments: Repairs and Overhauls, Line Maintenance, and Other Operations. Its MRO services include line maintenance, base maintenance, airframe, component, engineering, material and logistics, cabin maintenance, engine and APU maintenance, learning center, power, and aircraft support, as well as technical ground handling. The company was founded in 1949 and is headquartered in Tangerang, Indonesia. PT Garuda Maintenance Facility Aero Asia Tbk is a subsidiary of PT Garuda Indonesia (Persero) Tbk.",
"currency": "IDR",
"sector": "Industrials",
"industry": "Aerospace & Defense",
"exchange": "JKT",
"market": "id_market",
"country": "Indonesia",
"state": null,
"city": "Tangerang",
"zipcode": "15125",
"website": "http://www.gmf-aeroasia.co.id",
"market_cap": "Large Cap"
},
"KPAL.JK": {
"short_name": "Steadfast Marine Tbk.",
"long_name": "PT Steadfast Marine Tbk",
"summary": "PT Steadfast Marine Tbk designs and manufactures ships in Indonesia. The company offers anchor handling tugs, crew boats, tug boats, diving support vessels, dredgers, motor cepats, landing craft tanks, and propelled oil barges. It serves harbor and terminal, offshore oil and gas, public transport, and defense and security markets. The company was founded in 2004 and is headquartered in Jakarta Pusat, Indonesia.",
"currency": "IDR",
"sector": "Industrials",
"industry": "Aerospace & Defense",
"exchange": "JKT",
"market": "id_market",
"country": "Indonesia",
"state": null,
"city": "Jakarta Pusat",
"zipcode": "10720",
"website": "http://steadfast-marine.co.id",
"market_cap": "Large Cap"
}
} | 813 |
1,194 | package ca.uhn.fhir.parser.i423;
import java.math.BigDecimal;
import java.util.List;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.annotation.Block;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.dstu2.composite.PeriodDt;
import ca.uhn.fhir.model.dstu2.composite.RangeDt;
import ca.uhn.fhir.model.dstu2.composite.TimingDt;
import ca.uhn.fhir.model.dstu2.valueset.EventTimingEnum;
import ca.uhn.fhir.model.dstu2.valueset.UnitsOfTimeEnum;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.IntegerDt;
import ca.uhn.fhir.util.ElementUtil;
@DatatypeDef(name = "Timing")
public class CustomTimingDt extends TimingDt {
/**
* repeat
*/
@Child(name = FIELD_REPEAT, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {_Repeat.class})
@Description(shortDefinition = "When the event is to occur", formalDefinition = "A set of rules that describe when the event should occur.")
protected _Repeat ourRepeat;
public static final String FIELD_REPEAT = "repeat";
@Override
public boolean isEmpty() {
return super.isEmpty() && ElementUtil.isEmpty(ourRepeat);
}
@Override
public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) {
return ElementUtil.allPopulatedChildElements(theType, ourRepeat);
}
public _Repeat _getRepeat() {
if (ourRepeat == null)
ourRepeat = new _Repeat();
return ourRepeat;
}
public CustomTimingDt _setRepeat(_Repeat theValue) {
ourRepeat = theValue;
return this;
}
@Block
public static class _Repeat extends Repeat {
/**
* bounds
*/
@Child(name = FIELD_BOUNDS, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {RangeDt.class, PeriodDt.class})
@Description(shortDefinition = "Length/Range of lengths, or (Start and/or end) limits", formalDefinition = "Either a duration for the length of the timing schedule, a range of possible length, or outer bounds for start and/or end limits of the timing schedule.")
protected IDatatype ourBounds;
public static final String FIELD_BOUNDS = "bounds";
/**
* count
*/
@Child(name = FIELD_COUNT, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {IntegerDt.class})
@Description(shortDefinition = "Number of times to repeat", formalDefinition = "A total count of the desired number of repetitions.")
protected IntegerDt ourCount;
public static final String FIELD_COUNT = "count";
/**
* duration
*/
@Child(name = FIELD_DURATION, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {DecimalDt.class})
@Description(shortDefinition = "How long when it happens", formalDefinition = "How long this thing happens for when it happens.")
protected DecimalDt ourDuration;
public static final String FIELD_DURATION = "duration";
/**
* durationMax
*/
@Child(name = FIELD_DURATIONMAX, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {DecimalDt.class})
@Description(shortDefinition = "How long when it happens (Max)", formalDefinition = "The upper limit of how long this thing happens for when it happens.")
protected DecimalDt ourDurationMax;
public static final String FIELD_DURATIONMAX = "durationMax";
/**
* durationUnits
*/
@Child(name = FIELD_DURATIONUNITS, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {CodeDt.class})
@Description(shortDefinition = "s | min | h | d | wk | mo | a - unit of time (UCUM)", formalDefinition = "The units of time for the duration, in UCUM units.")
protected BoundCodeDt<UnitsOfTimeEnum> ourDurationUnits;
public static final String FIELD_DURATIONUNITS = "durationUnits";
/**
* frequency
*/
@Child(name = FIELD_FREQUENCY, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {IntegerDt.class})
@Description(shortDefinition = "Event occurs frequency times per period", formalDefinition = "The number of times to repeat the action within the specified period / period range (i.e. both period and periodMax provided).")
protected IntegerDt ourFrequency;
public static final String FIELD_FREQUENCY = "frequency";
/**
* frequencyMax
*/
@Child(name = FIELD_FREQUENCYMAX, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {IntegerDt.class})
@Description(shortDefinition = "Event occurs up to frequencyMax times per period", formalDefinition = "If present, indicates that the frequency is a range - so repeat between [frequency] and [frequencyMax] times within the period or period range.")
protected IntegerDt ourFrequencyMax;
public static final String FIELD_FREQUENCYMAX = "frequencyMax";
/**
* period
*/
@Child(name = FIELD_PERIOD, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {DecimalDt.class})
@Description(shortDefinition = "Event occurs frequency times per period", formalDefinition = "Indicates the duration of time over which repetitions are to occur; e.g. to express \"3 times per day\", 3 would be the frequency and \"1 day\" would be the period.")
protected DecimalDt ourPeriod;
public static final String FIELD_PERIOD = "period";
/**
* periodMax
*/
@Child(name = FIELD_PERIODMAX, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {DecimalDt.class})
@Description(shortDefinition = "Upper limit of period (3-4 hours)", formalDefinition = "If present, indicates that the period is a range from [period] to [periodMax], allowing expressing concepts such as \"do this once every 3-5 days.")
protected DecimalDt ourPeriodMax;
public static final String FIELD_PERIODMAX = "periodMax";
/**
* periodUnits
*/
@Child(name = FIELD_PERIODUNITS, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {CodeDt.class})
@Description(shortDefinition = "s | min | h | d | wk | mo | a - unit of time (UCUM)", formalDefinition = "The units of time for the period in UCUM units.")
protected BoundCodeDt<UnitsOfTimeEnum> ourPeriodUnits;
public static final String FIELD_PERIODUNITS = "periodUnits";
/**
* when
*/
@Child(name = FIELD_WHEN, min = 0, max = 1, order = Child.REPLACE_PARENT, summary = true, type = {CodeDt.class})
@Description(shortDefinition = "Regular life events the event is tied to", formalDefinition = "A real world event that the occurrence of the event should be tied to.")
protected BoundCodeDt<EventTimingEnum> ourWhen;
public static final String FIELD_WHEN = "when";
@Override
public boolean isEmpty() {
return super.isEmpty() && ElementUtil.isEmpty(ourBounds, ourCount, ourDuration, ourDurationMax, ourDurationUnits, ourFrequency, ourFrequencyMax, ourPeriod, ourPeriodMax, ourPeriodUnits, ourWhen);
}
@Override
public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) {
return ElementUtil.allPopulatedChildElements(theType, ourBounds, ourCount, ourDuration, ourDurationMax, ourDurationUnits, ourFrequency, ourFrequencyMax, ourPeriod, ourPeriodMax, ourPeriodUnits, ourWhen);
}
public IDatatype _getBounds() {
return ourBounds;
}
public _Repeat _setBounds(IDatatype theValue) {
ourBounds = theValue;
return this;
}
public IntegerDt _getCount() {
if (ourCount == null)
ourCount = new IntegerDt();
return ourCount;
}
public _Repeat _setCount(IntegerDt theValue) {
ourCount = theValue;
return this;
}
public DecimalDt _getDuration() {
if (ourDuration == null)
ourDuration = new DecimalDt();
return ourDuration;
}
public _Repeat _setDuration(DecimalDt theValue) {
ourDuration = theValue;
return this;
}
public DecimalDt _getDurationMax() {
if (ourDurationMax == null)
ourDurationMax = new DecimalDt();
return ourDurationMax;
}
public _Repeat _setDurationMax(DecimalDt theValue) {
ourDurationMax = theValue;
return this;
}
public BoundCodeDt<UnitsOfTimeEnum> _getDurationUnits() {
if (ourDurationUnits == null)
ourDurationUnits = new BoundCodeDt<UnitsOfTimeEnum>(UnitsOfTimeEnum.VALUESET_BINDER);
return ourDurationUnits;
}
public _Repeat _setDurationUnits(BoundCodeDt<UnitsOfTimeEnum> theValue) {
ourDurationUnits = theValue;
return this;
}
public IntegerDt _getFrequency() {
if (ourFrequency == null)
ourFrequency = new IntegerDt();
return ourFrequency;
}
public _Repeat _setFrequency(IntegerDt theValue) {
ourFrequency = theValue;
return this;
}
public IntegerDt _getFrequencyMax() {
if (ourFrequencyMax == null)
ourFrequencyMax = new IntegerDt();
return ourFrequencyMax;
}
public _Repeat _setFrequencyMax(IntegerDt theValue) {
ourFrequencyMax = theValue;
return this;
}
public DecimalDt _getPeriod() {
if (ourPeriod == null)
ourPeriod = new DecimalDt();
return ourPeriod;
}
public _Repeat _setPeriod(DecimalDt theValue) {
ourPeriod = theValue;
return this;
}
public DecimalDt _getPeriodMax() {
if (ourPeriodMax == null)
ourPeriodMax = new DecimalDt();
return ourPeriodMax;
}
public _Repeat _setPeriodMax(DecimalDt theValue) {
ourPeriodMax = theValue;
return this;
}
public BoundCodeDt<UnitsOfTimeEnum> _getPeriodUnits() {
if (ourPeriodUnits == null)
ourPeriodUnits = new BoundCodeDt<UnitsOfTimeEnum>(UnitsOfTimeEnum.VALUESET_BINDER);
return ourPeriodUnits;
}
public _Repeat _setPeriodUnits(BoundCodeDt<UnitsOfTimeEnum> theValue) {
ourPeriodUnits = theValue;
return this;
}
public BoundCodeDt<EventTimingEnum> _getWhen() {
if (ourWhen == null)
ourWhen = new BoundCodeDt<EventTimingEnum>(EventTimingEnum.VALUESET_BINDER);
return ourWhen;
}
public _Repeat _setWhen(BoundCodeDt<EventTimingEnum> theValue) {
ourWhen = theValue;
return this;
}
@Override
@Deprecated
public IDatatype getBounds() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setBounds(IDatatype p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setCount(IntegerDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setCount(int p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDuration(DecimalDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDuration(double p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDuration(BigDecimal p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDuration(long p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationMax(DecimalDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationMax(double p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationMax(BigDecimal p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationMax(long p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationUnits(UnitsOfTimeEnum p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setDurationUnits(BoundCodeDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setFrequency(IntegerDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setFrequency(int p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setFrequencyMax(IntegerDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setFrequencyMax(int p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriod(DecimalDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriod(double p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriod(BigDecimal p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriod(long p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodMax(DecimalDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodMax(double p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodMax(BigDecimal p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodMax(long p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodUnits(UnitsOfTimeEnum p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setPeriodUnits(BoundCodeDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setWhen(EventTimingEnum p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Repeat setWhen(BoundCodeDt p0) {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BoundCodeDt getDurationUnitsElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BoundCodeDt getPeriodUnitsElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BoundCodeDt getWhenElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public DecimalDt getDurationElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public DecimalDt getDurationMaxElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public DecimalDt getPeriodElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public DecimalDt getPeriodMaxElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public IntegerDt getCountElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public IntegerDt getFrequencyElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public IntegerDt getFrequencyMaxElement() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Integer getCount() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Integer getFrequency() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public Integer getFrequencyMax() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public String getDurationUnits() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public String getPeriodUnits() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public String getWhen() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BigDecimal getDuration() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BigDecimal getDurationMax() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BigDecimal getPeriod() {
throw new UnsupportedOperationException("Deprecated method");
}
@Override
@Deprecated
public BigDecimal getPeriodMax() {
throw new UnsupportedOperationException("Deprecated method");
}
}
}
| 8,427 |
675 | <filename>dragonfly/exd/unittest_exd_utils.py<gh_stars>100-1000
"""
Unit tests for ed_utils.
-- <EMAIL>
"""
from __future__ import absolute_import
from __future__ import division
# pylint: disable=relative-import
# Local imports
from .exd_utils import random_sampling_cts, random_sampling_kmeans_cts
from ..utils.base_test_class import BaseTestClass, execute_tests
class EDUtilsTestCase(BaseTestClass):
""" Unit tests for generic functions ed_utils.py """
def setUp(self):
""" Sets up unit tests. """
self.lhs_data = [(1, 10), (2, 5), (4, 10), (10, 100)]
@classmethod
def _check_sample_sizes(cls, data, samples):
""" Data is a tuple of the form (dim, num_samples) ans samples is an ndarray."""
assert (data[1], data[0]) == samples.shape
def test_random_sampling(self):
""" Tests random sampling. """
self.report('Test random sampling.')
for data in self.lhs_data:
self._check_sample_sizes(data, random_sampling_cts(data[0], data[1]))
def test_random_sampling_kmeans(self):
""" Tests random sampling with k-means. """
self.report('Test random sampling with k-means.')
for data in self.lhs_data:
self._check_sample_sizes(data, random_sampling_kmeans_cts(data[0], data[1]))
if __name__ == '__main__':
execute_tests()
| 475 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#include <com/sun/star/xml/crypto/CipherID.hpp>
#include <XUnbufferedStream.hxx>
#include <EncryptionData.hxx>
#include <PackageConstants.hxx>
#include <ZipFile.hxx>
#include <EncryptedDataHeader.hxx>
#include <algorithm>
#include <string.h>
#include <osl/mutex.hxx>
#if 0
// for debugging purposes here
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <comphelper/processfactory.hxx>
using namespace ::com::sun::star;
#endif
using namespace ::com::sun::star;
using namespace com::sun::star::packages::zip::ZipConstants;
using namespace com::sun::star::io;
using namespace com::sun::star::uno;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::packages::zip::ZipIOException;
using ::rtl::OUString;
XUnbufferedStream::XUnbufferedStream(
const uno::Reference< lang::XMultiServiceFactory >& xFactory,
SotMutexHolderRef aMutexHolder,
ZipEntry & rEntry,
Reference < XInputStream > xNewZipStream,
const ::rtl::Reference< EncryptionData >& rData,
sal_Int8 nStreamMode,
sal_Bool bIsEncrypted,
const ::rtl::OUString& aMediaType,
sal_Bool bRecoveryMode )
: maMutexHolder( aMutexHolder.Is() ? aMutexHolder : SotMutexHolderRef( new SotMutexHolder ) )
, mxZipStream ( xNewZipStream )
, mxZipSeek ( xNewZipStream, UNO_QUERY )
, maEntry ( rEntry )
, mxData ( rData )
, mnBlockSize( 1 )
, maInflater ( sal_True )
, mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbFinished ( sal_False )
, mnHeaderToRead ( 0 )
, mnZipCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnMyCurrent ( 0 )
, mbCheckCRC( !bRecoveryMode )
{
mnZipCurrent = maEntry.nOffset;
if ( mbRawStream )
{
mnZipSize = maEntry.nMethod == DEFLATED ? maEntry.nCompressedSize : maEntry.nSize;
mnZipEnd = maEntry.nOffset + mnZipSize;
}
else
{
mnZipSize = maEntry.nSize;
mnZipEnd = maEntry.nMethod == DEFLATED ? maEntry.nOffset + maEntry.nCompressedSize : maEntry.nOffset + maEntry.nSize;
}
sal_Bool bHaveEncryptData = ( rData.is() && rData->m_aSalt.getLength() && rData->m_aInitVector.getLength() && rData->m_nIterationCount != 0 ) ? sal_True : sal_False;
sal_Bool bMustDecrypt = ( nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && bIsEncrypted ) ? sal_True : sal_False;
if ( bMustDecrypt )
{
m_xCipherContext = ZipFile::StaticGetCipher( xFactory, rData, false );
mnBlockSize = ( rData->m_nEncAlg == xml::crypto::CipherID::AES_CBC_W3C_PADDING ? 16 : 1 );
}
if ( bHaveEncryptData && mbWrappedRaw && bIsEncrypted )
{
// if we have the data needed to decrypt it, but didn't want it decrypted (or
// we couldn't decrypt it due to wrong password), then we prepend this
// data to the stream
// Make a buffer big enough to hold both the header and the data itself
maHeader.realloc ( n_ConstHeaderSize +
rData->m_aInitVector.getLength() +
rData->m_aSalt.getLength() +
rData->m_aDigest.getLength() +
aMediaType.getLength() * sizeof( sal_Unicode ) );
sal_Int8 * pHeader = maHeader.getArray();
ZipFile::StaticFillHeader( rData, rEntry.nSize, aMediaType, pHeader );
mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
}
}
// allows to read package raw stream
XUnbufferedStream::XUnbufferedStream(
const uno::Reference< lang::XMultiServiceFactory >& /*xFactory*/,
const Reference < XInputStream >& xRawStream,
const ::rtl::Reference< EncryptionData >& rData )
: maMutexHolder( new SotMutexHolder )
, mxZipStream ( xRawStream )
, mxZipSeek ( xRawStream, UNO_QUERY )
, mxData ( rData )
, mnBlockSize( 1 )
, maInflater ( sal_True )
, mbRawStream ( sal_False )
, mbWrappedRaw ( sal_False )
, mbFinished ( sal_False )
, mnHeaderToRead ( 0 )
, mnZipCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnMyCurrent ( 0 )
, mbCheckCRC( sal_False )
{
// for this scenario maEntry is not set !!!
OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!\n" );
// skip raw header, it must be already parsed to rData
mnZipCurrent = n_ConstHeaderSize + rData->m_aInitVector.getLength() +
rData->m_aSalt.getLength() + rData->m_aDigest.getLength();
try {
if ( mxZipSeek.is() )
mnZipSize = mxZipSeek->getLength();
} catch( Exception& )
{
// in case of problem the size will stay set to 0
}
mnZipEnd = mnZipCurrent + mnZipSize;
// the raw data will not be decrypted, no need for the cipher
// m_xCipherContext = ZipFile::StaticGetCipher( xFactory, rData, false );
}
XUnbufferedStream::~XUnbufferedStream()
{
}
sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
::osl::MutexGuard aGuard( maMutexHolder->GetMutex() );
sal_Int32 nRequestedBytes = nBytesToRead;
OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
if ( mnMyCurrent + nRequestedBytes > mnZipSize + maHeader.getLength() )
nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + maHeader.getLength() - mnMyCurrent );
sal_Int32 nRead = 0, nLastRead = 0, nTotal = 0;
aData.realloc ( nRequestedBytes );
if ( nRequestedBytes )
{
if ( mbRawStream )
{
sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
if ( mbWrappedRaw && mnHeaderToRead )
{
sal_Int16 nHeadRead = static_cast< sal_Int16 >(( nRequestedBytes > mnHeaderToRead ?
mnHeaderToRead : nRequestedBytes ));
rtl_copyMemory ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
mnHeaderToRead = mnHeaderToRead - nHeadRead;
if ( nHeadRead < nRequestedBytes )
{
sal_Int32 nToRead = nRequestedBytes - nHeadRead;
nToRead = ( nDiff < nToRead ) ? sal::static_int_cast< sal_Int32 >( nDiff ) : nToRead;
Sequence< sal_Int8 > aPureData( nToRead );
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes ( aPureData, nToRead );
mnZipCurrent += nRead;
aPureData.realloc( nRead );
if ( mbCheckCRC )
maCRC.update( aPureData );
aData.realloc( nHeadRead + nRead );
sal_Int8* pPureBuffer = aPureData.getArray();
sal_Int8* pBuffer = aData.getArray();
for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
}
nRead += nHeadRead;
}
else
{
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes (
aData,
static_cast < sal_Int32 > ( nDiff < nRequestedBytes ? nDiff : nRequestedBytes ) );
mnZipCurrent += nRead;
aData.realloc( nRead );
if ( mbWrappedRaw && mbCheckCRC )
maCRC.update( aData );
}
}
else
{
while ( 0 == ( nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead ) ) ||
( nRead + nLastRead != nRequestedBytes && mnZipCurrent < mnZipEnd ) )
{
nRead += nLastRead;
if ( nRead > nRequestedBytes )
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Should not be possible to read more then requested!" ) ),
Reference< XInterface >() );
if ( maInflater.finished() || maInflater.getLastInflateError() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
if ( maInflater.needsDictionary() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Dictionaries are not supported!" ) ),
Reference< XInterface >() );
sal_Int32 nDiff = static_cast< sal_Int32 >( mnZipEnd - mnZipCurrent );
if ( nDiff > 0 )
{
mxZipSeek->seek ( mnZipCurrent );
sal_Int32 nToRead = std::max( nRequestedBytes, static_cast< sal_Int32 >( 8192 ) );
if ( mnBlockSize > 1 )
nToRead = nToRead + mnBlockSize - nToRead % mnBlockSize;
nToRead = std::min( nDiff, nToRead );
sal_Int32 nZipRead = mxZipStream->readBytes( maCompBuffer, nToRead );
if ( nZipRead < nToRead )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "No expected data!" ) ),
Reference< XInterface >() );
mnZipCurrent += nZipRead;
// maCompBuffer now has the data, check if we need to decrypt
// before passing to the Inflater
if ( m_xCipherContext.is() )
{
if ( mbCheckCRC )
maCRC.update( maCompBuffer );
maCompBuffer = m_xCipherContext->convertWithCipherContext( maCompBuffer );
if ( mnZipCurrent == mnZipEnd )
{
uno::Sequence< sal_Int8 > aSuffix = m_xCipherContext->finalizeCipherContextAndDispose();
if ( aSuffix.getLength() )
{
sal_Int32 nOldLen = maCompBuffer.getLength();
maCompBuffer.realloc( nOldLen + aSuffix.getLength() );
rtl_copyMemory( maCompBuffer.getArray() + nOldLen, aSuffix.getConstArray(), aSuffix.getLength() );
}
}
}
maInflater.setInput ( maCompBuffer );
}
else
{
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
}
mnMyCurrent += nRead + nLastRead;
nTotal = nRead + nLastRead;
if ( nTotal < nRequestedBytes)
aData.realloc ( nTotal );
if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
{
if ( !m_xCipherContext.is() && !mbWrappedRaw )
maCRC.update( aData );
#if 0
// for debugging purposes here
if ( mbWrappedRaw )
{
if ( 0 )
{
uno::Reference< lang::XMultiServiceFactory > xFactory = comphelper::getProcessServiceFactory();
uno::Reference< ucb::XSimpleFileAccess > xAccess( xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ), uno::UNO_QUERY );
uno::Reference< io::XOutputStream > xOut = xAccess->openFileWrite( ::rtl::OUString::createFromAscii( "file:///d:/777/Encrypted/picture" ) );
xOut->writeBytes( aData );
xOut->closeOutput();
}
}
#endif
if ( mnZipSize + maHeader.getLength() == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
return nTotal;
}
sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
return readBytes ( aData, nMaxBytesToRead );
}
void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
if ( nBytesToSkip )
{
Sequence < sal_Int8 > aSequence ( nBytesToSkip );
readBytes ( aSequence, nBytesToSkip );
}
}
sal_Int32 SAL_CALL XUnbufferedStream::available( )
throw( NotConnectedException, IOException, RuntimeException)
{
return static_cast < sal_Int32 > ( mnZipSize - mnMyCurrent );
}
void SAL_CALL XUnbufferedStream::closeInput( )
throw( NotConnectedException, IOException, RuntimeException)
{
}
/*
void SAL_CALL XUnbufferedStream::seek( sal_Int64 location )
throw( IllegalArgumentException, IOException, RuntimeException)
{
}
sal_Int64 SAL_CALL XUnbufferedStream::getPosition( )
throw(IOException, RuntimeException)
{
return mnMyCurrent;
}
sal_Int64 SAL_CALL XUnbufferedStream::getLength( )
throw(IOException, RuntimeException)
{
return mnZipSize;
}
*/
| 5,769 |
586 | <reponame>sathishmscict/FastEasyMappting-Report
{
"charProperty": 99,
"unsignedCharProperty": 117,
"shortProperty": 1,
"unsignedShortProperty": 2,
"intProperty": 3,
"unsignedIntProperty": 4,
"integerProperty": 5,
"unsignedIntegerProperty": 6,
"longProperty": 7,
"unsignedLongProperty": 8,
"longLongProperty": 9,
"unsignedLongLongProperty": 10,
"floatProperty": 11.1,
"cgFloatProperty": 12.2,
"doubleProperty": 13.3,
"boolProperty": true
} | 166 |
392 | /*******************************************************************************
* Copyright (c) 2015
*
* 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.network.server.match;
import java.util.List;
import java.util.TimerTask;
import jsettlers.network.NetworkConstants;
import jsettlers.network.common.packets.ArrayOfMatchInfosPacket;
import jsettlers.network.common.packets.MatchInfoPacket;
import jsettlers.network.server.db.IDBFacade;
/**
* This {@link TimerTask} implementation gets the logged in players and sends them the open matches on every call to {@link #run()}.
*
* @author <NAME>
*
*/
public class MatchesListSendingTimerTask extends TimerTask {
private final IDBFacade db;
public MatchesListSendingTimerTask(IDBFacade db) {
this.db = db;
}
@Override
public void run() {
List<Player> loggedInPlayers = db.getPlayers(EPlayerState.LOGGED_IN);
ArrayOfMatchInfosPacket packet = getArrayOfMatchInfosPacket();
for (Player currPlayer : loggedInPlayers) {
sendMatchesPacketToPlayer(currPlayer, packet);
}
}
private void sendMatchesPacketToPlayer(Player player, ArrayOfMatchInfosPacket arrayOfMatchesPacket) {
player.sendPacket(NetworkConstants.ENetworkKey.ARRAY_OF_MATCHES, arrayOfMatchesPacket);
}
private ArrayOfMatchInfosPacket getArrayOfMatchInfosPacket() {
List<Match> matches = db.getJoinableMatches();
MatchInfoPacket[] matchInfoPackets = new MatchInfoPacket[matches.size()];
int i = 0;
for (Match curr : matches) {
matchInfoPackets[i] = new MatchInfoPacket(curr);
i++;
}
return new ArrayOfMatchInfosPacket(matchInfoPackets);
}
public void sendMatchesTo(Player player) {
ArrayOfMatchInfosPacket arrayOfMatchesPacket = getArrayOfMatchInfosPacket();
sendMatchesPacketToPlayer(player, arrayOfMatchesPacket);
}
}
| 845 |
523 |
// Copyright <NAME> 2019.
// 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)
#if !defined(CNL_IMPL_NUM_TRAITS_SET_REP_H)
#define CNL_IMPL_NUM_TRAITS_SET_REP_H
/// compositional numeric library
namespace cnl {
/// \brief meta-function object that transforms a component from one Rep type to another
///
/// \tparam T component to transform
/// \tparam OutRep new representational type being wrapped by the resultant type
///
/// \sa to_rep, from_value, set_tag, rep
template<typename T, typename OutRep>
struct set_rep;
namespace _impl {
template<typename T, class OutRep>
using set_rep_t = typename set_rep<T, OutRep>::type;
}
}
#endif // CNL_IMPL_NUM_TRAITS_SET_REP_H
| 338 |
335 | {
"word": "Jactitation",
"definitions": [
"The restless tossing of the body in illness.",
"The twitching of a limb or muscle."
],
"parts-of-speech": "Noun"
} | 80 |
2,843 | <filename>business/MusicBusiness/src/main/java/com/ycbjie/music/utils/share/BaseSharePolicy.java
package com.ycbjie.music.utils.share;
import android.content.Context;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211/YCBlogs
* time : 2017/01/30
* desc : 分享弹窗,主要是为了练习策略者模式
* revise:
* </pre>
*/
public class BaseSharePolicy implements SharePolicy{
@Override
public void share(String type, ShareTypeBean shareTypeBean, Context context) {
switch (type){
case ShareComment.ShareViewType.SHARE_FRIEND: // 好友
shareFriend(shareTypeBean , context);
break;
case ShareComment.ShareViewType.SHARE_FRIEND_CIRCLE: // 朋友圈
shareFriendCircle(shareTypeBean , context);
break;
case ShareComment.ShareViewType.SHARE_CREATE_POSTER: // 生成海报图
shareCreatePoster(shareTypeBean , context);
break;
case ShareComment.ShareViewType.SHARE_SAVE_PIC: // 保存图片
shareSaveImg(shareTypeBean , context);
break;
default:
break;
}
}
void shareFriend(ShareTypeBean shareTypeBean, Context context) {
}
void shareFriendCircle(ShareTypeBean shareTypeBean, Context context) {
}
void shareCreatePoster(ShareTypeBean shareTypeBean, Context context) {
}
void shareSaveImg(ShareTypeBean shareTypeBean, Context context) {
}
}
| 743 |
3,263 | <reponame>arouel/immutables
/*
* Copyright 2020 Immutables Authors and Contributors
*
* 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.immutables.criteria.geode;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import org.immutables.criteria.backend.KeyExtractor;
import org.immutables.criteria.expression.Call;
import org.immutables.criteria.expression.Constant;
import org.immutables.criteria.expression.Expression;
import org.immutables.criteria.expression.Operators;
import org.immutables.criteria.expression.Path;
import org.immutables.criteria.expression.Visitors;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Tries to detect if current filter is based only on keys (IDs) and extracts them if possible.
* Useful in cases when these is a more efficient {@code getByKey} / {@code deleteByKey} API provided
* by backend.
*
* <p><strong>Usage example</strong> Geode (currently) doesn't support delete by query syntax ({@code DELETE ... WHERE ...}) and elements have to be
* removed explicitly by key (using {@link Map#remove(Object)} or {@code Region.removeAll()} API). With this method
* one can extract keys from expression and use delete by key API if delete query has only IDs.
*
* <p>Example:
* <pre>
* {@code
* key = 123 (valid)
* key in [1, 2, 3] (valid)
*
* key not in [1, 2, 3] (invalid since keys are unknown)
* key != 1 (invalid since keys are unknown)
* key > 1 (invalid since keys are unknown)
* }
* </pre>
*/
abstract class KeyLookupAnalyzer {
/**
* Analyze current expression and check if it has {@code (id = 1) or (id in [...])}
* format.
*
* @param filter expression to analyze
*/
public abstract Result analyze(Expression filter);
/**
* Result of analyzing filter expression
*/
public interface Result {
/**
* Wherever current expression can be converted to a key-lookup API similar to {@code key = 123} or {@code key in [1, 2, 3]}
*/
boolean isOptimizable();
/**
* Return values present in {@code key = 1} or {@code key in [1, 2, 3]} call
*
* Always check {@link #isOptimizable()} before using this method
*
* @return list of values (can be empty, with one or more elements)
* @throws UnsupportedOperationException if keys could not be extracted
*/
Set<?> values();
}
/**
* Always returns non-optimizable result
*/
static KeyLookupAnalyzer disabled() {
return new KeyLookupAnalyzer() {
@Override
public Result analyze(Expression filter) {
return NOT_OPTIMIZABLE;
}
};
}
/**
* Create analyzer based on existing extractor. Currently only
* single key is supported and key expression has to be {@link Path}.
*/
static KeyLookupAnalyzer fromExtractor(KeyExtractor extractor) {
Objects.requireNonNull(extractor, "extractor");
KeyExtractor.KeyMetadata metadata = extractor.metadata();
if (!(metadata.isExpression() && metadata.isKeyDefined()) || metadata.keys().size() > 1) {
return disabled();
}
Optional<Path> path = Visitors.maybePath(metadata.keys().get(0));
return path.map(KeyLookupAnalyzer::forPath).orElse(disabled());
}
/**
* Create optimizer when id attribute is known as {@link Path}
*/
static KeyLookupAnalyzer forPath(Path idPath) {
Objects.requireNonNull(idPath, "idPath");
return new PathAnalyzer(idPath);
}
/**
* Default optimization based on {@link Path}
*/
private static class PathAnalyzer extends KeyLookupAnalyzer {
private final Path idPath;
private PathAnalyzer(Path idPath) {
Objects.requireNonNull(idPath, "id");
Preconditions.checkArgument(!idPath.members().isEmpty(), "Path %s does not have any members", idPath);
this.idPath = idPath;
}
@Override
public Result analyze(Expression filter) {
Objects.requireNonNull(filter, "filter");
if (!(filter instanceof Call)) {
return NOT_OPTIMIZABLE;
}
final Call predicate = (Call) filter;
// require "equal" or "in" operators
if (!(predicate.operator() == Operators.EQUAL || predicate.operator() == Operators.IN)) {
return NOT_OPTIMIZABLE;
}
final List<Expression> args = predicate.arguments();
Preconditions.checkArgument(args.size() == 2, "Expected size 2 but got %s for %s",
args.size(), predicate);
if (!(args.get(0) instanceof Path && args.get(1) instanceof Constant)) {
// second argument should be a constant
return NOT_OPTIMIZABLE;
}
final Path path = Visitors.toPath(predicate.arguments().get(0));
if (!idPath.equals(path)) {
return NOT_OPTIMIZABLE;
}
// extract values
Set<?> values = ImmutableSet.copyOf(Visitors.toConstant(predicate.arguments().get(1)).values());
return new Result() {
@Override
public boolean isOptimizable() {
return true;
}
@Override
public Set<?> values() {
return values;
}
};
}
}
/**
* Result when optimization is not possible
*/
private static final Result NOT_OPTIMIZABLE = new Result() {
@Override
public boolean isOptimizable() {
return false;
}
@Override
public Set<?> values() {
throw new UnsupportedOperationException("Expression can not be optimized for key lookup." +
" Did you check isOptimizable() method ? ");
}
};
}
| 2,109 |
679 | <reponame>Grosskopf/openoffice<filename>main/svgio/inc/svgio/svgreader/svgpolynode.hxx
/**************************************************************
*
* 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.
*
*************************************************************/
#ifndef INCLUDED_SVGIO_SVGREADER_SVGPOLYNODE_HXX
#define INCLUDED_SVGIO_SVGREADER_SVGPOLYNODE_HXX
#include <svgio/svgiodllapi.h>
#include <svgio/svgreader/svgnode.hxx>
#include <svgio/svgreader/svgstyleattributes.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace svgio
{
namespace svgreader
{
class SvgPolyNode : public SvgNode
{
private:
/// use styles
SvgStyleAttributes maSvgStyleAttributes;
/// variable scan values, dependent of given XAttributeList
basegfx::B2DPolygon* mpPolygon;
basegfx::B2DHomMatrix* mpaTransform;
/// bitfield
bool mbIsPolyline : 1; // true = polyline, false = polygon
public:
SvgPolyNode(
SvgDocument& rDocument,
SvgNode* pParent,
bool bIsPolyline);
virtual ~SvgPolyNode();
virtual const SvgStyleAttributes* getSvgStyleAttributes() const;
virtual void parseAttribute(const rtl::OUString& rTokenName, SVGToken aSVGToken, const rtl::OUString& aContent);
virtual void decomposeSvgNode(drawinglayer::primitive2d::Primitive2DSequence& rTarget, bool bReferenced) const;
/// type read access
bool isPolyline() const { return mbIsPolyline; }
/// Polygon content, set if found in current context
const basegfx::B2DPolygon* getPolygon() const { return mpPolygon; }
void setPolygon(const basegfx::B2DPolygon* pPolygon = 0) { if(mpPolygon) delete mpPolygon; mpPolygon = 0; if(pPolygon) mpPolygon = new basegfx::B2DPolygon(*pPolygon); }
/// transform content, set if found in current context
const basegfx::B2DHomMatrix* getTransform() const { return mpaTransform; }
void setTransform(const basegfx::B2DHomMatrix* pMatrix = 0) { if(mpaTransform) delete mpaTransform; mpaTransform = 0; if(pMatrix) mpaTransform = new basegfx::B2DHomMatrix(*pMatrix); }
};
} // end of namespace svgreader
} // end of namespace svgio
//////////////////////////////////////////////////////////////////////////////
#endif //INCLUDED_SVGIO_SVGREADER_SVGPOLYNODE_HXX
// eof
| 1,253 |
703 | <filename>libpeconv/include/peconv/load_config_util.h
/**
* @file
* @brief Fetching Load Config Directory and recognizing its version.
*/
#pragma once
#include <windows.h>
#include "buffer_util.h"
#include "load_config_defs.h"
namespace peconv {
/**
A version of Load Config Directory.
*/
typedef enum {
LOAD_CONFIG_NONE = 0, /**< Load Config Directory not found */
LOAD_CONFIG_W7_VER = 7, /**< Load Config Directory in the Windows 7 version */
LOAD_CONFIG_W8_VER = 8, /**< Load Config Directory in the Windows 8 version */
LOAD_CONFIG_W10_VER = 10, /**< Load Config Directory in the Windows 10 version */
LOAD_CONFIG_UNK_VER = -1 /**< Load Config Directory in an unknown version */
} t_load_config_ver;
/**
Get a pointer to the Load Config Directory within the given PE.
\param buffer : a buffer containing the PE file in a Virtual format
\param buf_size : size of the buffer
\return a pointer to the Load Config Directory, NULL if the given PE does not have this directory
*/
BYTE* get_load_config_ptr(BYTE* buffer, size_t buf_size);
/**
Detect which version of Load Config Directory was used in the given PE.
\param buffer : a buffer containing the PE file in a Virtual format
\param buf_size : size of the buffer
\param ld_config_ptr : pointer to the Load Config Directory within the given PE
\return detected version of Load Config Directory
*/
t_load_config_ver get_load_config_version(BYTE* buffer, size_t buf_size, BYTE* ld_config_ptr);
}; // namespace peconv
| 542 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include "SerializationInteropTest.h"
using namespace Common;
using namespace std;
using namespace NativeAndManagedSerializationInteropTest;
int __cdecl wmain(int argc, __in_ecount(argc) wchar_t* argv[])
{
auto traceCode = TraceTaskCodes::Common;
StringLiteral traceType = "SerializationInteropTestExe";
Common::TraceNoise(traceCode, traceType, "argc: {0}", argc);
/// Too few argument?
if (argc < 4)
{
Trace.WriteError(traceType, "Error: Too few arguments. Expected 4, found {0}", argc);
return ErrorCodeValue::InvalidArgument;
}
Common::TraceNoise(traceCode, traceType, "arg1: {0}, arg2: {1}, arg3: {2}", argv[1], argv[2], argv[3]);
ErrorCode error = NativeAndManagedSerializationInteropTest::DeserializeAndSerialize(argv[1], argv[2], argv[3]);
if (!error.IsSuccess())
{
Trace.WriteError(traceType, "Error: {0}", error.Message);
Trace.WriteError(traceType, "Arguments were: arg1: {0}, arg2: {1}, arg3: {2}", argv[1], argv[2], argv[3]);
return -1;
}
Trace.WriteInfo(traceType, "Exiting with success.");
return 0;
}
| 506 |
619 | /*
* Author: <NAME> <<EMAIL>>
* Copyright (c) 2016 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
#pragma once
#include <string>
#include <iostream>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <jpeglib.h>
#include <linux/videodev2.h>
#define VCAP_DEFAULT_VIDEODEV "/dev/video0"
#define VCAP_DEFAULT_OUTPUTFILE "vcap.jpg"
#define VCAP_DEFAULT_WIDTH 640
#define VCAP_DEFAULT_HEIGHT 480
#define VCAP_DEFAULT_JPEG_QUALITY 99
namespace upm {
/**
* @brief Video Frame Capture and JPEG Image Save Library
*
* Take a snapshot from a USB video camera and save as a JPEG
*
* @defgroup vcap libupm-vcap
* @ingroup video
*/
/**
* @library vcap
* @sensor vcap
* @comname Video Frame Capture and Image Save Utility
* @type video
*
* @brief API for the Video Capture driver
*
* This UPM module captures a still frame from a Linux V4L device,
* such as a USB webcam, and and then allows you to save it as a
* JPEG image into a file.
*
* The camera and driver in use must support streaming, mmap-able
* buffers and must provide data in YUYV format. This should
* encompass most video cameras out there. It has been tested
* with a few off the shelf cameras without any problems.
*
* @snippet vcap.cxx Interesting
*/
class VCAP {
public:
/**
* VCAP object constructor
*
* @param videoDev The path to the video device, default is /dev/video0.
*/
VCAP(std::string videoDev=VCAP_DEFAULT_VIDEODEV);
/**
* VCAP object destructor
*/
~VCAP();
/**
* Set the desired resolution of the output image. Note, this is
* a hint to the underlying video driver. The video driver is
* free to lower the specified resolution if the hardware cannot
* support it. You can use getHeight() and getWidth() after
* calling this method to see what the video driver chose.
*
* @param width The desired width of the image.
* @param width The desired height of the image.
* @return true if the operation succeeded, false otherwise.
*/
bool setResolution(int width, int height);
/**
* Capture an image from the camera.
*
* @return true if the operation succeeded, false otherwise.
*/
bool captureImage();
/**
* Save the captured image (created with captureImage()) to a file
* in JPEG format. The file will be overwritten if it already
* exists.
*
* @param filename The name of the file in which to store the image.
* @return true if the operation succeeded, false otherwise.
*/
bool saveImage(std::string filename=VCAP_DEFAULT_OUTPUTFILE);
/**
* Return the current width of the image. You can use this method
* to determine if the video driver downgraded it after a call to
* setResolution().
*
* @return true Current width of capture.
*/
int getWidth() const
{
return m_width;
};
/**
* Return the current height of the image. You can use this method
* to determine if the video driver downgraded it after a call to
* setResolution().
*
* @return true Current height of capture.
*/
int getHeight() const
{
return m_height;
};
/**
* Set the JPEG quality.
*
* @param quality A number between 0-100, with higher numbers
* meaning higher quality. Numbers less than 0 will be clamped to
* 0, numbers higher than 100 will be clamped to 100.
*/
void setJPGQuality(unsigned int quality);
/**
* Get the current JPEG quality setting.
*
* @return the current JPEG quality setting.
*/
int getJPGQuality() const
{
return m_jpgQuality;
};
/**
* Enable or disable debugging output.
*
* @param enable true to enable debugging, false otherwise
*/
void setDebug(bool enable)
{
m_debugging = enable;
};
protected:
// open the device and check that it meats minimum requirements
bool initVideoDevice();
// make sure device is streamable, supports mmap and capture
bool checkCapabilities();
// read the mmapped buffer in YUYV format and create a jpeg image
bool YUYV2JPEG(FILE *file);
// buffer management
bool allocBuffer();
void releaseBuffer();
// does the actual capture
bool doCaptureImage();
private:
// internal ioctl
int xioctl(int fd, int request, void* argp);
std::string m_videoDevice;
// our file descriptor to the video device
int m_fd;
// v4l info
struct v4l2_capability m_caps;
struct v4l2_format m_format;
// our mmaped buffer
unsigned char *m_buffer;
size_t m_bufferLen;
// the resolution and quality
int m_width;
int m_height;
int m_jpgQuality;
// at least one image captured with current settings?
bool m_imageCaptured;
// are we debugging?
bool m_debugging;
};
}
| 1,888 |
8,629 | <filename>src/Interpreters/applyTableOverride.cpp
#include <Interpreters/applyTableOverride.h>
#include <Parsers/ASTCreateQuery.h>
#include <Parsers/ASTTableOverrides.h>
#include <Parsers/ASTColumnDeclaration.h>
#include <Parsers/ASTIndexDeclaration.h>
#include <Parsers/ASTConstraintDeclaration.h>
#include <Parsers/ASTProjectionDeclaration.h>
namespace DB
{
void applyTableOverrideToCreateQuery(const ASTTableOverride & override, ASTCreateQuery * create_query)
{
if (auto * columns = override.columns)
{
if (!create_query->columns_list)
create_query->set(create_query->columns_list, std::make_shared<ASTColumns>());
if (columns->columns)
{
for (const auto & override_column_ast : columns->columns->children)
{
auto * override_column = override_column_ast->as<ASTColumnDeclaration>();
if (!override_column)
continue;
if (!create_query->columns_list->columns)
create_query->columns_list->set(create_query->columns_list->columns, std::make_shared<ASTExpressionList>());
auto & dest_children = create_query->columns_list->columns->children;
auto exists = std::find_if(dest_children.begin(), dest_children.end(), [&](ASTPtr node) -> bool
{
return node->as<ASTColumnDeclaration>()->name == override_column->name;
});
/// For columns, only allow adding ALIAS (non-physical) for now.
/// TODO: This logic should instead be handled by validation that is
/// executed from InterpreterCreateQuery / InterpreterAlterQuery.
if (exists == dest_children.end())
{
if (override_column->default_specifier == "ALIAS")
dest_children.emplace_back(override_column_ast);
}
else
dest_children[exists - dest_children.begin()] = override_column_ast;
}
}
if (columns->indices)
{
for (const auto & override_index_ast : columns->indices->children)
{
auto * override_index = override_index_ast->as<ASTIndexDeclaration>();
if (!override_index)
continue;
if (!create_query->columns_list->indices)
create_query->columns_list->set(create_query->columns_list->indices, std::make_shared<ASTExpressionList>());
auto & dest_children = create_query->columns_list->indices->children;
auto exists = std::find_if(dest_children.begin(), dest_children.end(), [&](ASTPtr node) -> bool
{
return node->as<ASTIndexDeclaration>()->name == override_index->name;
});
if (exists == dest_children.end())
dest_children.emplace_back(override_index_ast);
else
dest_children[exists - dest_children.begin()] = override_index_ast;
}
}
if (columns->constraints)
{
for (const auto & override_constraint_ast : columns->constraints->children)
{
auto * override_constraint = override_constraint_ast->as<ASTConstraintDeclaration>();
if (!override_constraint)
continue;
if (!create_query->columns_list->constraints)
create_query->columns_list->set(create_query->columns_list->constraints, std::make_shared<ASTExpressionList>());
auto & dest_children = create_query->columns_list->constraints->children;
auto exists = std::find_if(dest_children.begin(), dest_children.end(), [&](ASTPtr node) -> bool
{
return node->as<ASTConstraintDeclaration>()->name == override_constraint->name;
});
if (exists == dest_children.end())
dest_children.emplace_back(override_constraint_ast);
else
dest_children[exists - dest_children.begin()] = override_constraint_ast;
}
}
if (columns->projections)
{
for (const auto & override_projection_ast : columns->projections->children)
{
auto * override_projection = override_projection_ast->as<ASTProjectionDeclaration>();
if (!override_projection)
continue;
if (!create_query->columns_list->projections)
create_query->columns_list->set(create_query->columns_list->projections, std::make_shared<ASTExpressionList>());
auto & dest_children = create_query->columns_list->projections->children;
auto exists = std::find_if(dest_children.begin(), dest_children.end(), [&](ASTPtr node) -> bool
{
return node->as<ASTProjectionDeclaration>()->name == override_projection->name;
});
if (exists == dest_children.end())
dest_children.emplace_back(override_projection_ast);
else
dest_children[exists - dest_children.begin()] = override_projection_ast;
}
}
}
if (auto * storage = override.storage)
{
if (!create_query->storage)
create_query->set(create_query->storage, std::make_shared<ASTStorage>());
if (storage->partition_by)
create_query->storage->set(create_query->storage->partition_by, storage->partition_by->clone());
if (storage->primary_key)
create_query->storage->set(create_query->storage->primary_key, storage->primary_key->clone());
if (storage->order_by)
create_query->storage->set(create_query->storage->order_by, storage->order_by->clone());
if (storage->sample_by)
create_query->storage->set(create_query->storage->sample_by, storage->sample_by->clone());
if (storage->ttl_table)
create_query->storage->set(create_query->storage->ttl_table, storage->ttl_table->clone());
// No support for overriding ENGINE and SETTINGS
}
}
}
| 2,963 |
2,338 | <filename>clang/test/Analysis/CheckThatArraySubsciptNodeIsNotCollected.cpp
// RUN: %clang_analyze_cc1 -analyzer-checker=core -analyzer-output=text -verify %s
class A {
public:
int method();
};
A *foo();
void bar(A *);
int index;
// We want to check here that the notes about the origins of the null pointer
// (array[index] = foo()) will get to the final report.
//
// The analyzer used to drop exploded nodes for array subscripts when it was
// time to collect redundant nodes. This GC-like mechanism kicks in only when
// the exploded graph is large enough (>1K nodes). For this reason, 'index'
// is a global variable, and the sink point is inside of a loop.
void test() {
A *array[42];
A *found;
for (index = 0; (array[index] = foo()); ++index) { // expected-note {{Loop condition is false. Execution continues on line 34}}
// expected-note@-1 {{Value assigned to 'index'}}
// expected-note@-2 {{Assigning value}}
// expected-note@-3 {{Assuming pointer value is null}}
if (array[0])
break;
}
do {
found = array[index]; // expected-note {{Null pointer value stored to 'found'}}
if (found->method()) // expected-warning {{Called C++ object pointer is null [core.CallAndMessage]}}
// expected-note@-1 {{Called C++ object pointer is null}}
bar(found);
} while (--index);
}
| 430 |
705 | package week03_part01.solution;
public abstract class Instrument
{
public int volume;
public abstract void tune();
public void setVolume(int volume)
{
this.volume = volume;
}
public int getVolume()
{
return this.volume;
}
}
| 85 |
5,964 | <gh_stars>1000+
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMutex.h"
#include "SkPath.h"
#include "SkPathOpsDebug.h"
#include "SkString.h"
#if DEBUG_VALIDATE
extern bool FLAGS_runFail;
#endif
#if DEBUG_SORT
int SkPathOpsDebug::gSortCountDefault = SK_MaxS32;
int SkPathOpsDebug::gSortCount;
#endif
#if DEBUG_ACTIVE_OP
const char* SkPathOpsDebug::kPathOpStr[] = {"diff", "sect", "union", "xor"};
#endif
#if defined SK_DEBUG || !FORCE_RELEASE
const char* SkPathOpsDebug::kLVerbStr[] = {"", "line", "quad", "cubic"};
#if defined(SK_DEBUG) || !FORCE_RELEASE
int SkPathOpsDebug::gContourID = 0;
int SkPathOpsDebug::gSegmentID = 0;
#endif
bool SkPathOpsDebug::ChaseContains(const SkTDArray<SkOpSpanBase* >& chaseArray,
const SkOpSpanBase* span) {
for (int index = 0; index < chaseArray.count(); ++index) {
const SkOpSpanBase* entry = chaseArray[index];
if (entry == span) {
return true;
}
}
return false;
}
void SkPathOpsDebug::MathematicaIze(char* str, size_t bufferLen) {
size_t len = strlen(str);
bool num = false;
for (size_t idx = 0; idx < len; ++idx) {
if (num && str[idx] == 'e') {
if (len + 2 >= bufferLen) {
return;
}
memmove(&str[idx + 2], &str[idx + 1], len - idx);
str[idx] = '*';
str[idx + 1] = '^';
++len;
}
num = str[idx] >= '0' && str[idx] <= '9';
}
}
bool SkPathOpsDebug::ValidWind(int wind) {
return wind > SK_MinS32 + 0xFFFF && wind < SK_MaxS32 - 0xFFFF;
}
void SkPathOpsDebug::WindingPrintf(int wind) {
if (wind == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", wind);
}
}
#endif // defined SK_DEBUG || !FORCE_RELEASE
#if DEBUG_SHOW_TEST_NAME
void* SkPathOpsDebug::CreateNameStr() {
return SkNEW_ARRAY(char, DEBUG_FILENAME_STRING_LENGTH);
}
void SkPathOpsDebug::DeleteNameStr(void* v) {
SkDELETE_ARRAY(reinterpret_cast<char* >(v));
}
void SkPathOpsDebug::BumpTestName(char* test) {
char* num = test + strlen(test);
while (num[-1] >= '0' && num[-1] <= '9') {
--num;
}
if (num[0] == '\0') {
return;
}
int dec = atoi(num);
if (dec == 0) {
return;
}
++dec;
SK_SNPRINTF(num, DEBUG_FILENAME_STRING_LENGTH - (num - test), "%d", dec);
}
#endif
static void show_function_header(const char* functionName) {
SkDebugf("\nstatic void %s(skiatest::Reporter* reporter, const char* filename) {\n", functionName);
if (strcmp("skphealth_com76", functionName) == 0) {
SkDebugf("found it\n");
}
}
static const char* gOpStrs[] = {
"kDifference_SkPathOp",
"kIntersect_SkPathOp",
"kUnion_SkPathOp",
"kXor_PathOp",
"kReverseDifference_SkPathOp",
};
const char* SkPathOpsDebug::OpStr(SkPathOp op) {
return gOpStrs[op];
}
static void show_op(SkPathOp op, const char* pathOne, const char* pathTwo) {
SkDebugf(" testPathOp(reporter, %s, %s, %s, filename);\n", pathOne, pathTwo, gOpStrs[op]);
SkDebugf("}\n");
}
SK_DECLARE_STATIC_MUTEX(gTestMutex);
void SkPathOpsDebug::ShowPath(const SkPath& a, const SkPath& b, SkPathOp shapeOp,
const char* testName) {
SkAutoMutexAcquire ac(gTestMutex);
show_function_header(testName);
ShowOnePath(a, "path", true);
ShowOnePath(b, "pathB", true);
show_op(shapeOp, "path", "pathB");
}
#include "SkPathOpsTypes.h"
#ifdef SK_DEBUG
bool SkOpGlobalState::debugRunFail() const {
#if DEBUG_VALIDATE
return FLAGS_runFail;
#else
return false;
#endif
}
#endif
#include "SkPathOpsCubic.h"
#include "SkPathOpsQuad.h"
SkDCubic SkDQuad::debugToCubic() const {
SkDCubic cubic;
cubic[0] = fPts[0];
cubic[2] = fPts[1];
cubic[3] = fPts[2];
cubic[1].fX = (cubic[0].fX + cubic[2].fX * 2) / 3;
cubic[1].fY = (cubic[0].fY + cubic[2].fY * 2) / 3;
cubic[2].fX = (cubic[3].fX + cubic[2].fX * 2) / 3;
cubic[2].fY = (cubic[3].fY + cubic[2].fY * 2) / 3;
return cubic;
}
#include "SkOpAngle.h"
#include "SkOpCoincidence.h"
#include "SkOpSegment.h"
SkOpAngle* SkOpSegment::debugLastAngle() {
SkOpAngle* result = NULL;
SkOpSpan* span = this->head();
do {
if (span->toAngle()) {
SkASSERT(!result);
result = span->toAngle();
}
} while ((span = span->next()->upCastable()));
SkASSERT(result);
return result;
}
void SkOpSegment::debugReset() {
this->init(this->fPts, this->fWeight, this->contour(), this->verb());
}
#if DEBUG_ACTIVE_SPANS
void SkOpSegment::debugShowActiveSpans() const {
debugValidate();
if (done()) {
return;
}
int lastId = -1;
double lastT = -1;
const SkOpSpan* span = &fHead;
do {
if (span->done()) {
continue;
}
if (lastId == this->debugID() && lastT == span->t()) {
continue;
}
lastId = this->debugID();
lastT = span->t();
SkDebugf("%s id=%d", __FUNCTION__, this->debugID());
SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
for (int vIndex = 1; vIndex <= SkPathOpsVerbToPoints(fVerb); ++vIndex) {
SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
}
if (SkPath::kConic_Verb == fVerb) {
SkDebugf(" %1.9gf", fWeight);
}
const SkOpPtT* ptT = span->ptT();
SkDebugf(") t=%1.9g (%1.9g,%1.9g)", ptT->fT, ptT->fPt.fX, ptT->fPt.fY);
SkDebugf(" tEnd=%1.9g", span->next()->t());
if (span->windSum() == SK_MinS32) {
SkDebugf(" windSum=?");
} else {
SkDebugf(" windSum=%d", span->windSum());
}
if (span->oppValue() && span->oppSum() == SK_MinS32) {
SkDebugf(" oppSum=?");
} else if (span->oppValue() || span->oppSum() != SK_MinS32) {
SkDebugf(" oppSum=%d", span->oppSum());
}
SkDebugf(" windValue=%d", span->windValue());
if (span->oppValue() || span->oppSum() != SK_MinS32) {
SkDebugf(" oppValue=%d", span->oppValue());
}
SkDebugf("\n");
} while ((span = span->next()->upCastable()));
}
#endif
#if DEBUG_MARK_DONE
void SkOpSegment::debugShowNewWinding(const char* fun, const SkOpSpan* span, int winding) {
const SkPoint& pt = span->ptT()->fPt;
SkDebugf("%s id=%d", fun, this->debugID());
SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
for (int vIndex = 1; vIndex <= SkPathOpsVerbToPoints(fVerb); ++vIndex) {
SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
}
SkDebugf(") t=%1.9g [%d] (%1.9g,%1.9g) tEnd=%1.9g newWindSum=",
span->t(), span->debugID(), pt.fX, pt.fY, span->next()->t());
if (winding == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", winding);
}
SkDebugf(" windSum=");
if (span->windSum() == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", span->windSum());
}
SkDebugf(" windValue=%d\n", span->windValue());
}
void SkOpSegment::debugShowNewWinding(const char* fun, const SkOpSpan* span, int winding,
int oppWinding) {
const SkPoint& pt = span->ptT()->fPt;
SkDebugf("%s id=%d", fun, this->debugID());
SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
for (int vIndex = 1; vIndex <= SkPathOpsVerbToPoints(fVerb); ++vIndex) {
SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
}
SkDebugf(") t=%1.9g [%d] (%1.9g,%1.9g) tEnd=%1.9g newWindSum=",
span->t(), span->debugID(), pt.fX, pt.fY, span->next()->t(), winding, oppWinding);
if (winding == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", winding);
}
SkDebugf(" newOppSum=");
if (oppWinding == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", oppWinding);
}
SkDebugf(" oppSum=");
if (span->oppSum() == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", span->oppSum());
}
SkDebugf(" windSum=");
if (span->windSum() == SK_MinS32) {
SkDebugf("?");
} else {
SkDebugf("%d", span->windSum());
}
SkDebugf(" windValue=%d oppValue=%d\n", span->windValue(), span->oppValue());
}
#endif
#if DEBUG_ANGLE
SkString SkOpAngle::debugPart() const {
SkString result;
switch (this->segment()->verb()) {
case SkPath::kLine_Verb:
result.printf(LINE_DEBUG_STR " id=%d", LINE_DEBUG_DATA(fCurvePart),
this->segment()->debugID());
break;
case SkPath::kQuad_Verb:
result.printf(QUAD_DEBUG_STR " id=%d", QUAD_DEBUG_DATA(fCurvePart),
this->segment()->debugID());
break;
case SkPath::kConic_Verb:
result.printf(CONIC_DEBUG_STR " id=%d",
CONIC_DEBUG_DATA(fCurvePart, fCurvePart.fConic.fWeight),
this->segment()->debugID());
break;
case SkPath::kCubic_Verb:
result.printf(CUBIC_DEBUG_STR " id=%d", CUBIC_DEBUG_DATA(fCurvePart),
this->segment()->debugID());
break;
default:
SkASSERT(0);
}
return result;
}
#endif
#if DEBUG_SORT
void SkOpAngle::debugLoop() const {
const SkOpAngle* first = this;
const SkOpAngle* next = this;
do {
next->dumpOne(true);
SkDebugf("\n");
next = next->fNext;
} while (next && next != first);
next = first;
do {
next->debugValidate();
next = next->fNext;
} while (next && next != first);
}
#endif
void SkOpAngle::debugValidate() const {
#if DEBUG_VALIDATE
const SkOpAngle* first = this;
const SkOpAngle* next = this;
int wind = 0;
int opp = 0;
int lastXor = -1;
int lastOppXor = -1;
do {
if (next->unorderable()) {
return;
}
const SkOpSpan* minSpan = next->start()->starter(next->end());
if (minSpan->windValue() == SK_MinS32) {
return;
}
bool op = next->segment()->operand();
bool isXor = next->segment()->isXor();
bool oppXor = next->segment()->oppXor();
SkASSERT(!DEBUG_LIMIT_WIND_SUM || between(0, minSpan->windValue(), DEBUG_LIMIT_WIND_SUM));
SkASSERT(!DEBUG_LIMIT_WIND_SUM
|| between(-DEBUG_LIMIT_WIND_SUM, minSpan->oppValue(), DEBUG_LIMIT_WIND_SUM));
bool useXor = op ? oppXor : isXor;
SkASSERT(lastXor == -1 || lastXor == (int) useXor);
lastXor = (int) useXor;
wind += next->debugSign() * (op ? minSpan->oppValue() : minSpan->windValue());
if (useXor) {
wind &= 1;
}
useXor = op ? isXor : oppXor;
SkASSERT(lastOppXor == -1 || lastOppXor == (int) useXor);
lastOppXor = (int) useXor;
opp += next->debugSign() * (op ? minSpan->windValue() : minSpan->oppValue());
if (useXor) {
opp &= 1;
}
next = next->fNext;
} while (next && next != first);
SkASSERT(wind == 0 || !FLAGS_runFail);
SkASSERT(opp == 0 || !FLAGS_runFail);
#endif
}
void SkOpAngle::debugValidateNext() const {
#if !FORCE_RELEASE
const SkOpAngle* first = this;
const SkOpAngle* next = first;
SkTDArray<const SkOpAngle*>(angles);
do {
// SK_ALWAYSBREAK(next->fSegment->debugContains(next));
angles.push(next);
next = next->next();
if (next == first) {
break;
}
SK_ALWAYSBREAK(!angles.contains(next));
if (!next) {
return;
}
} while (true);
#endif
}
void SkOpCoincidence::debugShowCoincidence() const {
SkCoincidentSpans* span = fHead;
while (span) {
SkDebugf("%s - id=%d t=%1.9g tEnd=%1.9g\n", __FUNCTION__,
span->fCoinPtTStart->segment()->debugID(),
span->fCoinPtTStart->fT, span->fCoinPtTEnd->fT);
SkDebugf("%s + id=%d t=%1.9g tEnd=%1.9g\n", __FUNCTION__,
span->fOppPtTStart->segment()->debugID(),
span->fOppPtTStart->fT, span->fOppPtTEnd->fT);
span = span->fNext;
}
}
void SkOpSegment::debugValidate() const {
#if DEBUG_VALIDATE
const SkOpSpanBase* span = &fHead;
double lastT = -1;
const SkOpSpanBase* prev = NULL;
int count = 0;
int done = 0;
do {
if (!span->final()) {
++count;
done += span->upCast()->done() ? 1 : 0;
}
SkASSERT(span->segment() == this);
SkASSERT(!prev || prev->upCast()->next() == span);
SkASSERT(!prev || prev == span->prev());
prev = span;
double t = span->ptT()->fT;
SkASSERT(lastT < t);
lastT = t;
span->debugValidate();
} while (!span->final() && (span = span->upCast()->next()));
SkASSERT(count == fCount);
SkASSERT(done == fDoneCount);
SkASSERT(count >= fDoneCount);
SkASSERT(span->final());
span->debugValidate();
#endif
}
bool SkOpSpanBase::debugCoinEndLoopCheck() const {
int loop = 0;
const SkOpSpanBase* next = this;
SkOpSpanBase* nextCoin;
do {
nextCoin = next->fCoinEnd;
SkASSERT(nextCoin == this || nextCoin->fCoinEnd != nextCoin);
for (int check = 1; check < loop - 1; ++check) {
const SkOpSpanBase* checkCoin = this->fCoinEnd;
const SkOpSpanBase* innerCoin = checkCoin;
for (int inner = check + 1; inner < loop; ++inner) {
innerCoin = innerCoin->fCoinEnd;
if (checkCoin == innerCoin) {
SkDebugf("*** bad coincident end loop ***\n");
return false;
}
}
}
++loop;
} while ((next = nextCoin) && next != this);
return true;
}
void SkOpSpanBase::debugValidate() const {
#if DEBUG_VALIDATE
const SkOpPtT* ptT = &fPtT;
SkASSERT(ptT->span() == this);
do {
// SkASSERT(SkDPoint::RoughlyEqual(fPtT.fPt, ptT->fPt));
ptT->debugValidate();
ptT = ptT->next();
} while (ptT != &fPtT);
SkASSERT(this->debugCoinEndLoopCheck());
if (!this->final()) {
SkASSERT(this->upCast()->debugCoinLoopCheck());
}
if (fFromAngle) {
fFromAngle->debugValidate();
}
if (!this->final() && this->upCast()->toAngle()) {
this->upCast()->toAngle()->debugValidate();
}
#endif
}
bool SkOpSpan::debugCoinLoopCheck() const {
int loop = 0;
const SkOpSpan* next = this;
SkOpSpan* nextCoin;
do {
nextCoin = next->fCoincident;
SkASSERT(nextCoin == this || nextCoin->fCoincident != nextCoin);
for (int check = 1; check < loop - 1; ++check) {
const SkOpSpan* checkCoin = this->fCoincident;
const SkOpSpan* innerCoin = checkCoin;
for (int inner = check + 1; inner < loop; ++inner) {
innerCoin = innerCoin->fCoincident;
if (checkCoin == innerCoin) {
SkDebugf("*** bad coincident loop ***\n");
return false;
}
}
}
++loop;
} while ((next = nextCoin) && next != this);
return true;
}
// called only by test code
int SkIntersections::debugCoincidentUsed() const {
if (!fIsCoincident[0]) {
SkASSERT(!fIsCoincident[1]);
return 0;
}
int count = 0;
SkDEBUGCODE(int count2 = 0;)
for (int index = 0; index < fUsed; ++index) {
if (fIsCoincident[0] & (1 << index)) {
++count;
}
#ifdef SK_DEBUG
if (fIsCoincident[1] & (1 << index)) {
++count2;
}
#endif
}
SkASSERT(count == count2);
return count;
}
#include "SkOpContour.h"
int SkOpPtT::debugLoopLimit(bool report) const {
int loop = 0;
const SkOpPtT* next = this;
do {
for (int check = 1; check < loop - 1; ++check) {
const SkOpPtT* checkPtT = this->fNext;
const SkOpPtT* innerPtT = checkPtT;
for (int inner = check + 1; inner < loop; ++inner) {
innerPtT = innerPtT->fNext;
if (checkPtT == innerPtT) {
if (report) {
SkDebugf("*** bad ptT loop ***\n");
}
return loop;
}
}
}
++loop;
} while ((next = next->fNext) && next != this);
return 0;
}
void SkOpPtT::debugValidate() const {
#if DEBUG_VALIDATE
SkOpGlobalState::Phase phase = contour()->globalState()->phase();
if (phase == SkOpGlobalState::kIntersecting
|| phase == SkOpGlobalState::kFixWinding) {
return;
}
SkASSERT(fNext);
SkASSERT(fNext != this);
SkASSERT(fNext->fNext);
SkASSERT(debugLoopLimit(false) == 0);
#endif
}
static void output_scalar(SkScalar num) {
if (num == (int) num) {
SkDebugf("%d", (int) num);
} else {
SkString str;
str.printf("%1.9g", num);
int width = (int) str.size();
const char* cStr = str.c_str();
while (cStr[width - 1] == '0') {
--width;
}
str.resize(width);
SkDebugf("%sf", str.c_str());
}
}
static void output_points(const SkPoint* pts, int count) {
for (int index = 0; index < count; ++index) {
output_scalar(pts[index].fX);
SkDebugf(", ");
output_scalar(pts[index].fY);
if (index + 1 < count) {
SkDebugf(", ");
}
}
}
static void showPathContours(SkPath::RawIter& iter, const char* pathName) {
uint8_t verb;
SkPoint pts[4];
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
SkDebugf(" %s.moveTo(", pathName);
output_points(&pts[0], 1);
SkDebugf(");\n");
continue;
case SkPath::kLine_Verb:
SkDebugf(" %s.lineTo(", pathName);
output_points(&pts[1], 1);
SkDebugf(");\n");
break;
case SkPath::kQuad_Verb:
SkDebugf(" %s.quadTo(", pathName);
output_points(&pts[1], 2);
SkDebugf(");\n");
break;
case SkPath::kConic_Verb:
SkDebugf(" %s.conicTo(", pathName);
output_points(&pts[1], 2);
SkDebugf(", %1.9gf);\n", iter.conicWeight());
break;
case SkPath::kCubic_Verb:
SkDebugf(" %s.cubicTo(", pathName);
output_points(&pts[1], 3);
SkDebugf(");\n");
break;
case SkPath::kClose_Verb:
SkDebugf(" %s.close();\n", pathName);
break;
default:
SkDEBUGFAIL("bad verb");
return;
}
}
}
static const char* gFillTypeStr[] = {
"kWinding_FillType",
"kEvenOdd_FillType",
"kInverseWinding_FillType",
"kInverseEvenOdd_FillType"
};
void SkPathOpsDebug::ShowOnePath(const SkPath& path, const char* name, bool includeDeclaration) {
SkPath::RawIter iter(path);
#define SUPPORT_RECT_CONTOUR_DETECTION 0
#if SUPPORT_RECT_CONTOUR_DETECTION
int rectCount = path.isRectContours() ? path.rectContours(NULL, NULL) : 0;
if (rectCount > 0) {
SkTDArray<SkRect> rects;
SkTDArray<SkPath::Direction> directions;
rects.setCount(rectCount);
directions.setCount(rectCount);
path.rectContours(rects.begin(), directions.begin());
for (int contour = 0; contour < rectCount; ++contour) {
const SkRect& rect = rects[contour];
SkDebugf("path.addRect(%1.9g, %1.9g, %1.9g, %1.9g, %s);\n", rect.fLeft, rect.fTop,
rect.fRight, rect.fBottom, directions[contour] == SkPath::kCCW_Direction
? "SkPath::kCCW_Direction" : "SkPath::kCW_Direction");
}
return;
}
#endif
SkPath::FillType fillType = path.getFillType();
SkASSERT(fillType >= SkPath::kWinding_FillType && fillType <= SkPath::kInverseEvenOdd_FillType);
if (includeDeclaration) {
SkDebugf(" SkPath %s;\n", name);
}
SkDebugf(" %s.setFillType(SkPath::%s);\n", name, gFillTypeStr[fillType]);
iter.setPath(path);
showPathContours(iter, name);
}
| 10,311 |
1,144 | // Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Utility functions for testing with IPC.
#ifndef MOZC_IPC_IPC_TEST_UTIL_H_
#define MOZC_IPC_IPC_TEST_UTIL_H_
#include "ipc/ipc.h"
namespace mozc {
#ifdef __APPLE__
// Mach port manager for testing: it allocates a mach port locally and
// shares it among client-server.
class TestMachPortManager : public mozc::MachPortManagerInterface {
public:
TestMachPortManager();
~TestMachPortManager();
virtual bool GetMachPort(const std::string &name, mach_port_t *port);
virtual bool IsServerRunning(const std::string &name) const;
private:
mach_port_t port_;
};
#endif
// An IPCClientFactory which holds an onmemory port instead of actual
// connections. It is only available for Mac. Otherwise it is same
// as a normal IPCClientFactory.
class IPCClientFactoryOnMemory : public IPCClientFactoryInterface {
public:
IPCClientFactoryOnMemory() {}
IPCClientInterface *NewClient(const std::string &name,
const std::string &port_name) override;
IPCClientInterface *NewClient(const std::string &name) override;
#ifdef __APPLE__
// Returns MachPortManager to share the mach port between client and server.
MachPortManagerInterface *OnMemoryPortManager() { return &mach_manager_; }
#endif
private:
#ifdef __APPLE__
TestMachPortManager mach_manager_;
#endif
DISALLOW_COPY_AND_ASSIGN(IPCClientFactoryOnMemory);
};
} // namespace mozc
#endif // MOZC_IPC_IPC_TEST_UTIL_H_
| 914 |
539 | #include "geometrycentral/surface/integer_coordinates_intrinsic_triangulation.h"
#include "geometrycentral/surface/intrinsic_triangulation.h"
#include "geometrycentral/surface/manifold_surface_mesh.h"
#include "geometrycentral/surface/meshio.h"
#include "geometrycentral/surface/signpost_intrinsic_triangulation.h"
#include "geometrycentral/surface/transfer_functions.h"
#include "geometrycentral/surface/vertex_position_geometry.h"
#include "load_test_meshes.h"
#include "gtest/gtest.h"
#include <iostream>
#include <string>
#include <unordered_set>
using namespace geometrycentral;
using namespace geometrycentral::surface;
class IntrinsicTriangulationSuite : public MeshAssetSuite {};
TEST_F(IntrinsicTriangulationSuite, SignpostFlip) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
EXPECT_TRUE(tri.isDelaunay());
}
}
TEST_F(IntrinsicTriangulationSuite, IntegerFlip) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
EXPECT_TRUE(tri.isDelaunay());
}
}
TEST_F(IntrinsicTriangulationSuite, DelaunayTriangulationsAgree) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri_int(mesh, origGeometry);
SignpostIntrinsicTriangulation tri_sign(mesh, origGeometry);
tri_int.flipToDelaunay();
tri_sign.flipToDelaunay();
for (size_t iE = 0; iE < tri_int.intrinsicMesh->nEdges(); iE++) {
double l_int = tri_int.edgeLengths[tri_int.intrinsicMesh->edge(iE)];
double l_sign = tri_sign.edgeLengths[tri_sign.intrinsicMesh->edge(iE)];
EXPECT_NEAR(l_int, l_sign, 1e-5);
}
}
}
TEST_F(IntrinsicTriangulationSuite, SignpostTrace) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
EdgeData<std::vector<SurfacePoint>> out = tri.traceAllIntrinsicEdgesAlongInput();
for (Edge e : tri.mesh.edges()) {
EXPECT_GE(out[e].size(), 2);
}
}
}
TEST_F(IntrinsicTriangulationSuite, IntegerTrace) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
EdgeData<std::vector<SurfacePoint>> out = tri.traceAllIntrinsicEdgesAlongInput();
for (Edge e : tri.mesh.edges()) {
EXPECT_EQ(out[e].size(), std::max(0, tri.normalCoordinates[e]) + 2);
}
}
}
TEST_F(IntrinsicTriangulationSuite, SignpostEquivalentPoint) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
auto roundtripTest = [&](SurfacePoint origPoint) {
Vector3 origPos = origPoint.interpolate(origGeometry.vertexPositions);
// Map to the intrinsic surface
SurfacePoint intPoint = tri.equivalentPointOnIntrinsic(origPoint);
// Map back to the input surface
SurfacePoint returnPoint = tri.equivalentPointOnInput(intPoint);
// Check that the result is close to where we started
Vector3 returnPos = returnPoint.interpolate(origGeometry.vertexPositions);
EXPECT_LT((origPos - returnPos).norm(), 1e-5);
};
// Pick a bunch of face points and map them back and forth; verify we get get very similar locations
std::mt19937 mt(42);
auto randBary = [&]() {
std::uniform_real_distribution<double> dist(0.0, 1.0);
double r1 = dist(mt);
double r2 = dist(mt);
Vector3 bary{1 - std::sqrt(r1), std::sqrt(r1) * (1 - r2), std::sqrt(r1) * r2};
return bary;
};
for (Face f : mesh.faces()) {
SurfacePoint origPoint(f, randBary());
roundtripTest(origPoint);
}
// Test a few vertex points & edge points
roundtripTest(SurfacePoint(mesh.vertex(12)));
roundtripTest(SurfacePoint(mesh.vertex(42)));
roundtripTest(SurfacePoint(mesh.vertex(55)));
roundtripTest(SurfacePoint(mesh.edge(55), 0.4));
roundtripTest(SurfacePoint(mesh.edge(55), 0.0));
roundtripTest(SurfacePoint(mesh.edge(55), 1.0));
roundtripTest(SurfacePoint(mesh.edge(11), 1.0));
}
}
TEST_F(IntrinsicTriangulationSuite, IntegerEdgeTraceAgreesWithBulk) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.flipToDelaunay();
// Traced individually
EdgeData<std::vector<SurfacePoint>> out1(tri.inputMesh);
for (Edge e : tri.inputMesh.edges()) {
out1[e] = tri.traceInputHalfedgeAlongIntrinsic(e.halfedge());
}
// Traced via common subdivision
EdgeData<std::vector<SurfacePoint>> out2 = tri.traceAllInputEdgesAlongIntrinsic();
for (Edge e : tri.inputMesh.edges()) {
EXPECT_EQ(out1[e].size(), out2[e].size());
for (size_t iP = 0; iP < out1[e].size(); iP++) {
EXPECT_EQ(out1[e][iP].type, out2[e][iP].type);
switch (out1[e][iP].type) {
case SurfacePointType::Vertex:
EXPECT_EQ(out1[e][iP].vertex, out2[e][iP].vertex);
break;
case SurfacePointType::Edge:
EXPECT_EQ(out1[e][iP].edge, out2[e][iP].edge);
EXPECT_NEAR(out1[e][iP].tEdge, out2[e][iP].tEdge, 1e-5);
break;
case SurfacePointType::Face:
EXPECT_EQ(out1[e][iP].face, out2[e][iP].face);
EXPECT_NEAR((out1[e][iP].faceCoords - out2[e][iP].faceCoords).norm(), 0, 1e-5);
break;
}
}
}
}
}
TEST_F(IntrinsicTriangulationSuite, TraceInputEdgeAlongIntrinsicSignpostVsInteger) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri_signpost(mesh, origGeometry);
IntegerCoordinatesIntrinsicTriangulation tri_integer(mesh, origGeometry);
tri_signpost.flipToDelaunay();
tri_integer.flipToDelaunay();
for (Halfedge he : mesh.halfedges()) {
std::vector<SurfacePoint> trace_signpost = tri_signpost.traceInputHalfedgeAlongIntrinsic(he);
std::vector<SurfacePoint> trace_integer = tri_integer.traceInputHalfedgeAlongIntrinsic(he);
EXPECT_EQ(trace_signpost.size(), trace_integer.size());
for (size_t iP = 0; iP < trace_signpost.size(); iP++) {
SurfacePoint& p_signpost = trace_signpost[iP];
SurfacePoint& p_integer = trace_integer[iP];
EXPECT_EQ(p_signpost.type, p_integer.type);
switch (p_signpost.type) {
case SurfacePointType::Vertex:
EXPECT_EQ(p_signpost.vertex, p_integer.vertex);
break;
case SurfacePointType::Edge:
EXPECT_EQ(p_signpost.edge, p_integer.edge);
EXPECT_NEAR(p_signpost.tEdge, p_integer.tEdge, 1e-5);
break;
case SurfacePointType::Face:
EXPECT_EQ(p_signpost.face, p_integer.face);
EXPECT_NEAR((p_signpost.faceCoords - p_integer.faceCoords).norm(), 0, 1e-5);
break;
}
}
}
}
}
TEST_F(IntrinsicTriangulationSuite, SignpostRefine) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
EXPECT_TRUE(tri.isDelaunay());
// (technically on some meshes no insertions may be needed, but for this test lets choose meshes that do need it)
EXPECT_GT(tri.mesh.nVertices(), tri.inputMesh.nVertices());
// (technically we should check the minimum angle away from needle-like vertices)
EXPECT_GE(tri.minAngleDegrees(), 25);
}
}
TEST_F(IntrinsicTriangulationSuite, IntegerRefine) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
EXPECT_TRUE(tri.isDelaunay());
// (technically on some meshes no insertions may be needed, but for this test lets choose meshes that do need it)
EXPECT_GT(tri.mesh.nVertices(), tri.inputMesh.nVertices());
// (technically we should check the minimum angle away from needle-like vertices)
EXPECT_GE(tri.minAngleDegrees(), 25);
}
}
TEST_F(IntrinsicTriangulationSuite, SignpostCommonSubdivision) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
SignpostIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
CommonSubdivision& cs = tri.getCommonSubdivision();
cs.constructMesh();
EXPECT_GT(cs.mesh->nVertices(), tri.inputMesh.nVertices());
EXPECT_GT(cs.mesh->nVertices(), tri.mesh.nVertices());
}
}
TEST_F(IntrinsicTriangulationSuite, IntegerCommonSubdivision) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
CommonSubdivision& cs = tri.getCommonSubdivision();
bool triangulate = false;
cs.constructMesh(triangulate);
EXPECT_GT(cs.mesh->nVertices(), tri.inputMesh.nVertices());
EXPECT_GT(cs.mesh->nVertices(), tri.mesh.nVertices());
// Check element counts against a few ways of computing them
size_t nV, nE, nF;
std::tie(nV, nE, nF) = cs.elementCounts();
EXPECT_EQ(cs.mesh->nVertices(), nV);
EXPECT_EQ(cs.mesh->nEdges(), nE);
EXPECT_EQ(cs.mesh->nFaces(), nF);
size_t nV_normal = tri.intrinsicMesh->nVertices();
for (Edge e : tri.intrinsicMesh->edges()) {
nV_normal += fmax(0, tri.normalCoordinates[e]);
}
EXPECT_EQ(cs.mesh->nVertices(), nV_normal);
}
}
// TODO test signpost and integer against each other to verify they give same results
TEST_F(IntrinsicTriangulationSuite, CommonSubdivisionCompareIntegerSignpost) {
for (const MeshAsset& a : {getAsset("fox.ply", true), getAsset("cat_head.obj", true)}) {
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
// Construct a common subdivision with both data structures
IntegerCoordinatesIntrinsicTriangulation tri_int(mesh, origGeometry);
SignpostIntrinsicTriangulation tri_sign(mesh, origGeometry);
// Refinement gives a slightly different mesh, which is a little annoying but probably
// not worth fixing.
//tri_int.delaunayRefine();
//tri_sign.delaunayRefine();
tri_int.flipToDelaunay();
tri_sign.flipToDelaunay();
EXPECT_EQ(tri_int.intrinsicMesh->nVertices(), tri_sign.intrinsicMesh->nVertices());
CommonSubdivision& cs_int = tri_int.getCommonSubdivision();
CommonSubdivision& cs_sign = tri_sign.getCommonSubdivision();
cs_int.constructMesh();
cs_sign.constructMesh();
// Check that the element counts of the commont subdivision are the same
EXPECT_EQ(cs_int.mesh->nVertices(), cs_sign.mesh->nVertices());
EXPECT_EQ(cs_int.mesh->nEdges(), cs_sign.mesh->nEdges());
EXPECT_EQ(cs_int.mesh->nFaces(), cs_sign.mesh->nFaces());
// Check that all faces have very similar area
// (technically we could generate two correct subdivisions with the faces not
// in correspondence, but in the current implementation they will be, so we'll
// just test that)
origGeometry.requireEdgeLengths();
EdgeData<double> len_int = cs_int.interpolateEdgeLengthsA(origGeometry.edgeLengths);
EdgeData<double> len_sign = cs_sign.interpolateEdgeLengthsA(origGeometry.edgeLengths);
for(size_t iF = 0; iF < cs_int.mesh->nFaces(); iF++) {
EXPECT_NEAR(len_int[iF], len_sign[iF], 1e-5);
}
}
}
// TODO: also test with signposts?
TEST_F(IntrinsicTriangulationSuite, FunctionTransfer) {
for (const MeshAsset& a : {getAsset("fox.ply", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
CommonSubdivision& cs = tri.getCommonSubdivision();
AttributeTransfer transfer(cs, origGeometry);
VertexData<double> data_B(*tri.intrinsicMesh, Vector<double>::Random(tri.intrinsicMesh->nVertices()));
VertexData<double> data_A_Pointwise = transfer.transferBtoA(data_B, TransferMethod::Pointwise);
VertexData<double> data_A_L2 = transfer.transferBtoA(data_B, TransferMethod::L2);
Vector<double> truth = transfer.P_B * data_B.toVector();
Vector<double> pointwiseA = transfer.P_A * data_A_Pointwise.toVector();
Vector<double> L2A = transfer.P_A * data_A_L2.toVector();
double pointwiseErr = (pointwiseA - truth).dot(transfer.M_CS_Galerkin * (pointwiseA - truth));
double L2Err = (L2A - truth).dot(transfer.M_CS_Galerkin * (L2A - truth));
EXPECT_LE(L2Err, pointwiseErr);
SparseMatrix<double> lhs, rhs;
std::tie(lhs, rhs) = transfer.constructBtoAMatrices();
Vector<double> residual = lhs * data_A_L2.toVector() - rhs * data_B.toVector();
EXPECT_LE(residual.norm(), 1e-6);
}
}
TEST_F(IntrinsicTriangulationSuite, CommonSubdivisionGeometry) {
for (const MeshAsset& a : {getAsset("fox.ply", true)}) {
a.printThyName();
ManifoldSurfaceMesh& mesh = *a.manifoldMesh;
VertexPositionGeometry& origGeometry = *a.geometry;
IntegerCoordinatesIntrinsicTriangulation tri(mesh, origGeometry);
tri.delaunayRefine();
CommonSubdivision& cs = tri.getCommonSubdivision();
cs.constructMesh();
// == Edge lengths
// Lengths from extrinsic vertex positions
const VertexData<Vector3>& posCS = cs.interpolateAcrossA(origGeometry.vertexPositions);
VertexPositionGeometry csGeo(*cs.mesh, posCS);
csGeo.requireEdgeLengths();
EdgeData<double> lengthsFromPosA = csGeo.edgeLengths;
csGeo.unrequireEdgeLengths();
// Lengths from extrinsic edge lengths
origGeometry.requireEdgeLengths();
const EdgeData<double>& lengthsA = origGeometry.edgeLengths;
EdgeData<double> lengthsFromLenA = cs.interpolateEdgeLengthsA(lengthsA);
// Lengths from intrinsic edge lengths
EdgeData<double> lengthsFromLenB = cs.interpolateEdgeLengthsB(tri.edgeLengths);
EXPECT_NEAR((lengthsFromPosA.toVector() - lengthsFromLenA.toVector()).norm(), 0, 1e-5);
EXPECT_NEAR((lengthsFromPosA.toVector() - lengthsFromLenB.toVector()).norm(), 0, 1e-5);
EXPECT_NEAR((lengthsFromLenA.toVector() - lengthsFromLenB.toVector()).norm(), 0, 1e-5);
}
}
| 6,486 |
2,576 | /*
* Copyright (c) 2010-2018. Axon Framework
*
* 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.axonframework.commandhandling.distributed;
import org.axonframework.commandhandling.CommandMessage;
import java.util.function.Function;
import static java.lang.String.format;
/**
* Set of simple {@link RoutingStrategy} implementations. Could for example be used as fallback solutions when another
* {@code RoutingStrategy} is unable to resolve the routing key.
*
* @author <NAME>
* @since 2.0
*/
public enum UnresolvedRoutingKeyPolicy implements RoutingStrategy {
/**
* A {@link RoutingStrategy} which always throws a {@link CommandDispatchException} regardless of the {@link
* CommandMessage} received. Only feasible as a fallback solution which should straight out fail if the intended
* policy is unable to resolve a routing key.
* <p>
* Note that when the routing key is based on static content in the {@code CommandMessage}, the exception raised
* should extend from {@link org.axonframework.common.AxonNonTransientException} to indicate that retries do not
* have a chance to succeed.
*
* @see org.axonframework.commandhandling.gateway.RetryScheduler
*/
ERROR(command -> {
throw new CommandDispatchException(format(
"The command [%s] does not contain a routing key.", command.getCommandName()
));
}),
/**
* Policy that indicates a random key is to be returned when no Routing Key can be found for a Command Message. This
* effectively means the Command Message is routed to a random segment.
* <p>
* Although not required to be fully random, implementations are required to return a different key for each
* incoming command. Multiple invocations for the same command message may return the same value, but are not
* required to do so.
*/
RANDOM_KEY(command -> Double.toHexString(Math.random())),
/**
* Policy that indicates a fixed key ("unresolved") should be returned when no Routing Key can be found for a
* Command Message. This effectively means all Command Messages with unresolved routing keys are routed to a the
* same segment. The load of that segment may therefore not match the load factor.
*/
STATIC_KEY(command -> "unresolved");
private final Function<CommandMessage<?>, String> routingKeyResolver;
UnresolvedRoutingKeyPolicy(Function<CommandMessage<?>, String> routingKeyResolver) {
this.routingKeyResolver = routingKeyResolver;
}
@Override
public String getRoutingKey(CommandMessage<?> command) {
return routingKeyResolver.apply(command);
}
}
| 944 |
1,356 | <reponame>matheusamazonas/cardboard
/*
* Copyright 2019 Google LLC
*
* 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 "util/matrix_4x4.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace cardboard {
Matrix4x4 Matrix4x4::Identity() {
Matrix4x4 ret;
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 4; ++i) {
ret.m[j][i] = (i == j) ? 1 : 0;
}
}
return ret;
}
Matrix4x4 Matrix4x4::Zeros() {
Matrix4x4 ret;
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 4; ++i) {
ret.m[j][i] = 0;
}
}
return ret;
}
Matrix4x4 Matrix4x4::Translation(float x, float y, float z) {
Matrix4x4 ret = Matrix4x4::Identity();
ret.m[3][0] = x;
ret.m[3][1] = y;
ret.m[3][2] = z;
return ret;
}
Matrix4x4 Matrix4x4::Perspective(const std::array<float, 4>& fov, float zNear,
float zFar) {
Matrix4x4 ret = Matrix4x4::Zeros();
const float xLeft = -std::tan(fov[0]) * zNear;
const float xRight = std::tan(fov[1]) * zNear;
const float yBottom = -std::tan(fov[2]) * zNear;
const float yTop = std::tan(fov[3]) * zNear;
const float X = (2 * zNear) / (xRight - xLeft);
const float Y = (2 * zNear) / (yTop - yBottom);
const float A = (xRight + xLeft) / (xRight - xLeft);
const float B = (yTop + yBottom) / (yTop - yBottom);
const float C = (zNear + zFar) / (zNear - zFar);
const float D = (2 * zNear * zFar) / (zNear - zFar);
ret.m[0][0] = X;
ret.m[2][0] = A;
ret.m[1][1] = Y;
ret.m[2][1] = B;
ret.m[2][2] = C;
ret.m[3][2] = D;
ret.m[2][3] = -1;
return ret;
}
void Matrix4x4::ToArray(float* array) const {
std::memcpy(array, &m[0][0], 16 * sizeof(float));
}
} // namespace cardboard
| 927 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-998c-j8wx-mhch",
"modified": "2022-05-01T06:49:56Z",
"published": "2022-05-01T06:49:56Z",
"aliases": [
"CVE-2006-1475"
],
"details": "Windows Firewall in Microsoft Windows XP SP2 does not produce application alerts when an application is executed using the NTFS Alternate Data Streams (ADS) filename:stream syntax, which might allow local users to launch a Trojan horse attack in which the victim does not obtain the alert that Windows Firewall would have produced for a non-ADS file.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-1475"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/25597"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/428970/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/429111/100/0/threaded"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "LOW",
"github_reviewed": false
}
} | 478 |
562 | <filename>recipes/xorg-cf-files/all/conanfile.py<gh_stars>100-1000
from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
import contextlib
import os
required_conan_version = ">=1.33.0"
class XorgCfFilesConan(ConanFile):
name = "xorg-cf-files"
description = "Imake configuration files & templates"
topics = ("conan", "imake", "xorg", "template", "configuration", "obsolete")
license = "MIT"
homepage = "https://gitlab.freedesktop.org/xorg/util/cf"
url = "https://github.com/conan-io/conan-center-index"
settings = "os", "compiler"
exports_sources = "patches/*"
generators = "pkg_config"
_autotools = None
@property
def _source_subfolder(self):
return "source_subfolder"
@property
def _settings_build(self):
return getattr(self, "settings_build", self.settings)
def requirements(self):
self.requires("xorg-macros/1.19.3")
self.requires("xorg-proto/2021.4")
def build_requirements(self):
self.build_requires("pkgconf/1.7.4")
if self._settings_build.os == "Windows" and not tools.get_env("CONAN_BASH_PATH"):
self.build_requires("msys2/cci.latest")
if self.settings.compiler == "Visual Studio":
self.build_requires("automake/1.16.3")
def configure(self):
del self.settings.compiler.cppstd
del self.settings.compiler.libcxx
def validate(self):
if tools.is_apple_os(self.settings.os):
raise ConanInvalidConfiguration("This recipe does not support Apple operating systems.")
def package_id(self):
del self.info.settings.compiler
# self.info.settings.os # FIXME: can be removed once c3i is able to test multiple os'es from one common package
def source(self):
tools.get(**self.conan_data["sources"][self.version],
destination=self._source_subfolder, strip_root=True)
@property
def _user_info_build(self):
return getattr(self, "user_info_build", self.deps_user_info)
@contextlib.contextmanager
def _build_context(self):
if self.settings.compiler == "Visual Studio":
with tools.vcvars(self):
env = {
"CC": "{} cl -nologo".format(tools.unix_path(self._user_info_build["automake"].compile)),
"CXX": "{} cl -nologo".format(tools.unix_path(self._user_info_build["automake"].compile)),
"CPP": "{} cl -E".format(tools.unix_path(self._user_info_build["automake"].compile)),
}
with tools.environment_append(env):
yield
else:
yield
def _configure_autotools(self):
if self._autotools:
return self._autotools
self._autotools = AutoToolsBuildEnvironment(self, win_bash=self._settings_build.os == "Windows")
self._autotools.libs = []
self._autotools.configure(configure_dir=self._source_subfolder)
return self._autotools
def build(self):
for patch in self.conan_data.get("patches", {}).get(self.version, []):
tools.patch(**patch)
with self._build_context():
autotools = self._configure_autotools()
autotools.make()
def package(self):
self.copy("COPYING", src=self._source_subfolder, dst="licenses")
with self._build_context():
autotools = self._configure_autotools()
autotools.install()
tools.rmdir(os.path.join(self.package_folder, "share"))
def package_info(self):
self.cpp_info.libdirs = []
self.user_info.CONFIG_PATH = os.path.join(self.package_folder, "lib", "X11", "config").replace("\\", "/")
| 1,630 |
711 | <gh_stars>100-1000
package com.java110.core.context;
import java.util.Date;
/**
* @author wux
* @create 2019-02-07 下午7:01
* @desc 订单通知数据流信息
**/
public abstract class AbstractOrderNotifyDataFlowContext extends AbstractDataFlowContextPlus implements IOrderNotifyDataFlowContext,IOrderResponse {
protected AbstractOrderNotifyDataFlowContext(Date startDate, String code) {
}
private String transactionId;
private Date responseTime;
private String orderTypeCd;
private String businessType;
private String code;
private String message;
private String bId;
private String businessTypeCd;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public Date getResponseTime() {
return responseTime;
}
public void setResponseTime(Date responseTime) {
this.responseTime = responseTime;
}
public String getOrderTypeCd() {
return orderTypeCd;
}
public void setOrderTypeCd(String orderTypeCd) {
this.orderTypeCd = orderTypeCd;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getbId() {
return bId;
}
public void setbId(String bId) {
this.bId = bId;
}
public String getBusinessTypeCd() {
return businessTypeCd;
}
public void setBusinessTypeCd(String businessTypeCd) {
this.businessTypeCd = businessTypeCd;
}
}
| 743 |
1,392 | # Generated by Django 3.2.12 on 2022-02-09 15:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("product", "0160_populate_product_datetimes"),
]
operations = [
migrations.AlterField(
model_name="product",
name="created",
field=models.DateTimeField(auto_now_add=True, db_index=True),
),
migrations.AlterField(
model_name="product",
name="updated_at",
field=models.DateTimeField(auto_now=True, db_index=True),
),
migrations.AlterField(
model_name="productvariant",
name="created",
field=models.DateTimeField(auto_now_add=True, db_index=True),
),
migrations.AlterField(
model_name="productvariant",
name="updated_at",
field=models.DateTimeField(auto_now=True, db_index=True),
),
]
| 463 |
391 | from mamba import description, it, before
from unittest.mock import MagicMock
from crowd_anki.history.archiver import AllDeckArchiver
with description(AllDeckArchiver) as self:
with before.each:
self.deck_without_children = MagicMock()
self.deck_manager = MagicMock()
self.deck_manager.leaf_decks.return_value = [self.deck_without_children]
self.archiver_supplier = MagicMock()
self.all_deck_archiver = AllDeckArchiver(self.deck_manager, self.archiver_supplier)
with it("should call archival on all leaf decks by default"):
self.all_deck_archiver.archive()
self.archiver_supplier.assert_called_once_with(self.deck_without_children)
| 260 |
348 | {"nom":"Saint-Eloi-de-Fourques","circ":"2ème circonscription","dpt":"Eure","inscrits":403,"abs":239,"votants":164,"blancs":9,"nuls":2,"exp":153,"res":[{"nuance":"REM","nom":"<NAME>","voix":99},{"nuance":"FN","nom":"<NAME>","voix":54}]} | 95 |
2,338 | <reponame>mkinsner/llvm
int other();
namespace {
template <typename T1> struct Temp { int x; };
// This emits the 'Temp' template in this TU.
Temp<float> Template1;
} // namespace
int main() {
return Template1.x + other(); // break here
}
| 84 |
432 | /*
* Exported interface to downloadable microcode for AdvanSys SCSI Adapters
*
* $FreeBSD: src/sys/dev/advansys/advmcode.h,v 1.6 2000/01/14 03:33:38 gibbs Exp $
* $DragonFly: src/sys/dev/disk/advansys/advmcode.h,v 1.2 2003/06/17 04:28:21 dillon Exp $
*
* Obtained from:
*
* Copyright (c) 1995-1999 Advanced System Products, Inc.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that redistributions of source
* code retain the above copyright notice and this comment without
* modification.
*/
extern u_int8_t adv_mcode[];
extern u_int16_t adv_mcode_size;
extern u_int32_t adv_mcode_chksum;
| 236 |
358 | <reponame>1over/mahi-gui
// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11
// from https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/metadata/icons.yml
// for use with https://github.com/FortAwesome/Font-Awesome/blob/master/webfonts/fa-brands-400.ttf
#pragma once
#define FONT_ICON_FILE_NAME_FAB "fa-brands-400.ttf"
#define ICON_MIN_FAB 0xf081
#define ICON_MAX_FAB 0xf8e8
#define ICON_FA_500PX u8"\uf26e"
#define ICON_FA_ACCESSIBLE_ICON u8"\uf368"
#define ICON_FA_ACCUSOFT u8"\uf369"
#define ICON_FA_ACQUISITIONS_INCORPORATED u8"\uf6af"
#define ICON_FA_ADN u8"\uf170"
#define ICON_FA_ADOBE u8"\uf778"
#define ICON_FA_ADVERSAL u8"\uf36a"
#define ICON_FA_AFFILIATETHEME u8"\uf36b"
#define ICON_FA_AIRBNB u8"\uf834"
#define ICON_FA_ALGOLIA u8"\uf36c"
#define ICON_FA_ALIPAY u8"\uf642"
#define ICON_FA_AMAZON u8"\uf270"
#define ICON_FA_AMAZON_PAY u8"\uf42c"
#define ICON_FA_AMILIA u8"\uf36d"
#define ICON_FA_ANDROID u8"\uf17b"
#define ICON_FA_ANGELLIST u8"\uf209"
#define ICON_FA_ANGRYCREATIVE u8"\uf36e"
#define ICON_FA_ANGULAR u8"\uf420"
#define ICON_FA_APP_STORE u8"\uf36f"
#define ICON_FA_APP_STORE_IOS u8"\uf370"
#define ICON_FA_APPER u8"\uf371"
#define ICON_FA_APPLE u8"\uf179"
#define ICON_FA_APPLE_PAY u8"\uf415"
#define ICON_FA_ARTSTATION u8"\uf77a"
#define ICON_FA_ASYMMETRIK u8"\uf372"
#define ICON_FA_ATLASSIAN u8"\uf77b"
#define ICON_FA_AUDIBLE u8"\uf373"
#define ICON_FA_AUTOPREFIXER u8"\uf41c"
#define ICON_FA_AVIANEX u8"\uf374"
#define ICON_FA_AVIATO u8"\uf421"
#define ICON_FA_AWS u8"\uf375"
#define ICON_FA_BANDCAMP u8"\uf2d5"
#define ICON_FA_BATTLE_NET u8"\uf835"
#define ICON_FA_BEHANCE u8"\uf1b4"
#define ICON_FA_BEHANCE_SQUARE u8"\uf1b5"
#define ICON_FA_BIMOBJECT u8"\uf378"
#define ICON_FA_BITBUCKET u8"\uf171"
#define ICON_FA_BITCOIN u8"\uf379"
#define ICON_FA_BITY u8"\uf37a"
#define ICON_FA_BLACK_TIE u8"\uf27e"
#define ICON_FA_BLACKBERRY u8"\uf37b"
#define ICON_FA_BLOGGER u8"\uf37c"
#define ICON_FA_BLOGGER_B u8"\uf37d"
#define ICON_FA_BLUETOOTH u8"\uf293"
#define ICON_FA_BLUETOOTH_B u8"\uf294"
#define ICON_FA_BOOTSTRAP u8"\uf836"
#define ICON_FA_BTC u8"\uf15a"
#define ICON_FA_BUFFER u8"\uf837"
#define ICON_FA_BUROMOBELEXPERTE u8"\uf37f"
#define ICON_FA_BUY_N_LARGE u8"\uf8a6"
#define ICON_FA_BUYSELLADS u8"\uf20d"
#define ICON_FA_CANADIAN_MAPLE_LEAF u8"\uf785"
#define ICON_FA_CC_AMAZON_PAY u8"\uf42d"
#define ICON_FA_CC_AMEX u8"\uf1f3"
#define ICON_FA_CC_APPLE_PAY u8"\uf416"
#define ICON_FA_CC_DINERS_CLUB u8"\uf24c"
#define ICON_FA_CC_DISCOVER u8"\uf1f2"
#define ICON_FA_CC_JCB u8"\uf24b"
#define ICON_FA_CC_MASTERCARD u8"\uf1f1"
#define ICON_FA_CC_PAYPAL u8"\uf1f4"
#define ICON_FA_CC_STRIPE u8"\uf1f5"
#define ICON_FA_CC_VISA u8"\uf1f0"
#define ICON_FA_CENTERCODE u8"\uf380"
#define ICON_FA_CENTOS u8"\uf789"
#define ICON_FA_CHROME u8"\uf268"
#define ICON_FA_CHROMECAST u8"\uf838"
#define ICON_FA_CLOUDSCALE u8"\uf383"
#define ICON_FA_CLOUDSMITH u8"\uf384"
#define ICON_FA_CLOUDVERSIFY u8"\uf385"
#define ICON_FA_CODEPEN u8"\uf1cb"
#define ICON_FA_CODIEPIE u8"\uf284"
#define ICON_FA_CONFLUENCE u8"\uf78d"
#define ICON_FA_CONNECTDEVELOP u8"\uf20e"
#define ICON_FA_CONTAO u8"\uf26d"
#define ICON_FA_COTTON_BUREAU u8"\uf89e"
#define ICON_FA_CPANEL u8"\uf388"
#define ICON_FA_CREATIVE_COMMONS u8"\uf25e"
#define ICON_FA_CREATIVE_COMMONS_BY u8"\uf4e7"
#define ICON_FA_CREATIVE_COMMONS_NC u8"\uf4e8"
#define ICON_FA_CREATIVE_COMMONS_NC_EU u8"\uf4e9"
#define ICON_FA_CREATIVE_COMMONS_NC_JP u8"\uf4ea"
#define ICON_FA_CREATIVE_COMMONS_ND u8"\uf4eb"
#define ICON_FA_CREATIVE_COMMONS_PD u8"\uf4ec"
#define ICON_FA_CREATIVE_COMMONS_PD_ALT u8"\uf4ed"
#define ICON_FA_CREATIVE_COMMONS_REMIX u8"\uf4ee"
#define ICON_FA_CREATIVE_COMMONS_SA u8"\uf4ef"
#define ICON_FA_CREATIVE_COMMONS_SAMPLING u8"\uf4f0"
#define ICON_FA_CREATIVE_COMMONS_SAMPLING_PLUS u8"\uf4f1"
#define ICON_FA_CREATIVE_COMMONS_SHARE u8"\uf4f2"
#define ICON_FA_CREATIVE_COMMONS_ZERO u8"\uf4f3"
#define ICON_FA_CRITICAL_ROLE u8"\uf6c9"
#define ICON_FA_CSS3 u8"\uf13c"
#define ICON_FA_CSS3_ALT u8"\uf38b"
#define ICON_FA_CUTTLEFISH u8"\uf38c"
#define ICON_FA_D_AND_D u8"\uf38d"
#define ICON_FA_D_AND_D_BEYOND u8"\uf6ca"
#define ICON_FA_DASHCUBE u8"\uf210"
#define ICON_FA_DELICIOUS u8"\uf1a5"
#define ICON_FA_DEPLOYDOG u8"\uf38e"
#define ICON_FA_DESKPRO u8"\uf38f"
#define ICON_FA_DEV u8"\uf6cc"
#define ICON_FA_DEVIANTART u8"\uf1bd"
#define ICON_FA_DHL u8"\uf790"
#define ICON_FA_DIASPORA u8"\uf791"
#define ICON_FA_DIGG u8"\uf1a6"
#define ICON_FA_DIGITAL_OCEAN u8"\uf391"
#define ICON_FA_DISCORD u8"\uf392"
#define ICON_FA_DISCOURSE u8"\uf393"
#define ICON_FA_DOCHUB u8"\uf394"
#define ICON_FA_DOCKER u8"\uf395"
#define ICON_FA_DRAFT2DIGITAL u8"\uf396"
#define ICON_FA_DRIBBBLE u8"\uf17d"
#define ICON_FA_DRIBBBLE_SQUARE u8"\uf397"
#define ICON_FA_DROPBOX u8"\uf16b"
#define ICON_FA_DRUPAL u8"\uf1a9"
#define ICON_FA_DYALOG u8"\uf399"
#define ICON_FA_EARLYBIRDS u8"\uf39a"
#define ICON_FA_EBAY u8"\uf4f4"
#define ICON_FA_EDGE u8"\uf282"
#define ICON_FA_ELEMENTOR u8"\uf430"
#define ICON_FA_ELLO u8"\uf5f1"
#define ICON_FA_EMBER u8"\uf423"
#define ICON_FA_EMPIRE u8"\uf1d1"
#define ICON_FA_ENVIRA u8"\uf299"
#define ICON_FA_ERLANG u8"\uf39d"
#define ICON_FA_ETHEREUM u8"\uf42e"
#define ICON_FA_ETSY u8"\uf2d7"
#define ICON_FA_EVERNOTE u8"\uf839"
#define ICON_FA_EXPEDITEDSSL u8"\uf23e"
#define ICON_FA_FACEBOOK u8"\uf09a"
#define ICON_FA_FACEBOOK_F u8"\uf39e"
#define ICON_FA_FACEBOOK_MESSENGER u8"\uf39f"
#define ICON_FA_FACEBOOK_SQUARE u8"\uf082"
#define ICON_FA_FANTASY_FLIGHT_GAMES u8"\uf6dc"
#define ICON_FA_FEDEX u8"\uf797"
#define ICON_FA_FEDORA u8"\uf798"
#define ICON_FA_FIGMA u8"\uf799"
#define ICON_FA_FIREFOX u8"\uf269"
#define ICON_FA_FIRST_ORDER u8"\uf2b0"
#define ICON_FA_FIRST_ORDER_ALT u8"\uf50a"
#define ICON_FA_FIRSTDRAFT u8"\uf3a1"
#define ICON_FA_FLICKR u8"\uf16e"
#define ICON_FA_FLIPBOARD u8"\uf44d"
#define ICON_FA_FLY u8"\uf417"
#define ICON_FA_FONT_AWESOME u8"\uf2b4"
#define ICON_FA_FONT_AWESOME_ALT u8"\uf35c"
#define ICON_FA_FONT_AWESOME_FLAG u8"\uf425"
#define ICON_FA_FONT_AWESOME_LOGO_FULL u8"\uf4e6"
#define ICON_FA_FONTICONS u8"\uf280"
#define ICON_FA_FONTICONS_FI u8"\uf3a2"
#define ICON_FA_FORT_AWESOME u8"\uf286"
#define ICON_FA_FORT_AWESOME_ALT u8"\uf3a3"
#define ICON_FA_FORUMBEE u8"\uf211"
#define ICON_FA_FOURSQUARE u8"\uf180"
#define ICON_FA_FREE_CODE_CAMP u8"\uf2c5"
#define ICON_FA_FREEBSD u8"\uf3a4"
#define ICON_FA_FULCRUM u8"\uf50b"
#define ICON_FA_GALACTIC_REPUBLIC u8"\uf50c"
#define ICON_FA_GALACTIC_SENATE u8"\uf50d"
#define ICON_FA_GET_POCKET u8"\uf265"
#define ICON_FA_GG u8"\uf260"
#define ICON_FA_GG_CIRCLE u8"\uf261"
#define ICON_FA_GIT u8"\uf1d3"
#define ICON_FA_GIT_ALT u8"\uf841"
#define ICON_FA_GIT_SQUARE u8"\uf1d2"
#define ICON_FA_GITHUB u8"\uf09b"
#define ICON_FA_GITHUB_ALT u8"\uf113"
#define ICON_FA_GITHUB_SQUARE u8"\uf092"
#define ICON_FA_GITKRAKEN u8"\uf3a6"
#define ICON_FA_GITLAB u8"\uf296"
#define ICON_FA_GITTER u8"\uf426"
#define ICON_FA_GLIDE u8"\uf2a5"
#define ICON_FA_GLIDE_G u8"\uf2a6"
#define ICON_FA_GOFORE u8"\uf3a7"
#define ICON_FA_GOODREADS u8"\uf3a8"
#define ICON_FA_GOODREADS_G u8"\uf3a9"
#define ICON_FA_GOOGLE u8"\uf1a0"
#define ICON_FA_GOOGLE_DRIVE u8"\uf3aa"
#define ICON_FA_GOOGLE_PLAY u8"\uf3ab"
#define ICON_FA_GOOGLE_PLUS u8"\uf2b3"
#define ICON_FA_GOOGLE_PLUS_G u8"\uf0d5"
#define ICON_FA_GOOGLE_PLUS_SQUARE u8"\uf0d4"
#define ICON_FA_GOOGLE_WALLET u8"\uf1ee"
#define ICON_FA_GRATIPAY u8"\uf184"
#define ICON_FA_GRAV u8"\uf2d6"
#define ICON_FA_GRIPFIRE u8"\uf3ac"
#define ICON_FA_GRUNT u8"\uf3ad"
#define ICON_FA_GULP u8"\uf3ae"
#define ICON_FA_HACKER_NEWS u8"\uf1d4"
#define ICON_FA_HACKER_NEWS_SQUARE u8"\uf3af"
#define ICON_FA_HACKERRANK u8"\uf5f7"
#define ICON_FA_HIPS u8"\uf452"
#define ICON_FA_HIRE_A_HELPER u8"\uf3b0"
#define ICON_FA_HOOLI u8"\uf427"
#define ICON_FA_HORNBILL u8"\uf592"
#define ICON_FA_HOTJAR u8"\uf3b1"
#define ICON_FA_HOUZZ u8"\uf27c"
#define ICON_FA_HTML5 u8"\uf13b"
#define ICON_FA_HUBSPOT u8"\uf3b2"
#define ICON_FA_IMDB u8"\uf2d8"
#define ICON_FA_INSTAGRAM u8"\uf16d"
#define ICON_FA_INTERCOM u8"\uf7af"
#define ICON_FA_INTERNET_EXPLORER u8"\uf26b"
#define ICON_FA_INVISION u8"\uf7b0"
#define ICON_FA_IOXHOST u8"\uf208"
#define ICON_FA_ITCH_IO u8"\uf83a"
#define ICON_FA_ITUNES u8"\uf3b4"
#define ICON_FA_ITUNES_NOTE u8"\uf3b5"
#define ICON_FA_JAVA u8"\uf4e4"
#define ICON_FA_JEDI_ORDER u8"\uf50e"
#define ICON_FA_JENKINS u8"\uf3b6"
#define ICON_FA_JIRA u8"\uf7b1"
#define ICON_FA_JOGET u8"\uf3b7"
#define ICON_FA_JOOMLA u8"\uf1aa"
#define ICON_FA_JS u8"\uf3b8"
#define ICON_FA_JS_SQUARE u8"\uf3b9"
#define ICON_FA_JSFIDDLE u8"\uf1cc"
#define ICON_FA_KAGGLE u8"\uf5fa"
#define ICON_FA_KEYBASE u8"\uf4f5"
#define ICON_FA_KEYCDN u8"\uf3ba"
#define ICON_FA_KICKSTARTER u8"\uf3bb"
#define ICON_FA_KICKSTARTER_K u8"\uf3bc"
#define ICON_FA_KORVUE u8"\uf42f"
#define ICON_FA_LARAVEL u8"\uf3bd"
#define ICON_FA_LASTFM u8"\uf202"
#define ICON_FA_LASTFM_SQUARE u8"\uf203"
#define ICON_FA_LEANPUB u8"\uf212"
#define ICON_FA_LESS u8"\uf41d"
#define ICON_FA_LINE u8"\uf3c0"
#define ICON_FA_LINKEDIN u8"\uf08c"
#define ICON_FA_LINKEDIN_IN u8"\uf0e1"
#define ICON_FA_LINODE u8"\uf2b8"
#define ICON_FA_LINUX u8"\uf17c"
#define ICON_FA_LYFT u8"\uf3c3"
#define ICON_FA_MAGENTO u8"\uf3c4"
#define ICON_FA_MAILCHIMP u8"\uf59e"
#define ICON_FA_MANDALORIAN u8"\uf50f"
#define ICON_FA_MARKDOWN u8"\uf60f"
#define ICON_FA_MASTODON u8"\uf4f6"
#define ICON_FA_MAXCDN u8"\uf136"
#define ICON_FA_MDB u8"\uf8ca"
#define ICON_FA_MEDAPPS u8"\uf3c6"
#define ICON_FA_MEDIUM u8"\uf23a"
#define ICON_FA_MEDIUM_M u8"\uf3c7"
#define ICON_FA_MEDRT u8"\uf3c8"
#define ICON_FA_MEETUP u8"\uf2e0"
#define ICON_FA_MEGAPORT u8"\uf5a3"
#define ICON_FA_MENDELEY u8"\uf7b3"
#define ICON_FA_MICROSOFT u8"\uf3ca"
#define ICON_FA_MIX u8"\uf3cb"
#define ICON_FA_MIXCLOUD u8"\uf289"
#define ICON_FA_MIZUNI u8"\uf3cc"
#define ICON_FA_MODX u8"\uf285"
#define ICON_FA_MONERO u8"\uf3d0"
#define ICON_FA_NAPSTER u8"\uf3d2"
#define ICON_FA_NEOS u8"\uf612"
#define ICON_FA_NIMBLR u8"\uf5a8"
#define ICON_FA_NODE u8"\uf419"
#define ICON_FA_NODE_JS u8"\uf3d3"
#define ICON_FA_NPM u8"\uf3d4"
#define ICON_FA_NS8 u8"\uf3d5"
#define ICON_FA_NUTRITIONIX u8"\uf3d6"
#define ICON_FA_ODNOKLASSNIKI u8"\uf263"
#define ICON_FA_ODNOKLASSNIKI_SQUARE u8"\uf264"
#define ICON_FA_OLD_REPUBLIC u8"\uf510"
#define ICON_FA_OPENCART u8"\uf23d"
#define ICON_FA_OPENID u8"\uf19b"
#define ICON_FA_OPERA u8"\uf26a"
#define ICON_FA_OPTIN_MONSTER u8"\uf23c"
#define ICON_FA_ORCID u8"\uf8d2"
#define ICON_FA_OSI u8"\uf41a"
#define ICON_FA_PAGE4 u8"\uf3d7"
#define ICON_FA_PAGELINES u8"\uf18c"
#define ICON_FA_PALFED u8"\uf3d8"
#define ICON_FA_PATREON u8"\uf3d9"
#define ICON_FA_PAYPAL u8"\uf1ed"
#define ICON_FA_PENNY_ARCADE u8"\uf704"
#define ICON_FA_PERISCOPE u8"\uf3da"
#define ICON_FA_PHABRICATOR u8"\uf3db"
#define ICON_FA_PHOENIX_FRAMEWORK u8"\uf3dc"
#define ICON_FA_PHOENIX_SQUADRON u8"\uf511"
#define ICON_FA_PHP u8"\uf457"
#define ICON_FA_PIED_PIPER u8"\uf2ae"
#define ICON_FA_PIED_PIPER_ALT u8"\uf1a8"
#define ICON_FA_PIED_PIPER_HAT u8"\uf4e5"
#define ICON_FA_PIED_PIPER_PP u8"\uf1a7"
#define ICON_FA_PINTEREST u8"\uf0d2"
#define ICON_FA_PINTEREST_P u8"\uf231"
#define ICON_FA_PINTEREST_SQUARE u8"\uf0d3"
#define ICON_FA_PLAYSTATION u8"\uf3df"
#define ICON_FA_PRODUCT_HUNT u8"\uf288"
#define ICON_FA_PUSHED u8"\uf3e1"
#define ICON_FA_PYTHON u8"\uf3e2"
#define ICON_FA_QQ u8"\uf1d6"
#define ICON_FA_QUINSCAPE u8"\uf459"
#define ICON_FA_QUORA u8"\uf2c4"
#define ICON_FA_R_PROJECT u8"\uf4f7"
#define ICON_FA_RASPBERRY_PI u8"\uf7bb"
#define ICON_FA_RAVELRY u8"\uf2d9"
#define ICON_FA_REACT u8"\uf41b"
#define ICON_FA_REACTEUROPE u8"\uf75d"
#define ICON_FA_README u8"\uf4d5"
#define ICON_FA_REBEL u8"\uf1d0"
#define ICON_FA_RED_RIVER u8"\uf3e3"
#define ICON_FA_REDDIT u8"\uf1a1"
#define ICON_FA_REDDIT_ALIEN u8"\uf281"
#define ICON_FA_REDDIT_SQUARE u8"\uf1a2"
#define ICON_FA_REDHAT u8"\uf7bc"
#define ICON_FA_RENREN u8"\uf18b"
#define ICON_FA_REPLYD u8"\uf3e6"
#define ICON_FA_RESEARCHGATE u8"\uf4f8"
#define ICON_FA_RESOLVING u8"\uf3e7"
#define ICON_FA_REV u8"\uf5b2"
#define ICON_FA_ROCKETCHAT u8"\uf3e8"
#define ICON_FA_ROCKRMS u8"\uf3e9"
#define ICON_FA_SAFARI u8"\uf267"
#define ICON_FA_SALESFORCE u8"\uf83b"
#define ICON_FA_SASS u8"\uf41e"
#define ICON_FA_SCHLIX u8"\uf3ea"
#define ICON_FA_SCRIBD u8"\uf28a"
#define ICON_FA_SEARCHENGIN u8"\uf3eb"
#define ICON_FA_SELLCAST u8"\uf2da"
#define ICON_FA_SELLSY u8"\uf213"
#define ICON_FA_SERVICESTACK u8"\uf3ec"
#define ICON_FA_SHIRTSINBULK u8"\uf214"
#define ICON_FA_SHOPWARE u8"\uf5b5"
#define ICON_FA_SIMPLYBUILT u8"\uf215"
#define ICON_FA_SISTRIX u8"\uf3ee"
#define ICON_FA_SITH u8"\uf512"
#define ICON_FA_SKETCH u8"\uf7c6"
#define ICON_FA_SKYATLAS u8"\uf216"
#define ICON_FA_SKYPE u8"\uf17e"
#define ICON_FA_SLACK u8"\uf198"
#define ICON_FA_SLACK_HASH u8"\uf3ef"
#define ICON_FA_SLIDESHARE u8"\uf1e7"
#define ICON_FA_SNAPCHAT u8"\uf2ab"
#define ICON_FA_SNAPCHAT_GHOST u8"\uf2ac"
#define ICON_FA_SNAPCHAT_SQUARE u8"\uf2ad"
#define ICON_FA_SOUNDCLOUD u8"\uf1be"
#define ICON_FA_SOURCETREE u8"\uf7d3"
#define ICON_FA_SPEAKAP u8"\uf3f3"
#define ICON_FA_SPEAKER_DECK u8"\uf83c"
#define ICON_FA_SPOTIFY u8"\uf1bc"
#define ICON_FA_SQUARESPACE u8"\uf5be"
#define ICON_FA_STACK_EXCHANGE u8"\uf18d"
#define ICON_FA_STACK_OVERFLOW u8"\uf16c"
#define ICON_FA_STACKPATH u8"\uf842"
#define ICON_FA_STAYLINKED u8"\uf3f5"
#define ICON_FA_STEAM u8"\uf1b6"
#define ICON_FA_STEAM_SQUARE u8"\uf1b7"
#define ICON_FA_STEAM_SYMBOL u8"\uf3f6"
#define ICON_FA_STICKER_MULE u8"\uf3f7"
#define ICON_FA_STRAVA u8"\uf428"
#define ICON_FA_STRIPE u8"\uf429"
#define ICON_FA_STRIPE_S u8"\uf42a"
#define ICON_FA_STUDIOVINARI u8"\uf3f8"
#define ICON_FA_STUMBLEUPON u8"\uf1a4"
#define ICON_FA_STUMBLEUPON_CIRCLE u8"\uf1a3"
#define ICON_FA_SUPERPOWERS u8"\uf2dd"
#define ICON_FA_SUPPLE u8"\uf3f9"
#define ICON_FA_SUSE u8"\uf7d6"
#define ICON_FA_SWIFT u8"\uf8e1"
#define ICON_FA_SYMFONY u8"\uf83d"
#define ICON_FA_TEAMSPEAK u8"\uf4f9"
#define ICON_FA_TELEGRAM u8"\uf2c6"
#define ICON_FA_TELEGRAM_PLANE u8"\uf3fe"
#define ICON_FA_TENCENT_WEIBO u8"\uf1d5"
#define ICON_FA_THE_RED_YETI u8"\uf69d"
#define ICON_FA_THEMECO u8"\uf5c6"
#define ICON_FA_THEMEISLE u8"\uf2b2"
#define ICON_FA_THINK_PEAKS u8"\uf731"
#define ICON_FA_TRADE_FEDERATION u8"\uf513"
#define ICON_FA_TRELLO u8"\uf181"
#define ICON_FA_TRIPADVISOR u8"\uf262"
#define ICON_FA_TUMBLR u8"\uf173"
#define ICON_FA_TUMBLR_SQUARE u8"\uf174"
#define ICON_FA_TWITCH u8"\uf1e8"
#define ICON_FA_TWITTER u8"\uf099"
#define ICON_FA_TWITTER_SQUARE u8"\uf081"
#define ICON_FA_TYPO3 u8"\uf42b"
#define ICON_FA_UBER u8"\uf402"
#define ICON_FA_UBUNTU u8"\uf7df"
#define ICON_FA_UIKIT u8"\uf403"
#define ICON_FA_UMBRACO u8"\uf8e8"
#define ICON_FA_UNIREGISTRY u8"\uf404"
#define ICON_FA_UNTAPPD u8"\uf405"
#define ICON_FA_UPS u8"\uf7e0"
#define ICON_FA_USB u8"\uf287"
#define ICON_FA_USPS u8"\uf7e1"
#define ICON_FA_USSUNNAH u8"\uf407"
#define ICON_FA_VAADIN u8"\uf408"
#define ICON_FA_VIACOIN u8"\uf237"
#define ICON_FA_VIADEO u8"\uf2a9"
#define ICON_FA_VIADEO_SQUARE u8"\uf2aa"
#define ICON_FA_VIBER u8"\uf409"
#define ICON_FA_VIMEO u8"\uf40a"
#define ICON_FA_VIMEO_SQUARE u8"\uf194"
#define ICON_FA_VIMEO_V u8"\uf27d"
#define ICON_FA_VINE u8"\uf1ca"
#define ICON_FA_VK u8"\uf189"
#define ICON_FA_VNV u8"\uf40b"
#define ICON_FA_VUEJS u8"\uf41f"
#define ICON_FA_WAZE u8"\uf83f"
#define ICON_FA_WEEBLY u8"\uf5cc"
#define ICON_FA_WEIBO u8"\uf18a"
#define ICON_FA_WEIXIN u8"\uf1d7"
#define ICON_FA_WHATSAPP u8"\uf232"
#define ICON_FA_WHATSAPP_SQUARE u8"\uf40c"
#define ICON_FA_WHMCS u8"\uf40d"
#define ICON_FA_WIKIPEDIA_W u8"\uf266"
#define ICON_FA_WINDOWS u8"\uf17a"
#define ICON_FA_WIX u8"\uf5cf"
#define ICON_FA_WIZARDS_OF_THE_COAST u8"\uf730"
#define ICON_FA_WOLF_PACK_BATTALION u8"\uf514"
#define ICON_FA_WORDPRESS u8"\uf19a"
#define ICON_FA_WORDPRESS_SIMPLE u8"\uf411"
#define ICON_FA_WPBEGINNER u8"\uf297"
#define ICON_FA_WPEXPLORER u8"\uf2de"
#define ICON_FA_WPFORMS u8"\uf298"
#define ICON_FA_WPRESSR u8"\uf3e4"
#define ICON_FA_XBOX u8"\uf412"
#define ICON_FA_XING u8"\uf168"
#define ICON_FA_XING_SQUARE u8"\uf169"
#define ICON_FA_Y_COMBINATOR u8"\uf23b"
#define ICON_FA_YAHOO u8"\uf19e"
#define ICON_FA_YAMMER u8"\uf840"
#define ICON_FA_YANDEX u8"\uf413"
#define ICON_FA_YANDEX_INTERNATIONAL u8"\uf414"
#define ICON_FA_YARN u8"\uf7e3"
#define ICON_FA_YELP u8"\uf1e9"
#define ICON_FA_YOAST u8"\uf2b1"
#define ICON_FA_YOUTUBE u8"\uf167"
#define ICON_FA_YOUTUBE_SQUARE u8"\uf431"
#define ICON_FA_ZHIHU u8"\uf63f" | 9,050 |
478 | <reponame>hawesy/qlcplus
/*
Q Light Controller
ftd2xx-interface.cpp
Copyright (C) <NAME>
<NAME>
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.txt
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 "ftd2xx-interface.h"
#include "enttecdmxusbpro.h"
#include <ftd2xx.h>
/**
* Get some interesting strings from the device.
*
* @param deviceIndex The device index, whose strings to get
* @param vendor Returned vendor string
* @param description Returned description string
* @param serial Returned serial string
* @return FT_OK if strings were extracted successfully
*/
static FT_STATUS get_interface_info(DWORD deviceIndex,
QString& vendor, QString& description,
QString& serial, quint16 &VID, quint16 &PID)
{
char cVendor[256];
char cVendorId[256];
char cDescription[256];
char cSerial[256];
FT_HANDLE handle;
FT_STATUS status = FT_Open(deviceIndex, &handle);
if (status != FT_OK)
return status;
FT_PROGRAM_DATA pData;
pData.Signature1 = 0;
pData.Signature2 = 0xFFFFFFFF;
pData.Version = 0x00000005;
pData.Manufacturer = cVendor;
pData.ManufacturerId = cVendorId;
pData.Description = cDescription;
pData.SerialNumber = cSerial;
status = FT_EE_Read(handle, &pData);
if (status == FT_OK)
{
VID = pData.VendorId;
PID = pData.ProductId;
if (pData.ProductId == DMXInterface::DMX4ALLPID)
vendor = QString("DMX4ALL");
else
vendor = QString(cVendor);
description = QString(cDescription);
serial = QString(cSerial);
}
FT_Close(handle);
return status;
}
FTD2XXInterface::FTD2XXInterface(const QString& serial, const QString& name, const QString& vendor,
quint16 VID, quint16 PID, quint32 id)
: DMXInterface(serial, name, vendor, VID, PID , id)
, m_handle(NULL)
{
}
FTD2XXInterface::~FTD2XXInterface()
{
if (isOpen() == true)
close();
}
QString FTD2XXInterface::readLabel(uchar label, int *ESTA_code)
{
FT_HANDLE ftdi = NULL;
if (FT_Open(id(), &ftdi) != FT_OK)
return QString();
if(FT_ResetDevice(ftdi) != FT_OK)
return QString();
if(FT_SetBaudRate(ftdi, 250000) != FT_OK)
return QString();
if(FT_SetDataCharacteristics(ftdi, FT_BITS_8, FT_STOP_BITS_2, FT_PARITY_NONE) != FT_OK)
return QString();
if(FT_SetFlowControl(ftdi, 0, 0, 0) != FT_OK)
return QString();
QByteArray request;
request.append(ENTTEC_PRO_START_OF_MSG);
request.append(label);
request.append(ENTTEC_PRO_DMX_ZERO); // data length LSB
request.append(ENTTEC_PRO_DMX_ZERO); // data length MSB
request.append(ENTTEC_PRO_END_OF_MSG);
DWORD written = 0;
if (FT_Write(ftdi, (char*) request.data(), request.size(), &written) != FT_OK)
return QString();
if (written == 0)
{
qDebug() << Q_FUNC_INFO << "Cannot write data to device";
return QString();
}
uchar* buffer = (uchar*) malloc(sizeof(uchar) * 40);
Q_ASSERT(buffer != NULL);
int read = 0;
QByteArray array;
FT_SetTimeouts(ftdi, 500,0);
FT_Read(ftdi, buffer, 40, (LPDWORD) &read);
qDebug() << Q_FUNC_INFO << "----- Read: " << read << " ------";
for (int i = 0; i < read; i++)
array.append((char) buffer[i]);
if (array[0] != ENTTEC_PRO_START_OF_MSG)
qDebug() << Q_FUNC_INFO << "Reply message wrong start code: " << QString::number(array[0], 16);
*ESTA_code = (array[5] << 8) | array[4];
array.remove(0, 6); // 4 bytes of Enttec protocol + 2 of ESTA ID
array.replace(ENTTEC_PRO_END_OF_MSG, '\0'); // replace Enttec termination with string termination
FT_Close(ftdi);
return QString(array);
}
DMXInterface::Type FTD2XXInterface::type()
{
return DMXInterface::FTD2xx;
}
QString FTD2XXInterface::typeString()
{
return "FTD2xx";
}
QList<DMXInterface *> FTD2XXInterface::interfaces(QList<DMXInterface *> discoveredList)
{
QList <DMXInterface*> interfacesList;
/* Find out the number of FTDI devices present */
DWORD num = 0;
FT_STATUS status = FT_CreateDeviceInfoList(&num);
if (status != FT_OK || num <= 0)
{
qWarning() << Q_FUNC_INFO << "[FTD2XXInterface] Error in FT_CreateDeviceInfoList:" << status;
return interfacesList;
}
// Allocate storage for list based on numDevices
FT_DEVICE_LIST_INFO_NODE* devInfo = new FT_DEVICE_LIST_INFO_NODE[num];
// Get the device information list
if (FT_GetDeviceInfoList(devInfo, &num) == FT_OK)
{
int id = 0;
for (DWORD i = 0; i < num; i++)
{
QString vendor, name, serial;
quint16 VID, PID;
FT_STATUS s = get_interface_info(i, vendor, name, serial, VID, PID);
if (s != FT_OK || name.isEmpty() || serial.isEmpty())
{
// Seems that some otherwise working devices don't provide
// FT_PROGRAM_DATA struct used by get_interface_info().
name = QString(devInfo[i].Description);
serial = QString(devInfo[i].SerialNumber);
vendor = QString();
}
qDebug() << "serial: " << serial << "name:" << name << "vendor:" << vendor;
bool found = false;
for (int c = 0; c < discoveredList.count(); c++)
{
if (discoveredList.at(c)->checkInfo(serial, name, vendor) == true)
{
found = true;
break;
}
}
if (found == false)
{
FTD2XXInterface *iface = new FTD2XXInterface(serial, name, vendor, VID, PID, id);
interfacesList << iface;
}
id++;
}
}
delete [] devInfo;
return interfacesList;
}
bool FTD2XXInterface::open()
{
if (isOpen() == true)
return true;
FT_STATUS status = FT_Open(id(), &m_handle);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << "Error opening" << name() << status;
return false;
}
status = FT_GetLatencyTimer(m_handle, &m_defaultLatency);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
m_defaultLatency = 16;
}
qDebug() << Q_FUNC_INFO << serial() << "Default latency is" << m_defaultLatency;
return true;
}
bool FTD2XXInterface::openByPID(const int PID)
{
Q_UNUSED(PID)
return open();
}
bool FTD2XXInterface::close()
{
FT_STATUS status = FT_Close(m_handle);
m_handle = NULL;
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::isOpen() const
{
return (m_handle != NULL) ? true : false;
}
bool FTD2XXInterface::reset()
{
FT_STATUS status = FT_ResetDevice(m_handle);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::setLineProperties()
{
FT_STATUS status = FT_SetDataCharacteristics(m_handle, FT_BITS_8, FT_STOP_BITS_2, FT_PARITY_NONE);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::setBaudRate()
{
FT_STATUS status = FT_SetBaudRate(m_handle, 250000);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::setFlowControl()
{
FT_STATUS status = FT_SetFlowControl(m_handle, 0, 0, 0);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::setLowLatency(bool lowLatency)
{
unsigned char latency;
if (lowLatency)
{
latency = 1;
}
else
{
latency = m_defaultLatency;
}
FT_STATUS status = FT_SetLatencyTimer(m_handle, latency);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::clearRts()
{
FT_STATUS status = FT_ClrRts(m_handle);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::purgeBuffers()
{
FT_STATUS status = FT_Purge(m_handle, FT_PURGE_RX | FT_PURGE_TX);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::setBreak(bool on)
{
FT_STATUS status;
if (on == true)
status = FT_SetBreakOn(m_handle);
else
status = FT_SetBreakOff(m_handle);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
bool FTD2XXInterface::write(const QByteArray& data)
{
DWORD written = 0;
FT_STATUS status = FT_Write(m_handle, (char*) data.data(), data.size(), &written);
if (status != FT_OK)
{
qWarning() << Q_FUNC_INFO << name() << status;
return false;
}
else
{
return true;
}
}
QByteArray FTD2XXInterface::read(int size, uchar* userBuffer)
{
if (m_handle == NULL)
return QByteArray();
DWORD RxBytes, TxBytes, event;
FT_GetStatus(m_handle, &RxBytes, &TxBytes, &event);
if (RxBytes < (DWORD)size)
return QByteArray();
uchar* buffer = NULL;
if (userBuffer == NULL)
buffer = (uchar*) malloc(sizeof(uchar) * size);
else
buffer = userBuffer;
Q_ASSERT(buffer != NULL);
int read = 0;
QByteArray array;
FT_Read(m_handle, buffer, size, (LPDWORD) &read);
if (userBuffer == NULL)
{
for (int i = 0; i < read; i++)
array.append((char) buffer[i]);
}
else
{
array = QByteArray((char*) buffer, read);
}
if (userBuffer == NULL)
free(buffer);
return array;
}
uchar FTD2XXInterface::readByte(bool* ok)
{
if (ok) *ok = false;
if (m_handle == NULL)
return 0;
DWORD RxBytes, TxBytes, event;
FT_GetStatus(m_handle, &RxBytes, &TxBytes, &event);
if (RxBytes < 1)
return 0;
uchar byte = 0;
int read = 0;
FT_Read(m_handle, &byte, 1, (LPDWORD) &read);
if (read == 1)
{
if (ok) *ok = true;
return byte;
}
return 0;
}
| 5,117 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-f434-223j-r8rm",
"modified": "2022-05-01T17:54:34Z",
"published": "2022-05-01T17:54:34Z",
"aliases": [
"CVE-2007-1522"
],
"details": "Double free vulnerability in the session extension in PHP 5.2.0 and 5.2.1 allows context-dependent attackers to execute arbitrary code via illegal characters in a session identifier, which is rejected by an internal session storage module, which calls the session identifier generator with an improper environment, leading to code execution when the generator is interrupted, as demonstrated by triggering a memory limit violation or certain PHP errors.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2007-1522"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/24505"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/25056"
},
{
"type": "WEB",
"url": "http://www.novell.com/linux/security/advisories/2007_32_php.html"
},
{
"type": "WEB",
"url": "http://www.php-security.org/MOPB/MOPB-23-2007.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/22971"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2007/0960"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 633 |
413 | import errno
import os
import locale
from datetime import datetime
try:
import pytz
HAS_PYTZ = True
except ImportError:
HAS_PYTZ = False
from i3pystatus import IntervalModule
class Clock(IntervalModule):
"""
This class shows a clock.
.. note:: Optionally requires `pytz` for time zone data when using time
zones other than local time.
Format can be passed in four different ways:
- single string, no timezone, just the strftime-format
- one two-tuple, first is the format, second the timezone
- list of strings - no timezones
- list of two tuples, first is the format, second is timezone
Use mousewheel to cycle between formats.
For complete time format specification see:
::
man strftime
All available timezones are located in directory:
::
/usr/share/zoneinfo/
.. rubric:: Format examples
::
# one format, local timezone
format = '%a %b %-d %b %X'
# multiple formats, local timezone
format = [ '%a %b %-d %b %X', '%X' ]
# one format, specified timezone
format = ('%a %b %-d %b %X', 'Europe/Bratislava')
# multiple formats, specified timezones
format = [ ('%a %b %-d %b %X', 'America/New_York'), ('%X', 'Etc/GMT+9') ]
"""
settings = (
("format", "`None` means to use the default, locale-dependent format."),
("color", "RGB hexadecimal code color specifier, default to #ffffff"),
)
format = None
color = "#ffffff"
interval = 1
on_upscroll = ["scroll_format", 1]
on_downscroll = ["scroll_format", -1]
def init(self):
env_lang = os.environ.get('LC_TIME', None)
if env_lang is None:
env_lang = os.environ.get('LANG', None)
if env_lang is not None:
if env_lang.find('.') != -1:
lang = tuple(env_lang.split('.', 1))
else:
lang = (env_lang, None)
else:
lang = (None, None)
if lang != locale.getlocale(locale.LC_TIME):
# affects language of *.strftime() in whole program
locale.setlocale(locale.LC_TIME, lang)
if self.format is None:
if lang[0] == 'en_US':
# MDY format - United States of America
self.format = ["%a %b %-d %X"]
else:
# DMY format - almost all other countries
self.format = ["%a %-d %b %X"]
elif isinstance(self.format, str) or isinstance(self.format, tuple):
self.format = [self.format]
self.system_tz = self._get_system_tz()
self.format = [self._expand_format(fmt) for fmt in self.format]
self.current_format_id = 0
def _expand_format(self, fmt):
if isinstance(fmt, tuple):
if len(fmt) == 1:
return (fmt[0], None)
else:
if not HAS_PYTZ:
raise RuntimeError("Need `pytz` for timezone data")
return (fmt[0], pytz.timezone(fmt[1]))
return (fmt, self.system_tz)
def _get_system_tz(self):
'''
Get the system timezone for use when no timezone is explicitly provided
Requires pytz, if not available then no timezone will be set when not
explicitly provided.
'''
if not HAS_PYTZ:
return None
def _etc_localtime():
try:
with open('/etc/localtime', 'rb') as fp:
return pytz.tzfile.build_tzinfo('system', fp)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/localtime contains unrecognized tzinfo'
)
return None
def _etc_timezone():
try:
with open('/etc/timezone', 'r') as fp:
tzname = fp.read().strip()
return pytz.timezone(tzname)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/timezone contains unrecognized timezone \'%s\'',
tzname
)
return None
return _etc_localtime() or _etc_timezone()
def run(self):
time = datetime.now(self.format[self.current_format_id][1])
self.output = {
"full_text": time.strftime(self.format[self.current_format_id][0]),
"color": self.color,
"urgent": False,
}
def scroll_format(self, step=1):
self.current_format_id = (self.current_format_id + step) % len(self.format)
| 2,460 |
432 | /*
* Copyright (C) 2020 ActiveJ LLC.
*
* 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.activej.cube.attributes;
import io.activej.async.service.EventloopService;
import io.activej.eventloop.Eventloop;
import io.activej.eventloop.jmx.EventloopJmxBean;
import io.activej.eventloop.schedule.ScheduledRunnable;
import io.activej.jmx.api.attribute.JmxAttribute;
import io.activej.jmx.api.attribute.JmxOperation;
import io.activej.jmx.stats.ValueStats;
import io.activej.promise.Promise;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import static io.activej.common.Utils.nullify;
public abstract class ReloadingAttributeResolver<K, A> extends AbstractAttributeResolver<K, A> implements EventloopService, EventloopJmxBean {
protected final Eventloop eventloop;
private long timestamp;
private long reloadPeriod;
private long retryPeriod = 1000L;
private @Nullable ScheduledRunnable scheduledRunnable;
private final Map<K, A> cache = new HashMap<>();
private int reloads;
private int reloadErrors;
private int resolveErrors;
private K lastResolveErrorKey;
private final ValueStats reloadTime = ValueStats.create(Duration.ofHours(1)).withRate("reloads").withUnit("milliseconds");
protected ReloadingAttributeResolver(Eventloop eventloop) {
this.eventloop = eventloop;
}
@Override
protected final @Nullable A resolveAttributes(K key) {
A result = cache.get(key);
if (result == null) {
resolveErrors++;
lastResolveErrorKey = key;
}
return result;
}
protected abstract Promise<Map<K, A>> reload(long lastTimestamp);
private void doReload() {
reloads++;
scheduledRunnable = nullify(scheduledRunnable, ScheduledRunnable::cancel);
long reloadTimestamp = eventloop.currentTimeMillis();
reload(timestamp)
.whenResult(result -> {
reloadTime.recordValue((int) (eventloop.currentTimeMillis() - reloadTimestamp));
cache.putAll(result);
timestamp = reloadTimestamp;
})
.whenException(e -> reloadErrors++)
.whenComplete(() -> scheduleReload(retryPeriod));
}
private void scheduleReload(long period) {
scheduledRunnable = eventloop.delayBackground(period, this::doReload);
}
@Override
public @NotNull Eventloop getEventloop() {
return eventloop;
}
@Override
public @NotNull Promise<Void> start() {
if (reloadPeriod == 0) return Promise.complete();
long reloadTimestamp = eventloop.currentTimeMillis();
return reload(timestamp)
.whenResult(result -> {
reloadTime.recordValue((int) (eventloop.currentTimeMillis() - reloadTimestamp));
cache.putAll(result);
timestamp = reloadTimestamp;
scheduleReload(reloadPeriod);
})
.toVoid();
}
@Override
public @NotNull Promise<Void> stop() {
scheduledRunnable = nullify(scheduledRunnable, ScheduledRunnable::cancel);
return Promise.complete();
}
@JmxOperation
public void reload() {
doReload();
}
@JmxAttribute
public long getReloadPeriod() {
return reloadPeriod;
}
@JmxAttribute
public void setReloadPeriod(long reloadPeriod) {
this.reloadPeriod = reloadPeriod;
}
@JmxAttribute
public long getRetryPeriod() {
return retryPeriod;
}
@JmxAttribute
public void setRetryPeriod(long retryPeriod) {
this.retryPeriod = retryPeriod;
}
@JmxAttribute
public int getReloads() {
return reloads;
}
@JmxAttribute
public int getReloadErrors() {
return reloadErrors;
}
@JmxAttribute
public int getResolveErrors() {
return resolveErrors;
}
@JmxAttribute
public @Nullable String getLastResolveErrorKey() {
return lastResolveErrorKey == null ? null : lastResolveErrorKey.toString();
}
@JmxAttribute
public ValueStats getReloadTime() {
return reloadTime;
}
}
| 1,530 |
335 | <gh_stars>100-1000
{
"word": "Phosphorescence",
"definitions": [
"Light emitted by a substance without combustion or perceptible heat.",
"The emission of radiation in a similar manner to fluorescence but on a longer timescale, so that emission continues after excitation ceases."
],
"parts-of-speech": "Noun"
} | 110 |
60,067 | from typing import NamedTuple
import torch
class MyNamedTup(NamedTuple):
i : torch.Tensor
f : torch.Tensor
| 45 |
364 | <reponame>xiaobing007/dagli<filename>xgboost-core/src/main/java/com/linkedin/dagli/xgboost/XGBoostRegression.java
package com.linkedin.dagli.xgboost;
import com.linkedin.dagli.annotation.equality.HandleEquality;
import com.linkedin.dagli.annotation.equality.ValueEquality;
import com.linkedin.dagli.math.vector.DenseVector;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import ml.dmlc.xgboost4j.java.Booster;
/**
* Gradient Boosted Decision Tree regression. The "labels" for training this regression can be any {@link Number}s,
* though the actual predictions resulting from the model will be {@link Float}s.
*/
@ValueEquality
public class XGBoostRegression extends AbstractXGBoostModel<Number, Float, XGBoostRegression.Prepared, XGBoostRegression> {
private static final long serialVersionUID = 1;
@Override
protected XGBoostObjective getObjective(int labelCount) {
return XGBoostObjective.REGRESSION_SQUARED_ERROR;
}
@Override
protected XGBoostObjectiveType getObjectiveType() {
return XGBoostObjectiveType.REGRESSION;
}
@Override
protected Prepared createPrepared(Object2IntOpenHashMap<Number> labelMap, Booster booster) {
return new Prepared(booster);
}
/**
* A trained XGBoost regression model.
*/
@HandleEquality
public static class Prepared
extends AbstractXGBoostModel.Prepared<Number, Float, Prepared> {
private static final long serialVersionUID = 1;
/**
* Creates a new instance.
*
* @param booster the trained XGBoost regression model.
*/
public Prepared(Booster booster) {
super(booster);
}
@Override
public Float apply(Number weight, Number label, DenseVector vector) {
return XGBoostModel.predictAsFloats(_booster, vector, (booster, dmatrix) -> booster.predict(dmatrix)[0])[0];
}
}
}
| 639 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.