repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
Testiduk/gitlabhq | spec/views/admin/application_settings/_repository_storage.html.haml_spec.rb | <reponame>Testiduk/gitlabhq
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'admin/application_settings/_repository_storage.html.haml' do
let(:app_settings) { build(:application_setting, repository_storages_weighted: repository_storages_weighted) }
before do
stub_storage_settings({ 'default': {}, 'mepmep': {}, 'foobar': {} })
assign(:application_setting, app_settings)
end
context 'additional storage config' do
let(:repository_storages_weighted) do
{
'default' => 100,
'mepmep' => 50
}
end
it 'lists them all' do
render
Gitlab.config.repositories.storages.keys.each do |storage_name|
expect(rendered).to have_content(storage_name)
end
expect(rendered).to have_content('foobar')
end
end
context 'fewer storage configs' do
let(:repository_storages_weighted) do
{
'default' => 100,
'mepmep' => 50,
'something_old' => 100
}
end
it 'lists only configured storages' do
render
Gitlab.config.repositories.storages.keys.each do |storage_name|
expect(rendered).to have_content(storage_name)
end
expect(rendered).not_to have_content('something_old')
end
end
end
|
dumpmemory/zenml | src/zenml/integrations/kubeflow/metadata_stores/kubeflow_metadata_store.py | # Copyright (c) ZenML GmbH 2021. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
import os
import subprocess
import sys
import time
from typing import ClassVar, Optional, Tuple, Union, cast
from kubernetes import config as k8s_config
from ml_metadata.proto import metadata_store_pb2
from zenml.exceptions import ProvisioningError
from zenml.integrations.constants import KUBEFLOW
from zenml.integrations.kubeflow import KUBEFLOW_METADATA_STORE_FLAVOR
from zenml.integrations.kubeflow.orchestrators.kubeflow_orchestrator import (
KubeflowOrchestrator,
)
from zenml.io import fileio
from zenml.logger import get_logger
from zenml.metadata_stores import BaseMetadataStore
from zenml.repository import Repository
from zenml.stack import StackValidator
from zenml.stack.stack import Stack
from zenml.utils import networking_utils
logger = get_logger(__name__)
def inside_kfp_pod() -> bool:
"""Returns if the current python process is running inside a KFP Pod."""
if "KFP_POD_NAME" not in os.environ:
return False
try:
k8s_config.load_incluster_config()
return True
except k8s_config.ConfigException:
return False
DEFAULT_KFP_METADATA_GRPC_PORT = 8081
DEFAULT_KFP_METADATA_DAEMON_TIMEOUT = 60
class KubeflowMetadataStore(BaseMetadataStore):
"""Kubeflow GRPC backend for ZenML metadata store."""
upgrade_migration_enabled: bool = False
host: str = "127.0.0.1"
port: int = DEFAULT_KFP_METADATA_GRPC_PORT
# Class Configuration
FLAVOR: ClassVar[str] = KUBEFLOW_METADATA_STORE_FLAVOR
@property
def validator(self) -> Optional[StackValidator]:
"""Validates that the stack contains a KFP orchestrator."""
def _ensure_kfp_orchestrator(stack: Stack) -> Tuple[bool, str]:
return (
stack.orchestrator.FLAVOR == KUBEFLOW,
"The Kubeflow metadata store can only be used with a Kubeflow "
"orchestrator.",
)
return StackValidator(
custom_validation_function=_ensure_kfp_orchestrator
)
def get_tfx_metadata_config(
self,
) -> Union[
metadata_store_pb2.ConnectionConfig,
metadata_store_pb2.MetadataStoreClientConfig,
]:
"""Return tfx metadata config for the kubeflow metadata store."""
connection_config = metadata_store_pb2.MetadataStoreClientConfig()
if inside_kfp_pod():
connection_config.host = os.environ["METADATA_GRPC_SERVICE_HOST"]
connection_config.port = int(
os.environ["METADATA_GRPC_SERVICE_PORT"]
)
else:
if not self.is_running:
raise RuntimeError(
"The KFP metadata daemon is not running. Please run the "
"following command to start it first:\n\n"
" 'zenml metadata-store up'\n"
)
connection_config.host = self.host
connection_config.port = self.port
return connection_config
@property
def kfp_orchestrator(self) -> KubeflowOrchestrator:
"""Returns the Kubeflow orchestrator in the active stack."""
repo = Repository(skip_repository_check=True) # type: ignore[call-arg]
return cast(KubeflowOrchestrator, repo.active_stack.orchestrator)
@property
def kubernetes_context(self) -> str:
"""Returns the kubernetes context to the cluster where the Kubeflow
Pipelines services are running."""
kubernetes_context = self.kfp_orchestrator.kubernetes_context
# will never happen, but mypy doesn't know that
assert kubernetes_context is not None
return kubernetes_context
@property
def root_directory(self) -> str:
"""Returns path to the root directory for all files concerning
this KFP metadata store.
Note: the root directory for the KFP metadata store is relative to the
root directory of the KFP orchestrator, because it is a sub-component
of it.
"""
return os.path.join(
self.kfp_orchestrator.root_directory,
"metadata-store",
str(self.uuid),
)
@property
def _pid_file_path(self) -> str:
"""Returns path to the daemon PID file."""
return os.path.join(self.root_directory, "kubeflow_daemon.pid")
@property
def _log_file(self) -> str:
"""Path of the daemon log file."""
return os.path.join(self.root_directory, "kubeflow_daemon.log")
@property
def is_provisioned(self) -> bool:
"""If the component provisioned resources to run locally."""
return fileio.exists(self.root_directory)
@property
def is_running(self) -> bool:
"""If the component is running locally."""
if sys.platform != "win32":
from zenml.utils.daemon import check_if_daemon_is_running
if not check_if_daemon_is_running(self._pid_file_path):
return False
else:
# Daemon functionality is not supported on Windows, so the PID
# file won't exist. This if clause exists just for mypy to not
# complain about missing functions
pass
return True
def provision(self) -> None:
"""Provisions resources to run the component locally."""
logger.info("Provisioning local Kubeflow Pipelines deployment...")
fileio.makedirs(self.root_directory)
def deprovision(self) -> None:
"""Deprovisions all local resources of the component."""
if fileio.exists(self._log_file):
fileio.remove(self._log_file)
logger.info("Local kubeflow pipelines deployment deprovisioned.")
def resume(self) -> None:
"""Resumes the local k3d cluster."""
if self.is_running:
logger.info("Local kubeflow pipelines deployment already running.")
return
self.start_kfp_metadata_daemon()
self.wait_until_metadata_store_ready()
def suspend(self) -> None:
"""Suspends the local k3d cluster."""
if not self.is_running:
logger.info("Local kubeflow pipelines deployment not running.")
return
self.stop_kfp_metadata_daemon()
def start_kfp_metadata_daemon(self) -> None:
"""Starts a daemon process that forwards ports so the Kubeflow Pipelines
Metadata MySQL database is accessible on the localhost."""
command = [
"kubectl",
"--context",
self.kubernetes_context,
"--namespace",
"kubeflow",
"port-forward",
"svc/metadata-grpc-service",
f"{self.port}:8080",
]
if sys.platform == "win32":
logger.warning(
"Daemon functionality not supported on Windows. "
"In order to access the Kubeflow Pipelines Metadata locally, "
"please run '%s' in a separate command line shell.",
self.port,
" ".join(command),
)
elif not networking_utils.port_available(self.port):
raise ProvisioningError(
f"Unable to port-forward Kubeflow Pipelines Metadata to local "
f"port {self.port} because the port is occupied. In order to "
f"access the Kubeflow Pipelines Metadata locally, please "
f"change the metadata store configuration to use an available "
f"port or stop the other process currently using the port."
)
else:
from zenml.utils import daemon
def _daemon_function() -> None:
"""Forwards the port of the Kubeflow Pipelines Metadata pod ."""
subprocess.check_call(command)
daemon.run_as_daemon(
_daemon_function,
pid_file=self._pid_file_path,
log_file=self._log_file,
)
logger.info(
"Started Kubeflow Pipelines Metadata daemon (check the daemon"
"logs at %s in case you're not able to access the pipeline"
"metadata).",
self._log_file,
)
def stop_kfp_metadata_daemon(self) -> None:
"""Stops the KFP Metadata daemon process if it is running."""
if fileio.exists(self._pid_file_path):
if sys.platform == "win32":
# Daemon functionality is not supported on Windows, so the PID
# file won't exist. This if clause exists just for mypy to not
# complain about missing functions
pass
else:
from zenml.utils import daemon
daemon.stop_daemon(self._pid_file_path)
fileio.remove(self._pid_file_path)
def wait_until_metadata_store_ready(
self, timeout: int = DEFAULT_KFP_METADATA_DAEMON_TIMEOUT
) -> None:
"""Waits until the metadata store connection is ready, an irrecoverable
error occurs or the timeout expires."""
logger.info(
"Waiting for the Kubeflow metadata store to be ready (this might "
"take a few minutes)."
)
while True:
try:
# it doesn't matter what we call here as long as it exercises
# the MLMD connection
self.get_pipelines()
break
except Exception as e:
logger.info(
"The Kubeflow metadata store is not ready yet. Waiting for "
"10 seconds..."
)
if timeout <= 0:
raise RuntimeError(
f"An unexpected error was encountered while waiting for the "
f"Kubeflow metadata store to be functional: {str(e)}"
) from e
timeout -= 10
time.sleep(10)
logger.info("The Kubeflow metadata store is functional.")
|
bitigchi/MuditaOS | module-bluetooth/Bluetooth/interface/profiles/A2DP/AVRCP.hpp | // Copyright (c) 2017-2021, Mudit<NAME>. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "A2DPImpl.hpp"
extern "C"
{
#include "classic/avrcp.h"
#include "classic/avrcp_browsing_controller.h"
#include "classic/avrcp_browsing_target.h"
#include "classic/avrcp_controller.h"
#include "classic/avrcp_media_item_iterator.h"
#include "classic/avrcp_target.h"
#include <btstack.h>
#include <btstack_defines.h>
}
namespace bluetooth
{
class AVRCP
{
public:
constexpr static const uint8_t subunitInfo[] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7};
constexpr static uint32_t companyId = 0x112233;
constexpr static uint8_t companiesNum = 1;
constexpr static uint8_t companies[] = {
0x00, 0x19, 0x58 // BT SIG registered CompanyID
};
constexpr static uint8_t eventsNum = 6;
constexpr static uint8_t events[] = {AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED,
AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED,
AVRCP_NOTIFICATION_EVENT_PLAYER_APPLICATION_SETTING_CHANGED,
AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED,
AVRCP_NOTIFICATION_EVENT_AVAILABLE_PLAYERS_CHANGED,
AVRCP_NOTIFICATION_EVENT_ADDRESSED_PLAYER_CHANGED};
static constexpr int SDP_BUFFER_LENGTH = 200;
struct PlaybackStatusInfo
{
uint8_t track_id[8];
uint32_t song_length_ms;
avrcp_playback_status_t status;
uint32_t song_position_ms; // 0xFFFFFFFF if not supported
};
static std::array<uint8_t, SDP_BUFFER_LENGTH> sdpTargetServiceBuffer;
static std::array<uint8_t, SDP_BUFFER_LENGTH> sdpControllerServiceBuffer;
static sys::Service *ownerService;
static avrcp_track_t tracks[3];
static int currentTrackIndex;
static PlaybackStatusInfo playInfo;
static MediaContext mediaTracker;
static void packetHandler(uint8_t packetType, uint16_t channel, uint8_t *packet, uint16_t size);
static void targetPacketHandler(uint8_t packetType, uint16_t channel, uint8_t *packet, uint16_t size);
static void controllerPacketHandler(uint8_t packetType, uint16_t channel, uint8_t *packet, uint16_t size);
static void init(sys::Service *service);
};
} // namespace Bt
|
cyberstormdotmu/dream-study-java | dream-study-java-common/src/main/java/com/wy/redis/DelayTimer.java | package com.wy.redis;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
*
*
* @author 飞花梦影
* @date 2021-10-29 16:44:59
* @git {@link https://github.com/dreamFlyingFlower }
*/
@Component
public class DelayTimer implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private DelayBucket delayBucket;
@Autowired
private TaskJobPool jobPool;
@Autowired
private ReadyQueue readyQueue;
@Value("${thread.size}")
private int length;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
ExecutorService executorService =
new ThreadPoolExecutor(length, length, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < length; i++) {
executorService.execute(new DelayJobHandler(delayBucket, jobPool, readyQueue, i));
}
}
} |
diegolovison/Hyperfoil | core/src/main/java/io/hyperfoil/core/parser/PhaseParser.java | <gh_stars>0
package io.hyperfoil.core.parser;
import io.hyperfoil.api.config.PhaseBuilder;
abstract class PhaseParser extends AbstractParser<PhaseBuilder.Catalog, PhaseBuilder> {
PhaseParser() {
register("startTime", new PropertyParser.String<>(PhaseBuilder::startTime));
register("startAfter", new StartAfterParser(PhaseBuilder::startAfter));
register("startAfterStrict", new StartAfterParser(PhaseBuilder::startAfterStrict));
register("duration", new PropertyParser.String<>(PhaseBuilder::duration));
register("maxDuration", new PropertyParser.String<>(PhaseBuilder::maxDuration));
register("maxUnfinishedSessions", new PropertyParser.Int<>(PhaseBuilder::maxUnfinishedSessions));
register("maxIterations", new PropertyParser.Int<>(PhaseBuilder::maxIterations));
register("scenario", new Adapter<>(PhaseBuilder::scenario, new ScenarioParser()));
register("forks", new PhaseForkParser());
}
@Override
public void parse(Context ctx, PhaseBuilder.Catalog target) throws ParserException {
callSubBuilders(ctx, type(target));
}
protected abstract PhaseBuilder type(PhaseBuilder.Catalog catalog);
static class AtOnce extends PhaseParser {
AtOnce() {
register("users", new IncrementPropertyParser.Int<>((builder, base, inc) -> ((PhaseBuilder.AtOnce) builder).users(base, inc)));
}
@Override
protected PhaseBuilder type(PhaseBuilder.Catalog catalog) {
return catalog.atOnce(-1);
}
}
static class Always extends PhaseParser {
Always() {
register("users", new IncrementPropertyParser.Int<>((builder, base, inc) -> ((PhaseBuilder.Always) builder).users(base, inc)));
}
@Override
protected PhaseBuilder type(PhaseBuilder.Catalog catalog) {
return catalog.always(-1);
}
}
static class RampPerSec extends PhaseParser {
RampPerSec() {
register("initialUsersPerSec", new IncrementPropertyParser.Double<>((builder, base, inc) -> ((PhaseBuilder.RampPerSec) builder).initialUsersPerSec(base, inc)));
register("targetUsersPerSec", new IncrementPropertyParser.Double<>((builder, base, inc) -> ((PhaseBuilder.RampPerSec) builder).targetUsersPerSec(base, inc)));
register("maxSessionsEstimate", new PropertyParser.Int<>((builder, sessions) -> ((PhaseBuilder.RampPerSec) builder).maxSessionsEstimate(sessions)));
register("variance", new PropertyParser.Boolean<>((builder, variance) -> ((PhaseBuilder.RampPerSec) builder).variance(variance)));
}
@Override
protected PhaseBuilder type(PhaseBuilder.Catalog catalog) {
return catalog.rampPerSec(-1, -1);
}
}
static class ConstantPerSec extends PhaseParser {
ConstantPerSec() {
register("usersPerSec", new IncrementPropertyParser.Double<>((builder, base, inc) -> ((PhaseBuilder.ConstantPerSec) builder).usersPerSec(base, inc)));
register("maxSessionsEstimate", new PropertyParser.Int<>((builder, sessions) -> ((PhaseBuilder.ConstantPerSec) builder).maxSessionsEstimate(sessions)));
register("variance", new PropertyParser.Boolean<>((builder, variance) -> ((PhaseBuilder.ConstantPerSec) builder).variance(variance)));
}
@Override
protected PhaseBuilder type(PhaseBuilder.Catalog catalog) {
return catalog.constantPerSec(-1);
}
}
}
|
J-VOL/mage | Mage/src/main/java/mage/game/permanent/token/VrondissRageOfAncientsToken.java | package mage.game.permanent.token;
import mage.MageInt;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.SacrificeSourceEffect;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
public final class VrondissRageOfAncientsToken extends TokenImpl {
public VrondissRageOfAncientsToken() {
super("Dragon Spirit", "5/4 red and green Dragon Spirit creature token with \"When this creature deals damage, sacrifice it.\"");
cardType.add(CardType.CREATURE);
color.setRed(true);
color.setGreen(true);
subtype.add(SubType.DRAGON);
subtype.add(SubType.SPIRIT);
power = new MageInt(5);
toughness = new MageInt(4);
this.addAbility(new VrondissRageOfAncientsTokenTriggeredAbility());
}
public VrondissRageOfAncientsToken(final VrondissRageOfAncientsToken token) {
super(token);
}
public VrondissRageOfAncientsToken copy() {
return new VrondissRageOfAncientsToken(this);
}
}
class VrondissRageOfAncientsTokenTriggeredAbility extends TriggeredAbilityImpl {
public VrondissRageOfAncientsTokenTriggeredAbility() {
super(Zone.BATTLEFIELD, new SacrificeSourceEffect(), false);
}
public VrondissRageOfAncientsTokenTriggeredAbility(final VrondissRageOfAncientsTokenTriggeredAbility ability) {
super(ability);
}
@Override
public VrondissRageOfAncientsTokenTriggeredAbility copy() {
return new VrondissRageOfAncientsTokenTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.DAMAGED_PLAYER
|| event.getType() == GameEvent.EventType.DAMAGED_PERMANENT;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
return event.getSourceId().equals(this.getSourceId());
}
@Override
public String getRule() {
return "When this creature deals damage, sacrifice it.";
}
}
|
fugazi/CypressPataconf | node_modules/@applitools/eyes-sdk-core/lib/fluent/FloatingRegionByRectangle.js | <reponame>fugazi/CypressPataconf<gh_stars>0
'use strict'
const {FloatingMatchSettings} = require('../..')
const {GetFloatingRegion} = require('./GetFloatingRegion')
/**
* @ignore
*/
class FloatingRegionByRectangle extends GetFloatingRegion {
/**
* @param {Region} rect
* @param {number} maxUpOffset
* @param {number} maxDownOffset
* @param {number} maxLeftOffset
* @param {number} maxRightOffset
*/
constructor(rect, maxUpOffset, maxDownOffset, maxLeftOffset, maxRightOffset) {
super()
this._rect = rect
this._maxUpOffset = maxUpOffset
this._maxDownOffset = maxDownOffset
this._maxLeftOffset = maxLeftOffset
this._maxRightOffset = maxRightOffset
}
/**
* @inheritDoc
*/
async getRegion(_eyesBase, _screenshot) {
const floatingRegion = new FloatingMatchSettings({
left: this._rect.getLeft(),
top: this._rect.getTop(),
width: this._rect.getWidth(),
height: this._rect.getHeight(),
maxUpOffset: this._maxUpOffset,
maxDownOffset: this._maxDownOffset,
maxLeftOffset: this._maxLeftOffset,
maxRightOffset: this._maxRightOffset,
})
return [floatingRegion]
}
async toPersistedRegions(_driver) {
return [
{
left: this._rect.getLeft(),
top: this._rect.getTop(),
width: this._rect.getWidth(),
height: this._rect.getHeight(),
maxUpOffset: this._maxUpOffset,
maxDownOffset: this._maxDownOffset,
maxLeftOffset: this._maxLeftOffset,
maxRightOffset: this._maxRightOffset,
},
]
}
}
exports.FloatingRegionByRectangle = FloatingRegionByRectangle
|
ScalablyTyped/SlinkyTyped | d/devtools-protocol/src/main/scala/typingsSlinky/devtoolsProtocol/mod/Protocol/CSS/FontFace.scala | package typingsSlinky.devtoolsProtocol.mod.Protocol.CSS
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait FontFace extends StObject {
/**
* The font-family.
*/
var fontFamily: String = js.native
/**
* The font-stretch.
*/
var fontStretch: String = js.native
/**
* The font-style.
*/
var fontStyle: String = js.native
/**
* The font-variant.
*/
var fontVariant: String = js.native
/**
* Available variation settings (a.k.a. "axes").
*/
var fontVariationAxes: js.UndefOr[js.Array[FontVariationAxis]] = js.native
/**
* The font-weight.
*/
var fontWeight: String = js.native
/**
* The resolved platform font family
*/
var platformFontFamily: String = js.native
/**
* The src.
*/
var src: String = js.native
/**
* The unicode-range.
*/
var unicodeRange: String = js.native
}
object FontFace {
@scala.inline
def apply(
fontFamily: String,
fontStretch: String,
fontStyle: String,
fontVariant: String,
fontWeight: String,
platformFontFamily: String,
src: String,
unicodeRange: String
): FontFace = {
val __obj = js.Dynamic.literal(fontFamily = fontFamily.asInstanceOf[js.Any], fontStretch = fontStretch.asInstanceOf[js.Any], fontStyle = fontStyle.asInstanceOf[js.Any], fontVariant = fontVariant.asInstanceOf[js.Any], fontWeight = fontWeight.asInstanceOf[js.Any], platformFontFamily = platformFontFamily.asInstanceOf[js.Any], src = src.asInstanceOf[js.Any], unicodeRange = unicodeRange.asInstanceOf[js.Any])
__obj.asInstanceOf[FontFace]
}
@scala.inline
implicit class FontFaceMutableBuilder[Self <: FontFace] (val x: Self) extends AnyVal {
@scala.inline
def setFontFamily(value: String): Self = StObject.set(x, "fontFamily", value.asInstanceOf[js.Any])
@scala.inline
def setFontStretch(value: String): Self = StObject.set(x, "fontStretch", value.asInstanceOf[js.Any])
@scala.inline
def setFontStyle(value: String): Self = StObject.set(x, "fontStyle", value.asInstanceOf[js.Any])
@scala.inline
def setFontVariant(value: String): Self = StObject.set(x, "fontVariant", value.asInstanceOf[js.Any])
@scala.inline
def setFontVariationAxes(value: js.Array[FontVariationAxis]): Self = StObject.set(x, "fontVariationAxes", value.asInstanceOf[js.Any])
@scala.inline
def setFontVariationAxesUndefined: Self = StObject.set(x, "fontVariationAxes", js.undefined)
@scala.inline
def setFontVariationAxesVarargs(value: FontVariationAxis*): Self = StObject.set(x, "fontVariationAxes", js.Array(value :_*))
@scala.inline
def setFontWeight(value: String): Self = StObject.set(x, "fontWeight", value.asInstanceOf[js.Any])
@scala.inline
def setPlatformFontFamily(value: String): Self = StObject.set(x, "platformFontFamily", value.asInstanceOf[js.Any])
@scala.inline
def setSrc(value: String): Self = StObject.set(x, "src", value.asInstanceOf[js.Any])
@scala.inline
def setUnicodeRange(value: String): Self = StObject.set(x, "unicodeRange", value.asInstanceOf[js.Any])
}
}
|
akritisneh/OnAndOn | 02 Arrays and Vectors/Basics/KadanesSubarraysum.cpp | #include<iostream>
using namespace std;
int KadanesSubArraysum(int arr[], int n){
int sum = 0 ;
int largest = 0;
for(int i=0;i<n;i++){
sum = sum + arr[i];
if(sum<0)
sum = 0;
largest = max(largest,sum);
}
return largest;
}
int main(){
int arr[] = {-2,3,4,-1,5,-12,6,1,3};
int n = sizeof(arr)/sizeof(int);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
cout<<"Maximun sum from the array is - "<<KadanesSubArraysum(arr,n);
return 0;
}
//time complexity O(n)
|
xiaohaogong/spring-data-redis | src/main/java/org/springframework/data/redis/connection/lettuce/LettuceServerCommands.java | /*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.data.redis.connection.lettuce;
import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands;
import io.lettuce.core.cluster.api.sync.RedisClusterCommands;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.Properties;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.connection.convert.Converters;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* @author <NAME>
* @since 2.0
*/
@RequiredArgsConstructor
class LettuceServerCommands implements RedisServerCommands {
private final @NonNull LettuceConnection connection;
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#bgReWriteAof()
*/
@Override
public void bgReWriteAof() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().bgrewriteaof()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().bgrewriteaof()));
return;
}
getConnection().bgrewriteaof();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#bgSave()
*/
@Override
public void bgSave() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().bgsave()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().bgsave()));
return;
}
getConnection().bgsave();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#lastSave()
*/
@Override
public Long lastSave() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().lastsave(), LettuceConverters.dateToLong()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().lastsave(), LettuceConverters.dateToLong()));
return null;
}
return LettuceConverters.toLong(getConnection().lastsave());
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#save()
*/
@Override
public void save() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().save()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().save()));
return;
}
getConnection().save();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#dbSize()
*/
@Override
public Long dbSize() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().dbsize()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().dbsize()));
return null;
}
return getConnection().dbsize();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#flushDb()
*/
@Override
public void flushDb() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().flushdb()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().flushdb()));
return;
}
getConnection().flushdb();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#flushAll()
*/
@Override
public void flushAll() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().flushall()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().flushall()));
return;
}
getConnection().flushall();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#info()
*/
@Override
public Properties info() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().info(), LettuceConverters.stringToProps()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().info(), LettuceConverters.stringToProps()));
return null;
}
return LettuceConverters.toProperties(getConnection().info());
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#info(java.lang.String)
*/
@Override
public Properties info(String section) {
Assert.hasText(section, "Section must not be null or empty!");
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().info(section), LettuceConverters.stringToProps()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().info(section), LettuceConverters.stringToProps()));
return null;
}
return LettuceConverters.toProperties(getConnection().info(section));
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#shutdown()
*/
@Override
public void shutdown() {
try {
if (isPipelined()) {
getAsyncConnection().shutdown(true);
return;
}
getConnection().shutdown(true);
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#shutdown(org.springframework.data.redis.connection.RedisServerCommands.ShutdownOption)
*/
@Override
public void shutdown(ShutdownOption option) {
if (option == null) {
shutdown();
return;
}
boolean save = ShutdownOption.SAVE.equals(option);
try {
if (isPipelined()) {
getAsyncConnection().shutdown(save);
return;
}
getConnection().shutdown(save);
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#getConfig(java.lang.String)
*/
@Override
public Properties getConfig(String pattern) {
Assert.hasText(pattern, "Pattern must not be null or empty!");
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().configGet(pattern),
Converters.mapToPropertiesConverter()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().configGet(pattern),
Converters.mapToPropertiesConverter()));
return null;
}
return Converters.toProperties(getConnection().configGet(pattern));
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#setConfig(java.lang.String, java.lang.String)
*/
@Override
public void setConfig(String param, String value) {
Assert.hasText(param, "Parameter must not be null or empty!");
Assert.hasText(value, "Value must not be null or empty!");
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().configSet(param, value)));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().configSet(param, value)));
return;
}
getConnection().configSet(param, value);
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#resetConfigStats()
*/
@Override
public void resetConfigStats() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().configResetstat()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().configResetstat()));
return;
}
getConnection().configResetstat();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#time()
*/
@Override
public Long time() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().time(), LettuceConverters.toTimeConverter()));
return null;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().time(), LettuceConverters.toTimeConverter()));
return null;
}
return LettuceConverters.toTimeConverter().convert(getConnection().time());
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#killClient(java.lang.String, int)
*/
@Override
public void killClient(String host, int port) {
Assert.hasText(host, "Host for 'CLIENT KILL' must not be 'null' or 'empty'.");
String client = String.format("%s:%s", host, port);
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().clientKill(client)));
return;
}
getConnection().clientKill(client);
} catch (Exception e) {
throw convertLettuceAccessException(e);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#setClientName(byte[])
*/
@Override
public void setClientName(byte[] name) {
Assert.notNull(name, "Name must not be null!");
if (isQueueing()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().clientSetname(name)));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceStatusResult(getAsyncConnection().clientSetname(name)));
return;
}
getAsyncConnection().clientSetname(name);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#getClientName()
*/
@Override
public String getClientName() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().clientGetname(), LettuceConverters.bytesToString()));
return null;
}
if (isQueueing()) {
transaction(
connection.newLettuceResult(getAsyncConnection().clientGetname(), LettuceConverters.bytesToString()));
return null;
}
return LettuceConverters.toString(getConnection().clientGetname());
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#getClientList()
*/
@Override
public List<RedisClientInfo> getClientList() {
if (isPipelined()) {
throw new UnsupportedOperationException("Cannot be called in pipeline mode.");
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().clientList(),
LettuceConverters.stringToRedisClientListConverter()));
return null;
}
return LettuceConverters.toListOfRedisClientInformation(getConnection().clientList());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#slaveOf(java.lang.String, int)
*/
@Override
public void slaveOf(String host, int port) {
Assert.hasText(host, "Host must not be null for 'SLAVEOF' command.");
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().slaveof(host, port)));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().slaveof(host, port)));
return;
}
getConnection().slaveof(host, port);
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#slaveOfNoOne()
*/
@Override
public void slaveOfNoOne() {
try {
if (isPipelined()) {
pipeline(connection.newLettuceStatusResult(getAsyncConnection().slaveofNoOne()));
return;
}
if (isQueueing()) {
transaction(connection.newLettuceResult(getAsyncConnection().slaveofNoOne()));
return;
}
getConnection().slaveofNoOne();
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#migrate(byte[], org.springframework.data.redis.connection.RedisNode, int, org.springframework.data.redis.connection.RedisServerCommands.MigrateOption)
*/
@Override
public void migrate(byte[] key, RedisNode target, int dbIndex, @Nullable MigrateOption option) {
migrate(key, target, dbIndex, option, Long.MAX_VALUE);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#migrate(byte[], org.springframework.data.redis.connection.RedisNode, int, org.springframework.data.redis.connection.RedisServerCommands.MigrateOption, long)
*/
@Override
public void migrate(byte[] key, RedisNode target, int dbIndex, @Nullable MigrateOption option, long timeout) {
Assert.notNull(key, "Key must not be null!");
Assert.notNull(target, "Target node must not be null!");
try {
if (isPipelined()) {
pipeline(connection
.newLettuceResult(getAsyncConnection().migrate(target.getHost(), target.getPort(), key, dbIndex, timeout)));
return;
}
if (isQueueing()) {
transaction(connection
.newLettuceResult(getAsyncConnection().migrate(target.getHost(), target.getPort(), key, dbIndex, timeout)));
return;
}
getConnection().migrate(target.getHost(), target.getPort(), key, dbIndex, timeout);
} catch (Exception ex) {
throw convertLettuceAccessException(ex);
}
}
private boolean isPipelined() {
return connection.isPipelined();
}
private boolean isQueueing() {
return connection.isQueueing();
}
private void pipeline(LettuceResult<?, ?> result) {
connection.pipeline(result);
}
private void transaction(LettuceResult<?, ?> result) {
connection.transaction(result);
}
private RedisClusterAsyncCommands<byte[], byte[]> getAsyncConnection() {
return connection.getAsyncConnection();
}
public RedisClusterCommands<byte[], byte[]> getConnection() {
return connection.getConnection();
}
private DataAccessException convertLettuceAccessException(Exception ex) {
return connection.convertLettuceAccessException(ex);
}
}
|
theonlylawislove/omaha | core/google_update_core.cc | <filename>core/google_update_core.cc
// Copyright 2008-2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/core/google_update_core.h"
#include "omaha/common/debug.h"
#include "omaha/common/error.h"
#include "omaha/common/exception_barrier.h"
#include "omaha/common/logging.h"
#include "omaha/common/reg_key.h"
#include "omaha/common/scope_guard.h"
#include "omaha/common/scoped_any.h"
#include "omaha/common/system.h"
#include "omaha/common/utils.h"
#include "omaha/goopdate/config_manager.h"
namespace omaha {
GoogleUpdateCore::GoogleUpdateCore() {
CORE_LOG(L3, (_T("[GoogleUpdateCore::GoogleUpdateCore]")));
}
GoogleUpdateCore::~GoogleUpdateCore() {
CORE_LOG(L3, (_T("[GoogleUpdateCore::~GoogleUpdateCore]")));
}
STDMETHODIMP GoogleUpdateCore::LaunchCmdElevated(const WCHAR* app_guid,
const WCHAR* cmd_id,
DWORD caller_proc_id,
ULONG_PTR* proc_handle) {
CORE_LOG(L3, (_T("[GoogleUpdateCore::LaunchCmdElevated]")
_T("[app %s][cmd %s][pid %d]"),
app_guid, cmd_id, caller_proc_id));
ExceptionBarrier barrier;
ASSERT1(app_guid);
ASSERT1(cmd_id);
ASSERT1(proc_handle);
if (!(IsGuid(app_guid) && cmd_id && _tcslen(cmd_id) && proc_handle)) {
return E_INVALIDARG;
}
scoped_process caller_proc_handle;
HRESULT hr = OpenCallerProcessHandle(caller_proc_id,
address(caller_proc_handle));
if (FAILED(hr)) {
CORE_LOG(LE, (_T("[failed to open caller's handle][0x%x]"), hr));
return hr;
}
CString cmd(GetCommandToLaunch(app_guid, cmd_id));
CORE_LOG(L3, (_T("[GoogleUpdateCore::LaunchCmdElevated][cmd %s]"), cmd));
if (cmd.IsEmpty()) {
return GOOPDATE_E_CORE_MISSING_CMD;
}
return LaunchCmd(&cmd, get(caller_proc_handle), proc_handle);
}
HRESULT GoogleUpdateCore::OpenCallerProcessHandle(DWORD proc_id,
HANDLE* proc_handle) {
ASSERT1(proc_handle);
*proc_handle = NULL;
HRESULT hr = ::CoImpersonateClient();
if (FAILED(hr)) {
return hr;
}
ON_SCOPE_EXIT(::CoRevertToSelf);
*proc_handle = ::OpenProcess(PROCESS_DUP_HANDLE, false, proc_id);
return *proc_handle ? S_OK : HRESULTFromLastError();
}
CString GoogleUpdateCore::GetCommandToLaunch(const TCHAR* app_guid,
const TCHAR* cmd_id) {
CString cmd_line;
if (!app_guid || !cmd_id) {
return cmd_line;
}
ConfigManager* config_manager = ConfigManager::Instance();
CString clients_key_name = config_manager->machine_registry_clients();
CString app_key_name = AppendRegKeyPath(clients_key_name, app_guid);
RegKey::GetValue(app_key_name, cmd_id, &cmd_line);
return cmd_line;
}
HRESULT GoogleUpdateCore::LaunchCmd(CString* cmd,
HANDLE caller_proc_handle,
ULONG_PTR* proc_handle) {
if (!cmd || !caller_proc_handle || !proc_handle) {
return E_INVALIDARG;
}
*proc_handle = NULL;
HRESULT hr = S_OK;
// This is a pseudo handle that must not be closed.
HANDLE this_process_handle = ::GetCurrentProcess();
PROCESS_INFORMATION pi = {0};
hr = System::StartProcess(NULL, cmd->GetBuffer(), &pi);
if (FAILED(hr)) {
CORE_LOG(LE, (_T("[failed to launch cmd][%s][0x%08x]"), *cmd, hr));
return hr;
}
// DuplicateHandle call will close the source handle regardless of any error
// status returned.
ASSERT1(pi.hProcess);
VERIFY1(::CloseHandle(pi.hThread));
scoped_process duplicate_proc_handle;
DWORD desired_access = PROCESS_QUERY_INFORMATION | SYNCHRONIZE;
bool res = ::DuplicateHandle(
this_process_handle, // Current process.
pi.hProcess, // Process handle to duplicate.
caller_proc_handle, // Process receiving the handle.
address(duplicate_proc_handle), // Duplicated handle.
desired_access, // Access requested for the new handle.
false, // Don't inherit the new handle.
DUPLICATE_CLOSE_SOURCE) != 0; // Closes the source handle.
if (!res) {
hr = HRESULTFromLastError();
CORE_LOG(LE, (_T("[failed to duplicate the handle][0x%08x]"), hr));
return hr;
}
// Transfer the ownership of the new handle to the caller. The caller must
// close this handle.
*proc_handle = reinterpret_cast<ULONG_PTR>(release(duplicate_proc_handle));
return S_OK;
}
} // namespace omaha
|
Jaystified/scala-js-nodejs | app/nodejs-v10/src/test/scala/io/scalajs/nodejs/fs/FsClassesTest.scala | <reponame>Jaystified/scala-js-nodejs
package io.scalajs.nodejs
package fs
import io.scalajs.nodejs.buffer.Buffer
import io.scalajs.nodejs.url.URL
import org.scalatest.funspec.AnyFunSpec
class FsClassesTest extends AnyFunSpec {
val dirname = process.Process.cwd()
describe("ReadStream") {
it("supports constructor(") {
assert(new ReadStream("package.json").readableLength === 0)
assert(new ReadStream(Buffer.from("package.json")) !== null)
assert(new ReadStream(new URL(s"file:///${dirname}/package.json")) !== null)
}
}
describe("WriteStream") {
it("supports constructor") {
assert(new WriteStream("NO_SUCH_FILE").writableLength === 0)
assert(new WriteStream(Buffer.from("NO_SUCH_FILE")) !== null)
assert(new WriteStream(new URL(s"file:///${dirname}/NO_SUCH_FILE")) !== null)
}
}
}
|
menglu21/cmssw | L1Trigger/Phase2L1ParticleFlow/plugins/L1TPFCandMultiMerger.cc | <filename>L1Trigger/Phase2L1ParticleFlow/plugins/L1TPFCandMultiMerger.cc
#include "DataFormats/L1TParticleFlow/interface/PFCandidate.h"
#include "FWCore/Framework/interface/global/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/transform.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Common/interface/CloneTrait.h"
#include <vector>
class L1TPFCandMultiMerger : public edm::global::EDProducer<> {
public:
explicit L1TPFCandMultiMerger(const edm::ParameterSet&);
~L1TPFCandMultiMerger() override;
private:
void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override;
std::vector<std::string> instances_, regionalInstances_;
std::vector<bool> alsoRegional_; // aligned with instances_
std::vector<edm::EDGetTokenT<l1t::PFCandidateCollection>> tokens_;
std::vector<edm::EDGetTokenT<l1t::PFCandidateRegionalOutput>> regionalTokens_;
};
L1TPFCandMultiMerger::L1TPFCandMultiMerger(const edm::ParameterSet& iConfig)
: instances_(iConfig.getParameter<std::vector<std::string>>("labelsToMerge")),
regionalInstances_(iConfig.getParameter<std::vector<std::string>>("regionalLabelsToMerge")) {
const std::vector<edm::InputTag>& pfProducers = iConfig.getParameter<std::vector<edm::InputTag>>("pfProducers");
tokens_.reserve(instances_.size() * pfProducers.size());
for (const std::string& instance : instances_) {
for (const edm::InputTag& tag : pfProducers) {
tokens_.push_back(consumes<l1t::PFCandidateCollection>(edm::InputTag(tag.label(), instance, tag.process())));
}
produces<l1t::PFCandidateCollection>(instance);
// check if regional output is needed too
if (std::find(regionalInstances_.begin(), regionalInstances_.end(), instance) != regionalInstances_.end()) {
alsoRegional_.push_back(true);
for (const edm::InputTag& tag : pfProducers) {
regionalTokens_.push_back(
consumes<l1t::PFCandidateRegionalOutput>(edm::InputTag(tag.label(), instance + "Regional", tag.process())));
}
produces<l1t::PFCandidateRegionalOutput>(instance + "Regional");
} else {
alsoRegional_.push_back(false);
}
}
// check that regional output is not requested without the standard one
for (const std::string& instance : regionalInstances_) {
auto match = std::find(instances_.begin(), instances_.end(), instance);
if (match == instances_.end()) {
throw cms::Exception("Configuration", "The regional label '" + instance + "' is not in labelsToMerge\n");
}
}
}
L1TPFCandMultiMerger::~L1TPFCandMultiMerger() {}
void L1TPFCandMultiMerger::produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup&) const {
edm::Handle<l1t::PFCandidateCollection> handle;
edm::Handle<l1t::PFCandidateRegionalOutput> regionalHandle;
unsigned int ninstances = instances_.size(), nproducers = tokens_.size() / ninstances;
std::vector<int> keys;
for (unsigned int ii = 0, it = 0, irt = 0; ii < ninstances; ++ii) {
auto out = std::make_unique<l1t::PFCandidateCollection>();
std::unique_ptr<l1t::PFCandidateRegionalOutput> regout;
if (alsoRegional_[ii]) {
auto refprod = iEvent.getRefBeforePut<l1t::PFCandidateCollection>(instances_[ii]);
regout = std::make_unique<l1t::PFCandidateRegionalOutput>(edm::RefProd<l1t::PFCandidateCollection>(refprod));
}
for (unsigned int ip = 0; ip < nproducers; ++ip, ++it) {
iEvent.getByToken(tokens_[it], handle);
unsigned int offset = out->size();
out->insert(out->end(), handle->begin(), handle->end());
if (alsoRegional_[ii]) {
iEvent.getByToken(regionalTokens_[irt++], regionalHandle);
const auto& src = *regionalHandle;
for (unsigned int ireg = 0, nreg = src.nRegions(); ireg < nreg; ++ireg) {
auto region = src.region(ireg);
keys.clear();
for (auto iter = region.begin(), iend = region.end(); iter != iend; ++iter) {
keys.push_back(iter.idx() + offset);
}
regout->addRegion(keys, src.eta(ireg), src.phi(ireg));
}
}
}
iEvent.put(std::move(out), instances_[ii]);
if (alsoRegional_[ii]) {
iEvent.put(std::move(regout), instances_[ii] + "Regional");
}
}
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(L1TPFCandMultiMerger);
|
armindojr/pure-gen | src/locale/en/dessert/index.js | <filename>src/locale/en/dessert/index.js
const dessert = {
flavor: require('./flavor'),
topping: require('./topping'),
variety: require('./variety'),
};
module.exports = dessert;
|
artyomkorzun/f1x | src/main/java/org/efix/message/field/RoundingDirection.java | <gh_stars>10-100
package org.efix.message.field;
public class RoundingDirection {
public static final byte ROUND_TO_NEAREST = '0';
public static final byte ROUND_DOWN = '1';
public static final byte ROUND_UP = '2';
} |
amannougrahiya/imop-compiler | src/imop/ast/info/cfgNodeInfo/OmpForInitExpressionInfo.java | <reponame>amannougrahiya/imop-compiler
/*
* Copyright (c) 2019 <NAME>, <NAME>, IIT Madras.
* This file is a part of the project IMOP, licensed under the MIT license.
* See LICENSE.md for the full text of the license.
*
* The above notice shall be included in all copies or substantial
* portions of this file.
*/
package imop.ast.info.cfgNodeInfo;
import imop.ast.info.NodeInfo;
import imop.ast.node.external.*;
public class OmpForInitExpressionInfo extends NodeInfo {
public OmpForInitExpressionInfo(Node owner) {
super(owner);
}
}
|
7274-dev/AdventnaVyzva-React | src/hooks/getFileType.js | const extensions = {
'image': ['jpg', 'png', 'webp', 'gif', 'tiff', 'psd', 'raw', 'bmp', 'jpeg', 'heif', 'indd', 'svg'],
'video': ['mp4', 'webm', 'mpg', 'mp2', 'mpeg', 'mpe', 'mpv', 'ogg', 'm4p', 'm4v', 'avi', 'wmv', 'mov', 'qt', 'flv', 'swf']
}
const getFileType = (extension) => {
extension = extension.replaceAll('.', '').toLowerCase();
for (let i in extensions) {
if (extensions[i].includes(extension)) {
return i.toString();
}
}
return undefined;
}
export { getFileType }
|
RitualYang/JavaUp | reflect/src/main/java/com/base/reflect/ReflectTest.java | <reponame>RitualYang/JavaUp
package com.base.reflect;
import com.base.entity.Student;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author wty
* @create 2020-03-04 18:16
*/
public class ReflectTest {
public static void main(String[] args) throws Exception {
getInstance();
}
public static void getInstance() throws Exception {
Class aClass = Class.forName("com.base.entity.Student");
//初始化
//无参初始化
Constructor<Student> constructors = aClass.getConstructor();
Student student = constructors.newInstance();
//有参初始化
Constructor<Student> constructors1 = aClass.getConstructor(String.class);
Student student1 = constructors1.newInstance("哈哈哈");
//方法调用
//有参方法调用
Method study = aClass.getMethod("study", String.class);
study.invoke(student, "我是好人");
//无参方法调用
Method study1 = aClass.getMethod("study");
study1.invoke(student);
//获取类的属性,无法获取私有化的属性
Field[] fields = aClass.getFields();
System.out.println("获取到Student类的属性");
for (Field field : fields) {
System.out.print(" " + field.getName());
}
Field mobile = aClass.getDeclaredField("mobile");
mobile.setAccessible(true);
Object o = mobile.get(student);
System.out.println(o);
//修改属性值
mobile.set(student, "key");
Object o1 = mobile.get(student);
System.out.println(o1);
Field nums = aClass.getField("nums");
Object o2 = nums.get(student);
System.out.println(o2);
}
}
|
ranton256/cortex | vendor/github.com/alicebob/miniredis/direct.go | package miniredis
// Commands to modify and query our databases directly.
import (
"errors"
"time"
)
var (
// ErrKeyNotFound is returned when a key doesn't exist.
ErrKeyNotFound = errors.New(msgKeyNotFound)
// ErrWrongType when a key is not the right type.
ErrWrongType = errors.New(msgWrongType)
// ErrIntValueError can returned by INCRBY
ErrIntValueError = errors.New(msgInvalidInt)
// ErrFloatValueError can returned by INCRBYFLOAT
ErrFloatValueError = errors.New(msgInvalidFloat)
)
// Select sets the DB id for all direct commands.
func (m *Miniredis) Select(i int) {
m.Lock()
defer m.Unlock()
m.selectedDB = i
}
// Keys returns all keys from the selected database, sorted.
func (m *Miniredis) Keys() []string {
return m.DB(m.selectedDB).Keys()
}
// Keys returns all keys, sorted.
func (db *RedisDB) Keys() []string {
db.master.Lock()
defer db.master.Unlock()
return db.allKeys()
}
// FlushAll removes all keys from all databases.
func (m *Miniredis) FlushAll() {
m.Lock()
defer m.Unlock()
m.flushAll()
}
func (m *Miniredis) flushAll() {
for _, db := range m.dbs {
db.flush()
}
}
// FlushDB removes all keys from the selected database.
func (m *Miniredis) FlushDB() {
m.DB(m.selectedDB).FlushDB()
}
// FlushDB removes all keys.
func (db *RedisDB) FlushDB() {
db.master.Lock()
defer db.master.Unlock()
db.flush()
}
// Get returns string keys added with SET.
func (m *Miniredis) Get(k string) (string, error) {
return m.DB(m.selectedDB).Get(k)
}
// Get returns a string key.
func (db *RedisDB) Get(k string) (string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return "", ErrKeyNotFound
}
if db.t(k) != "string" {
return "", ErrWrongType
}
return db.stringGet(k), nil
}
// Set sets a string key. Removes expire.
func (m *Miniredis) Set(k, v string) error {
return m.DB(m.selectedDB).Set(k, v)
}
// Set sets a string key. Removes expire.
// Unlike redis the key can't be an existing non-string key.
func (db *RedisDB) Set(k, v string) error {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "string" {
return ErrWrongType
}
db.del(k, true) // Remove expire
db.stringSet(k, v)
return nil
}
// Incr changes a int string value by delta.
func (m *Miniredis) Incr(k string, delta int) (int, error) {
return m.DB(m.selectedDB).Incr(k, delta)
}
// Incr changes a int string value by delta.
func (db *RedisDB) Incr(k string, delta int) (int, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "string" {
return 0, ErrWrongType
}
return db.stringIncr(k, delta)
}
// Incrfloat changes a float string value by delta.
func (m *Miniredis) Incrfloat(k string, delta float64) (float64, error) {
return m.DB(m.selectedDB).Incrfloat(k, delta)
}
// Incrfloat changes a float string value by delta.
func (db *RedisDB) Incrfloat(k string, delta float64) (float64, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "string" {
return 0, ErrWrongType
}
return db.stringIncrfloat(k, delta)
}
// List returns the list k, or an error if it's not there or something else.
// This is the same as the Redis command `LRANGE 0 -1`, but you can do your own
// range-ing.
func (m *Miniredis) List(k string) ([]string, error) {
return m.DB(m.selectedDB).List(k)
}
// List returns the list k, or an error if it's not there or something else.
// This is the same as the Redis command `LRANGE 0 -1`, but you can do your own
// range-ing.
func (db *RedisDB) List(k string) ([]string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return nil, ErrKeyNotFound
}
if db.t(k) != "list" {
return nil, ErrWrongType
}
return db.listKeys[k], nil
}
// Lpush is an unshift. Returns the new length.
func (m *Miniredis) Lpush(k, v string) (int, error) {
return m.DB(m.selectedDB).Lpush(k, v)
}
// Lpush is an unshift. Returns the new length.
func (db *RedisDB) Lpush(k, v string) (int, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "list" {
return 0, ErrWrongType
}
return db.listLpush(k, v), nil
}
// Lpop is a shift. Returns the popped element.
func (m *Miniredis) Lpop(k string) (string, error) {
return m.DB(m.selectedDB).Lpop(k)
}
// Lpop is a shift. Returns the popped element.
func (db *RedisDB) Lpop(k string) (string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return "", ErrKeyNotFound
}
if db.t(k) != "list" {
return "", ErrWrongType
}
return db.listLpop(k), nil
}
// Push add element at the end. Is called RPUSH in redis. Returns the new length.
func (m *Miniredis) Push(k string, v ...string) (int, error) {
return m.DB(m.selectedDB).Push(k, v...)
}
// Push add element at the end. Is called RPUSH in redis. Returns the new length.
func (db *RedisDB) Push(k string, v ...string) (int, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "list" {
return 0, ErrWrongType
}
return db.listPush(k, v...), nil
}
// Pop removes and returns the last element. Is called RPOP in Redis.
func (m *Miniredis) Pop(k string) (string, error) {
return m.DB(m.selectedDB).Pop(k)
}
// Pop removes and returns the last element. Is called RPOP in Redis.
func (db *RedisDB) Pop(k string) (string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return "", ErrKeyNotFound
}
if db.t(k) != "list" {
return "", ErrWrongType
}
return db.listPop(k), nil
}
// SetAdd adds keys to a set. Returns the number of new keys.
func (m *Miniredis) SetAdd(k string, elems ...string) (int, error) {
return m.DB(m.selectedDB).SetAdd(k, elems...)
}
// SetAdd adds keys to a set. Returns the number of new keys.
func (db *RedisDB) SetAdd(k string, elems ...string) (int, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "set" {
return 0, ErrWrongType
}
return db.setAdd(k, elems...), nil
}
// Members gives all set keys. Sorted.
func (m *Miniredis) Members(k string) ([]string, error) {
return m.DB(m.selectedDB).Members(k)
}
// Members gives all set keys. Sorted.
func (db *RedisDB) Members(k string) ([]string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return nil, ErrKeyNotFound
}
if db.t(k) != "set" {
return nil, ErrWrongType
}
return db.setMembers(k), nil
}
// IsMember tells if value is in the set.
func (m *Miniredis) IsMember(k, v string) (bool, error) {
return m.DB(m.selectedDB).IsMember(k, v)
}
// IsMember tells if value is in the set.
func (db *RedisDB) IsMember(k, v string) (bool, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return false, ErrKeyNotFound
}
if db.t(k) != "set" {
return false, ErrWrongType
}
return db.setIsMember(k, v), nil
}
// HKeys returns all (sorted) keys ('fields') for a hash key.
func (m *Miniredis) HKeys(k string) ([]string, error) {
return m.DB(m.selectedDB).HKeys(k)
}
// HKeys returns all (sorted) keys ('fields') for a hash key.
func (db *RedisDB) HKeys(key string) ([]string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(key) {
return nil, ErrKeyNotFound
}
if db.t(key) != "hash" {
return nil, ErrWrongType
}
return db.hashFields(key), nil
}
// Del deletes a key and any expiration value. Returns whether there was a key.
func (m *Miniredis) Del(k string) bool {
return m.DB(m.selectedDB).Del(k)
}
// Del deletes a key and any expiration value. Returns whether there was a key.
func (db *RedisDB) Del(k string) bool {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return false
}
db.del(k, true)
return true
}
// TTL is the left over time to live. As set via EXPIRE, PEXPIRE, EXPIREAT,
// PEXPIREAT.
// 0 if not set.
func (m *Miniredis) TTL(k string) time.Duration {
return m.DB(m.selectedDB).TTL(k)
}
// TTL is the left over time to live. As set via EXPIRE, PEXPIRE, EXPIREAT,
// PEXPIREAT.
// 0 if not set.
func (db *RedisDB) TTL(k string) time.Duration {
db.master.Lock()
defer db.master.Unlock()
return db.ttl[k]
}
// SetTTL sets the TTL of a key.
func (m *Miniredis) SetTTL(k string, ttl time.Duration) {
m.DB(m.selectedDB).SetTTL(k, ttl)
}
// SetTTL sets the time to live of a key.
func (db *RedisDB) SetTTL(k string, ttl time.Duration) {
db.master.Lock()
defer db.master.Unlock()
db.ttl[k] = ttl
db.keyVersion[k]++
}
// Type gives the type of a key, or ""
func (m *Miniredis) Type(k string) string {
return m.DB(m.selectedDB).Type(k)
}
// Type gives the type of a key, or ""
func (db *RedisDB) Type(k string) string {
db.master.Lock()
defer db.master.Unlock()
return db.t(k)
}
// Exists tells whether a key exists.
func (m *Miniredis) Exists(k string) bool {
return m.DB(m.selectedDB).Exists(k)
}
// Exists tells whether a key exists.
func (db *RedisDB) Exists(k string) bool {
db.master.Lock()
defer db.master.Unlock()
return db.exists(k)
}
// HGet returns hash keys added with HSET.
// This will return an empty string if the key is not set. Redis would return
// a nil.
// Returns empty string when the key is of a different type.
func (m *Miniredis) HGet(k, f string) string {
return m.DB(m.selectedDB).HGet(k, f)
}
// HGet returns hash keys added with HSET.
// Returns empty string when the key is of a different type.
func (db *RedisDB) HGet(k, f string) string {
db.master.Lock()
defer db.master.Unlock()
h, ok := db.hashKeys[k]
if !ok {
return ""
}
return h[f]
}
// HSet sets a hash key.
// If there is another key by the same name it will be gone.
func (m *Miniredis) HSet(k, f, v string) {
m.DB(m.selectedDB).HSet(k, f, v)
}
// HSet sets a hash key.
// If there is another key by the same name it will be gone.
func (db *RedisDB) HSet(k, f, v string) {
db.master.Lock()
defer db.master.Unlock()
db.hashSet(k, f, v)
}
// HDel deletes a hash key.
func (m *Miniredis) HDel(k, f string) {
m.DB(m.selectedDB).HDel(k, f)
}
// HDel deletes a hash key.
func (db *RedisDB) HDel(k, f string) {
db.master.Lock()
defer db.master.Unlock()
db.hdel(k, f)
}
func (db *RedisDB) hdel(k, f string) {
if _, ok := db.hashKeys[k]; !ok {
return
}
delete(db.hashKeys[k], f)
db.keyVersion[k]++
}
// HIncr increases a key/field by delta (int).
func (m *Miniredis) HIncr(k, f string, delta int) (int, error) {
return m.DB(m.selectedDB).HIncr(k, f, delta)
}
// HIncr increases a key/field by delta (int).
func (db *RedisDB) HIncr(k, f string, delta int) (int, error) {
db.master.Lock()
defer db.master.Unlock()
return db.hashIncr(k, f, delta)
}
// HIncrfloat increases a key/field by delta (float).
func (m *Miniredis) HIncrfloat(k, f string, delta float64) (float64, error) {
return m.DB(m.selectedDB).HIncrfloat(k, f, delta)
}
// HIncrfloat increases a key/field by delta (float).
func (db *RedisDB) HIncrfloat(k, f string, delta float64) (float64, error) {
db.master.Lock()
defer db.master.Unlock()
return db.hashIncrfloat(k, f, delta)
}
// SRem removes fields from a set. Returns number of deleted fields.
func (m *Miniredis) SRem(k string, fields ...string) (int, error) {
return m.DB(m.selectedDB).SRem(k, fields...)
}
// SRem removes fields from a set. Returns number of deleted fields.
func (db *RedisDB) SRem(k string, fields ...string) (int, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return 0, ErrKeyNotFound
}
if db.t(k) != "set" {
return 0, ErrWrongType
}
return db.setRem(k, fields...), nil
}
// ZAdd adds a score,member to a sorted set.
func (m *Miniredis) ZAdd(k string, score float64, member string) (bool, error) {
return m.DB(m.selectedDB).ZAdd(k, score, member)
}
// ZAdd adds a score,member to a sorted set.
func (db *RedisDB) ZAdd(k string, score float64, member string) (bool, error) {
db.master.Lock()
defer db.master.Unlock()
if db.exists(k) && db.t(k) != "zset" {
return false, ErrWrongType
}
return db.ssetAdd(k, score, member), nil
}
// ZMembers returns all members by score
func (m *Miniredis) ZMembers(k string) ([]string, error) {
return m.DB(m.selectedDB).ZMembers(k)
}
// ZMembers returns all members by score
func (db *RedisDB) ZMembers(k string) ([]string, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return nil, ErrKeyNotFound
}
if db.t(k) != "zset" {
return nil, ErrWrongType
}
return db.ssetMembers(k), nil
}
// SortedSet returns a raw string->float64 map.
func (m *Miniredis) SortedSet(k string) (map[string]float64, error) {
return m.DB(m.selectedDB).SortedSet(k)
}
// SortedSet returns a raw string->float64 map.
func (db *RedisDB) SortedSet(k string) (map[string]float64, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return nil, ErrKeyNotFound
}
if db.t(k) != "zset" {
return nil, ErrWrongType
}
return db.sortedSet(k), nil
}
// ZRem deletes a member. Returns whether the was a key.
func (m *Miniredis) ZRem(k, member string) (bool, error) {
return m.DB(m.selectedDB).ZRem(k, member)
}
// ZRem deletes a member. Returns whether the was a key.
func (db *RedisDB) ZRem(k, member string) (bool, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return false, ErrKeyNotFound
}
if db.t(k) != "zset" {
return false, ErrWrongType
}
return db.ssetRem(k, member), nil
}
// ZScore gives the score of a sorted set member.
func (m *Miniredis) ZScore(k, member string) (float64, error) {
return m.DB(m.selectedDB).ZScore(k, member)
}
// ZScore gives the score of a sorted set member.
func (db *RedisDB) ZScore(k, member string) (float64, error) {
db.master.Lock()
defer db.master.Unlock()
if !db.exists(k) {
return 0, ErrKeyNotFound
}
if db.t(k) != "zset" {
return 0, ErrWrongType
}
return db.ssetScore(k, member), nil
}
|
josueeduardo/snappy | snappy/src/main/java/io/joshworks/snappy/http/Interceptor.java | package io.joshworks.snappy.http;
import io.joshworks.snappy.handler.HandlerUtil;
public abstract class Interceptor {
private final String url;
private final boolean wildcard;
protected Interceptor(String url) {
url = HandlerUtil.parseUrl(url);
this.wildcard = url.endsWith(HandlerUtil.WILDCARD);
this.url = wildcard ? url.substring(0, url.length() - 1) : url;
}
public String url() {
return url;
}
public boolean match(String url) {
return wildcard ? url.startsWith(this.url) : url.equals(this.url);
}
}
|
bigpkd/glo-2003-airbnb | src/test/java/ca/ulaval/glo2003/reports/domain/helpers/ReportPeriodBuilder.java | <gh_stars>0
package ca.ulaval.glo2003.reports.domain.helpers;
import static ca.ulaval.glo2003.reports.domain.helpers.ReportPeriodObjectMother.createPeriodName;
import static ca.ulaval.glo2003.time.domain.helpers.TimePeriodBuilder.aTimePeriod;
import ca.ulaval.glo2003.reports.domain.ReportPeriod;
import ca.ulaval.glo2003.time.domain.TimePeriod;
public class ReportPeriodBuilder {
private String name = createPeriodName();
private TimePeriod period = aTimePeriod().build();
public static ReportPeriodBuilder aReportPeriod() {
return new ReportPeriodBuilder();
}
public ReportPeriod build() {
return new ReportPeriod(name, period);
}
}
|
LacertosusRepo/headers | UIKit/_UIBackdropViewSettingsUltraDark.h | #import "_UIBackdropViewSettings.h"
@interface _UIBackdropViewSettingsUltraDark : _UIBackdropViewSettings
@end
|
mcsma01/DayTrader | modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.tomcat;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ObjectName;
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.Realm;
import org.apache.catalina.Valve;
import org.apache.catalina.cluster.CatalinaCluster;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
import org.apache.geronimo.j2ee.management.impl.InvalidObjectNameException;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.jmx.JMXUtil;
import org.apache.geronimo.management.J2EEApplication;
import org.apache.geronimo.management.J2EEServer;
import org.apache.geronimo.management.geronimo.WebModule;
import org.apache.geronimo.security.jacc.RoleDesignateSource;
import org.apache.geronimo.tomcat.cluster.CatalinaClusterGBean;
import org.apache.geronimo.tomcat.cluster.WADIGBean;
import org.apache.geronimo.tomcat.util.SecurityHolder;
import org.apache.geronimo.transaction.TrackedConnectionAssociator;
import org.apache.geronimo.transaction.context.OnlineUserTransaction;
import org.apache.geronimo.transaction.context.TransactionContextManager;
/**
* Wrapper for a WebApplicationContext that sets up its J2EE environment.
*
* @version $Rev$ $Date$
*/
public class TomcatWebAppContext implements GBeanLifecycle, TomcatContext, WebModule {
private static Log log = LogFactory.getLog(TomcatWebAppContext.class);
protected final TomcatContainer container;
private final ClassLoader webClassLoader;
protected Context context = null;
private final URI webAppRoot;
private String path = null;
private String docBase = null;
private String virtualServer = null;
private final Realm realm;
private final List valveChain;
private final CatalinaCluster catalinaCluster;
private final Manager manager;
private final boolean crossContext;
private final Map componentContext;
private final Kernel kernel;
private final Set unshareableResources;
private final Set applicationManagedSecurityResources;
private final TrackedConnectionAssociator trackedConnectionAssociator;
private final TransactionContextManager transactionContextManager;
private final RoleDesignateSource roleDesignateSource;
private final SecurityHolder securityHolder;
private final J2EEServer server;
private final J2EEApplication application;
private final Map webServices;
private final String objectName;
private final String originalSpecDD;
public TomcatWebAppContext(
ClassLoader classLoader,
String objectName,
String originalSpecDD,
URI relativeWebAppRoot,
URI[] webClassPath,
boolean contextPriorityClassLoader,
URL configurationBaseUrl,
SecurityHolder securityHolder,
String virtualServer,
Map componentContext,
Set unshareableResources,
Set applicationManagedSecurityResources,
OnlineUserTransaction userTransaction,
TransactionContextManager transactionContextManager,
TrackedConnectionAssociator trackedConnectionAssociator,
TomcatContainer container,
RoleDesignateSource roleDesignateSource,
ObjectRetriever tomcatRealm,
ValveGBean tomcatValveChain,
CatalinaClusterGBean cluster,
WADIGBean manager,
boolean crossContext,
Map webServices,
J2EEServer server,
J2EEApplication application,
Kernel kernel)
throws Exception {
assert classLoader != null;
assert relativeWebAppRoot != null;
assert webClassPath != null;
assert configurationBaseUrl != null;
assert transactionContextManager != null;
assert trackedConnectionAssociator != null;
assert componentContext != null;
assert container != null;
this.objectName = objectName;
URI root = null;
//TODO is there a simpler way to do this?
if (configurationBaseUrl.getProtocol().equalsIgnoreCase("file")) {
root = new URI("file", configurationBaseUrl.getPath(), null);
} else {
root = URI.create(configurationBaseUrl.toString());
}
this.webAppRoot = root.resolve(relativeWebAppRoot);
this.container = container;
this.originalSpecDD = originalSpecDD;
this.setDocBase(this.webAppRoot.getPath());
this.virtualServer = virtualServer;
this.securityHolder = securityHolder;
this.componentContext = componentContext;
this.transactionContextManager = transactionContextManager;
this.unshareableResources = unshareableResources;
this.applicationManagedSecurityResources = applicationManagedSecurityResources;
this.trackedConnectionAssociator = trackedConnectionAssociator;
this.roleDesignateSource = roleDesignateSource;
this.server = server;
this.application = application;
if (tomcatRealm != null){
realm = (Realm)tomcatRealm.getInternalObject();
if (!(realm instanceof Realm)){
throw new IllegalArgumentException("tomcatRealm must be an instance of org.apache.catalina.Realm.");
}
} else{
realm = null;
}
//Add the valve list
if (tomcatValveChain != null){
ArrayList chain = new ArrayList();
ValveGBean valveGBean = tomcatValveChain;
while(valveGBean != null){
chain.add((Valve)valveGBean.getInternalObject());
valveGBean = valveGBean.getNextValve();
}
valveChain = chain;
} else {
valveChain = null;
}
//Add the cluster
if (cluster != null)
catalinaCluster = (CatalinaCluster)cluster.getInternalObject();
else
catalinaCluster = null;
//Add the manager
if (manager != null)
this.manager = (Manager)manager.getInternalObject();
else
this.manager = null;
this.crossContext = crossContext;
this.webServices = webServices;
URL webAppRootURL = webAppRoot.toURL();
URL[] urls = new URL[webClassPath.length];
for (int i = 0; i < webClassPath.length; i++) {
URI classPathEntry = webClassPath[i];
classPathEntry = root.resolve(classPathEntry);
urls[i] = classPathEntry.toURL();
}
this.webClassLoader = new TomcatClassLoader(urls, webAppRootURL, classLoader, contextPriorityClassLoader);
this.kernel = kernel;
ObjectName myObjectName = JMXUtil.getObjectName(objectName);
verifyObjectName(myObjectName);
if (securityHolder != null){
if (roleDesignateSource == null) {
throw new IllegalArgumentException("RoleDesignateSource must be supplied for a secure web app");
}
}
userTransaction.setUp(transactionContextManager,
trackedConnectionAssociator);
}
public String getObjectName() {
return objectName;
}
public boolean isStateManageable() {
return true;
}
public boolean isStatisticsProvider() {
return false;
}
public boolean isEventProvider() {
return true;
}
public String getContainerName() {
return container.getObjectName();
}
public String getServer() {
return server.getObjectName();
}
public String getDocBase() {
return docBase;
}
public void setDocBase(String docBase) {
this.docBase = docBase;
}
public Map getComponentContext() {
return componentContext;
}
public String getVirtualServer() {
return virtualServer;
}
public ClassLoader getWebClassLoader() {
return webClassLoader;
}
public Kernel getKernel() {
return kernel;
}
public TransactionContextManager getTransactionContextManager() {
return transactionContextManager;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public String getContextPath() {
return path;
}
public void setContextPath(String path) {
this.path = path.startsWith("/") ? path : "/" + path;
}
public SecurityHolder getSecurityHolder() {
return securityHolder;
}
public Set getApplicationManagedSecurityResources() {
return applicationManagedSecurityResources;
}
public TrackedConnectionAssociator getTrackedConnectionAssociator() {
return trackedConnectionAssociator;
}
public Set getUnshareableResources() {
return unshareableResources;
}
public Realm getRealm() {
return realm;
}
public List getValveChain() {
return valveChain;
}
public CatalinaCluster getCluster() {
return catalinaCluster;
}
public Manager getManager() {
return manager;
}
public boolean isCrossContext() {
return crossContext;
}
public Map getWebServices(){
return webServices;
}
public String[] getServlets(){
String[] result = null;
if ((context != null) && (context instanceof StandardContext))
result = ((StandardContext)context).getServlets();
return result;
}
/**
* ObjectName must match this pattern: <p/>
* domain:j2eeType=WebModule,name=MyName,J2EEServer=MyServer,J2EEApplication=MyApplication
*/
private void verifyObjectName(ObjectName objectName) {
if (objectName.isPattern()) {
throw new InvalidObjectNameException(
"ObjectName can not be a pattern", objectName);
}
Hashtable keyPropertyList = objectName.getKeyPropertyList();
if (!NameFactory.WEB_MODULE.equals(keyPropertyList.get("j2eeType"))) {
throw new InvalidObjectNameException(
"WebModule object name j2eeType property must be 'WebModule'",
objectName);
}
if (!keyPropertyList.containsKey(NameFactory.J2EE_NAME)) {
throw new InvalidObjectNameException(
"WebModule object must contain a name property", objectName);
}
if (!keyPropertyList.containsKey(NameFactory.J2EE_SERVER)) {
throw new InvalidObjectNameException(
"WebModule object name must contain a J2EEServer property",
objectName);
}
if (!keyPropertyList.containsKey(NameFactory.J2EE_APPLICATION)) {
throw new InvalidObjectNameException(
"WebModule object name must contain a J2EEApplication property",
objectName);
}
if (keyPropertyList.size() != 4) {
throw new InvalidObjectNameException(
"WebModule object name can only have j2eeType, name, J2EEApplication, and J2EEServer properties",
objectName);
}
}
public String[] getJavaVMs() {
return server.getJavaVMs();
}
public String getDeploymentDescriptor() {
return originalSpecDD;
}
public void doStart() throws Exception {
// See the note of TomcatContainer::addContext
container.addContext(this);
// Is it necessary - doesn't Tomcat Embedded take care of it?
// super.start();
log.debug("TomcatWebAppContext started for " + path);
}
public void doStop() throws Exception {
container.removeContext(this);
// No more logging will occur for this ClassLoader. Inform the LogFactory to avoid a memory leak.
LogFactory.release(webClassLoader);
log.debug("TomcatWebAppContext stopped");
}
public void doFail() {
container.removeContext(this);
// No more logging will occur for this ClassLoader. Inform the LogFactory to avoid a memory leak.
LogFactory.release(webClassLoader);
log.warn("TomcatWebAppContext failed");
}
public static final GBeanInfo GBEAN_INFO;
static {
GBeanInfoBuilder infoBuilder = GBeanInfoBuilder.createStatic("Tomcat WebApplication Context", TomcatWebAppContext.class, NameFactory.WEB_MODULE);
infoBuilder.addAttribute("classLoader", ClassLoader.class, false);
infoBuilder.addAttribute("objectName", String.class, false);
infoBuilder.addAttribute("deploymentDescriptor", String.class, true);
infoBuilder.addAttribute("webAppRoot", URI.class, true);
infoBuilder.addAttribute("webClassPath", URI[].class, true);
infoBuilder.addAttribute("contextPriorityClassLoader", boolean.class, true);
infoBuilder.addAttribute("configurationBaseUrl", URL.class, true);
infoBuilder.addAttribute("contextPath", String.class, true);
infoBuilder.addAttribute("securityHolder", SecurityHolder.class, true);
infoBuilder.addAttribute("virtualServer", String.class, true);
infoBuilder.addAttribute("componentContext", Map.class, true);
infoBuilder.addAttribute("unshareableResources", Set.class, true);
infoBuilder.addAttribute("applicationManagedSecurityResources", Set.class, true);
infoBuilder.addAttribute("userTransaction", OnlineUserTransaction.class, true);
infoBuilder.addReference("TransactionContextManager", TransactionContextManager.class, NameFactory.TRANSACTION_CONTEXT_MANAGER);
infoBuilder.addReference("TrackedConnectionAssociator", TrackedConnectionAssociator.class, NameFactory.JCA_CONNECTION_TRACKER);
infoBuilder.addReference("Container", TomcatContainer.class, NameFactory.GERONIMO_SERVICE);
infoBuilder.addReference("RoleDesignateSource", RoleDesignateSource.class, NameFactory.JACC_MANAGER);
infoBuilder.addReference("TomcatRealm", ObjectRetriever.class);
infoBuilder.addReference("TomcatValveChain", ValveGBean.class);
infoBuilder.addReference("Cluster", CatalinaClusterGBean.class, CatalinaClusterGBean.J2EE_TYPE);
infoBuilder.addReference("Manager", WADIGBean.class);
infoBuilder.addAttribute("crossContext", boolean.class, true);
infoBuilder.addAttribute("webServices", Map.class, true);
infoBuilder.addReference("J2EEServer", J2EEServer.class);
infoBuilder.addReference("J2EEApplication", J2EEApplication.class);
infoBuilder.addAttribute("kernel", Kernel.class, false);
infoBuilder.addInterface(WebModule.class);
infoBuilder.setConstructor(new String[] {
"classLoader",
"objectName",
"deploymentDescriptor",
"webAppRoot",
"webClassPath",
"contextPriorityClassLoader",
"configurationBaseUrl",
"securityHolder",
"virtualServer",
"componentContext",
"unshareableResources",
"applicationManagedSecurityResources",
"userTransaction",
"TransactionContextManager",
"TrackedConnectionAssociator",
"Container",
"RoleDesignateSource",
"TomcatRealm",
"TomcatValveChain",
"Cluster",
"Manager",
"crossContext",
"webServices",
"J2EEServer",
"J2EEApplication",
"kernel"
}
);
GBEAN_INFO = infoBuilder.getBeanInfo();
}
public static GBeanInfo getGBeanInfo() {
return GBEAN_INFO;
}
}
|
Jarunik/sm-team-finder | src/main/java/org/slos/splinterlands/history/Battle.java | <gh_stars>1-10
package org.slos.splinterlands.history;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.slos.util.ToJson;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Battle implements ToJson {
private int player_1_rating_initial;
private int player_2_rating_initial;
private String player_1;
private String player_2;
private String winner;
private int player_1_rating_final;
private int player_2_rating_final;
@JsonDeserialize(using = DetailsDeserializer.class)
private Details details;
private int manaCap;
private String ruleset;
public Battle(@JsonProperty("player_1_rating_initial") int player_1_rating_initial,
@JsonProperty("player_2_rating_initial") int player_2_rating_initial,
@JsonProperty("winner") String winner,
@JsonProperty("player_1_rating_final") int player_1_rating_final,
@JsonProperty("player_2_rating_final") int player_2_rating_final,
@JsonProperty("details") Details details,
@JsonProperty("mana_cap") int manaCap,
@JsonProperty("ruleset") String ruleset,
@JsonProperty("player_1") String player_1,
@JsonProperty("player_2") String player_2) {
this.player_1_rating_initial = player_1_rating_initial;
this.player_2_rating_initial = player_2_rating_initial;
this.player_1 = player_1;
this.player_2 = player_2;
this.winner = winner;
this.player_1_rating_final = player_1_rating_final;
this.player_2_rating_final = player_2_rating_final;
this.details = details;
this.manaCap = manaCap;
this.ruleset = ruleset;
}
public int getPlayer_1_rating_initial() {
return player_1_rating_initial;
}
public int getPlayer_2_rating_initial() {
return player_2_rating_initial;
}
public String getWinner() {
return winner;
}
public int getPlayer_1_rating_final() {
return player_1_rating_final;
}
public String getPlayer_1() {
return player_1;
}
public String getPlayer_2() {
return player_2;
}
public int getPlayer_2_rating_final() {
return player_2_rating_final;
}
public Details getDetails() {
return details;
}
public int getManaCap() {
return manaCap;
}
public String getRuleset() {
return ruleset;
}
@Override
public String toString() {
return "Battle{" +
"player_1_rating_initial=" + player_1_rating_initial +
", player_2_rating_initial=" + player_2_rating_initial +
", winner='" + winner + '\'' +
", player_1_rating_final=" + player_1_rating_final +
", player_2_rating_final=" + player_2_rating_final +
", details=" + details +
'}';
}
}
|
wxhemiao/MyBlaire | MB/ViewController/MBAboutViewController.h | <reponame>wxhemiao/MyBlaire
//
// MBAboutViewController.h
// MB
//
// Created by <NAME> on 14/11/13.
// Copyright (c) 2014年 xxx Innovation Co. Ltd. All rights reserved.
//
#import "TTXBaseViewController.h"
@interface MBAboutViewController : TTXBaseViewController
@end
|
harishbsrinivas/flapjack | spec/service_consumers/pact_helper.rb | <gh_stars>100-1000
require 'pact/provider/rspec'
require 'flapjack'
require 'flapjack/configuration'
require 'flapjack/redis_proxy'
require 'flapjack/gateways/jsonapi'
require './spec/support/mock_logger.rb'
require './spec/service_consumers/fixture_data.rb'
require './spec/service_consumers/provider_support.rb'
require './spec/service_consumers/provider_states_for_flapjack-diner.rb'
FLAPJACK_ENV = ENV["FLAPJACK_ENV"] || 'test'
FLAPJACK_ROOT = File.join(File.dirname(__FILE__), '..')
FLAPJACK_CONFIG = File.join(FLAPJACK_ROOT, 'etc', 'flapjack_test_config.toml')
ENV['RACK_ENV'] = ENV["FLAPJACK_ENV"]
require 'bundler'
Bundler.require(:default, :test)
ActiveSupport.use_standard_json_time_format = true
ActiveSupport.time_precision = 0
MockLogger.configure_log('flapjack-jsonapi')
Zermelo.logger = Flapjack.logger = MockLogger.new
# ::RSpec.configuration.full_backtrace = true
Flapjack::Gateways::JSONAPI.class_eval do
set :show_exceptions, false
set :raise_errors, false
end
cfg = Flapjack::Configuration.new
$redis_options = cfg.load(FLAPJACK_CONFIG) ?
cfg.for_redis :
{:db => 14, :driver => :ruby}
Flapjack::RedisProxy.config = $redis_options
Zermelo.redis = Flapjack.redis
Flapjack::Gateways::JSONAPI.instance_variable_set('@config', 'port' => 19081)
Flapjack::Gateways::JSONAPI.start
Pact.configure do |config|
config.include ::FixtureData
config.include ::ProviderSupport
end
Pact.service_provider "flapjack" do
app { Flapjack::Gateways::JSONAPI.new }
honours_pact_with 'flapjack-diner' do
pact_uri './spec/service_consumers/pacts/flapjack-diner_v2.0.json'
end
end |
acourreges/reshade | src/Hooks/d3d9.cpp | #include "Log.hpp"
#include "HookManager.hpp"
#include "Runtimes\RuntimeD3D9.hpp"
#undef IDirect3D9_CreateDevice
#undef IDirect3D9Ex_CreateDeviceEx
// -----------------------------------------------------------------------------------------------------
namespace
{
struct Direct3DDevice9 : public IDirect3DDevice9Ex, private boost::noncopyable
{
friend struct Direct3DSwapChain9;
Direct3DDevice9(IDirect3D9 *d3d, IDirect3DDevice9 *originalDevice) : mRef(1), mD3D(d3d), mOrig(originalDevice), mImplicitSwapChain(nullptr), mAutoDepthStencil(nullptr)
{
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override;
virtual ULONG STDMETHODCALLTYPE AddRef() override;
virtual ULONG STDMETHODCALLTYPE Release() override;
virtual HRESULT STDMETHODCALLTYPE TestCooperativeLevel() override;
virtual UINT STDMETHODCALLTYPE GetAvailableTextureMem() override;
virtual HRESULT STDMETHODCALLTYPE EvictManagedResources() override;
virtual HRESULT STDMETHODCALLTYPE GetDirect3D(IDirect3D9 **ppD3D9) override;
virtual HRESULT STDMETHODCALLTYPE GetDeviceCaps(D3DCAPS9 *pCaps) override;
virtual HRESULT STDMETHODCALLTYPE GetDisplayMode(UINT iSwapChain, D3DDISPLAYMODE *pMode) override;
virtual HRESULT STDMETHODCALLTYPE GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters) override;
virtual HRESULT STDMETHODCALLTYPE SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9 *pCursorBitmap) override;
virtual void STDMETHODCALLTYPE SetCursorPosition(int X, int Y, DWORD Flags) override;
virtual BOOL STDMETHODCALLTYPE ShowCursor(BOOL bShow) override;
virtual HRESULT STDMETHODCALLTYPE CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DSwapChain9 **ppSwapChain) override;
virtual HRESULT STDMETHODCALLTYPE GetSwapChain(UINT iSwapChain, IDirect3DSwapChain9 **ppSwapChain) override;
virtual UINT STDMETHODCALLTYPE GetNumberOfSwapChains() override;
virtual HRESULT STDMETHODCALLTYPE Reset(D3DPRESENT_PARAMETERS *pPresentationParameters) override;
virtual HRESULT STDMETHODCALLTYPE Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion) override;
virtual HRESULT STDMETHODCALLTYPE GetBackBuffer(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer) override;
virtual HRESULT STDMETHODCALLTYPE GetRasterStatus(UINT iSwapChain, D3DRASTER_STATUS *pRasterStatus) override;
virtual HRESULT STDMETHODCALLTYPE SetDialogBoxMode(BOOL bEnableDialogs) override;
virtual void STDMETHODCALLTYPE SetGammaRamp(UINT iSwapChain, DWORD Flags, const D3DGAMMARAMP *pRamp) override;
virtual void STDMETHODCALLTYPE GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP *pRamp) override;
virtual HRESULT STDMETHODCALLTYPE CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9 **ppTexture, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9 **ppVolumeTexture, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9 **ppCubeTexture, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9 **ppVertexBuffer, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9 **ppIndexBuffer, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE UpdateSurface(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestinationSurface, const POINT *pDestPoint) override;
virtual HRESULT STDMETHODCALLTYPE UpdateTexture(IDirect3DBaseTexture9 *pSourceTexture, IDirect3DBaseTexture9 *pDestinationTexture) override;
virtual HRESULT STDMETHODCALLTYPE GetRenderTargetData(IDirect3DSurface9 *pRenderTarget, IDirect3DSurface9 *pDestSurface) override;
virtual HRESULT STDMETHODCALLTYPE GetFrontBufferData(UINT iSwapChain, IDirect3DSurface9 *pDestSurface) override;
virtual HRESULT STDMETHODCALLTYPE StretchRect(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestSurface, const RECT *pDestRect, D3DTEXTUREFILTERTYPE Filter) override;
virtual HRESULT STDMETHODCALLTYPE ColorFill(IDirect3DSurface9 *pSurface, const RECT *pRect, D3DCOLOR color) override;
virtual HRESULT STDMETHODCALLTYPE CreateOffscreenPlainSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) override;
virtual HRESULT STDMETHODCALLTYPE SetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 *pRenderTarget) override;
virtual HRESULT STDMETHODCALLTYPE GetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 **ppRenderTarget) override;
virtual HRESULT STDMETHODCALLTYPE SetDepthStencilSurface(IDirect3DSurface9 *pNewZStencil) override;
virtual HRESULT STDMETHODCALLTYPE GetDepthStencilSurface(IDirect3DSurface9 **ppZStencilSurface) override;
virtual HRESULT STDMETHODCALLTYPE BeginScene() override;
virtual HRESULT STDMETHODCALLTYPE EndScene() override;
virtual HRESULT STDMETHODCALLTYPE Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil) override;
virtual HRESULT STDMETHODCALLTYPE SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix) override;
virtual HRESULT STDMETHODCALLTYPE GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix) override;
virtual HRESULT STDMETHODCALLTYPE MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix) override;
virtual HRESULT STDMETHODCALLTYPE SetViewport(const D3DVIEWPORT9 *pViewport) override;
virtual HRESULT STDMETHODCALLTYPE GetViewport(D3DVIEWPORT9 *pViewport) override;
virtual HRESULT STDMETHODCALLTYPE SetMaterial(const D3DMATERIAL9 *pMaterial) override;
virtual HRESULT STDMETHODCALLTYPE GetMaterial(D3DMATERIAL9 *pMaterial) override;
virtual HRESULT STDMETHODCALLTYPE SetLight(DWORD Index, const D3DLIGHT9 *pLight) override;
virtual HRESULT STDMETHODCALLTYPE GetLight(DWORD Index, D3DLIGHT9 *pLight) override;
virtual HRESULT STDMETHODCALLTYPE LightEnable(DWORD Index, BOOL Enable) override;
virtual HRESULT STDMETHODCALLTYPE GetLightEnable(DWORD Index, BOOL *pEnable) override;
virtual HRESULT STDMETHODCALLTYPE SetClipPlane(DWORD Index, const float *pPlane) override;
virtual HRESULT STDMETHODCALLTYPE GetClipPlane(DWORD Index, float *pPlane) override;
virtual HRESULT STDMETHODCALLTYPE SetRenderState(D3DRENDERSTATETYPE State, DWORD Value) override;
virtual HRESULT STDMETHODCALLTYPE GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue) override;
virtual HRESULT STDMETHODCALLTYPE CreateStateBlock(D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9 **ppSB) override;
virtual HRESULT STDMETHODCALLTYPE BeginStateBlock() override;
virtual HRESULT STDMETHODCALLTYPE EndStateBlock(IDirect3DStateBlock9 **ppSB) override;
virtual HRESULT STDMETHODCALLTYPE SetClipStatus(const D3DCLIPSTATUS9 *pClipStatus) override;
virtual HRESULT STDMETHODCALLTYPE GetClipStatus(D3DCLIPSTATUS9 *pClipStatus) override;
virtual HRESULT STDMETHODCALLTYPE GetTexture(DWORD Stage, IDirect3DBaseTexture9 **ppTexture) override;
virtual HRESULT STDMETHODCALLTYPE SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture) override;
virtual HRESULT STDMETHODCALLTYPE GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue) override;
virtual HRESULT STDMETHODCALLTYPE SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value) override;
virtual HRESULT STDMETHODCALLTYPE GetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD *pValue) override;
virtual HRESULT STDMETHODCALLTYPE SetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value) override;
virtual HRESULT STDMETHODCALLTYPE ValidateDevice(DWORD *pNumPasses) override;
virtual HRESULT STDMETHODCALLTYPE SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries) override;
virtual HRESULT STDMETHODCALLTYPE GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries) override;
virtual HRESULT STDMETHODCALLTYPE SetCurrentTexturePalette(UINT PaletteNumber) override;
virtual HRESULT STDMETHODCALLTYPE GetCurrentTexturePalette(UINT *PaletteNumber) override;
virtual HRESULT STDMETHODCALLTYPE SetScissorRect(const RECT *pRect) override;
virtual HRESULT STDMETHODCALLTYPE GetScissorRect(RECT *pRect) override;
virtual HRESULT STDMETHODCALLTYPE SetSoftwareVertexProcessing(BOOL bSoftware) override;
virtual BOOL STDMETHODCALLTYPE GetSoftwareVertexProcessing() override;
virtual HRESULT STDMETHODCALLTYPE SetNPatchMode(float nSegments) override;
virtual float STDMETHODCALLTYPE GetNPatchMode() override;
virtual HRESULT STDMETHODCALLTYPE DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) override;
virtual HRESULT STDMETHODCALLTYPE DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount) override;
virtual HRESULT STDMETHODCALLTYPE DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride) override;
virtual HRESULT STDMETHODCALLTYPE DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride) override;
virtual HRESULT STDMETHODCALLTYPE ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9 *pDestBuffer, IDirect3DVertexDeclaration9 *pVertexDecl, DWORD Flags) override;
virtual HRESULT STDMETHODCALLTYPE CreateVertexDeclaration(const D3DVERTEXELEMENT9 *pVertexElements, IDirect3DVertexDeclaration9 **ppDecl) override;
virtual HRESULT STDMETHODCALLTYPE SetVertexDeclaration(IDirect3DVertexDeclaration9 *pDecl) override;
virtual HRESULT STDMETHODCALLTYPE GetVertexDeclaration(IDirect3DVertexDeclaration9 **ppDecl) override;
virtual HRESULT STDMETHODCALLTYPE SetFVF(DWORD FVF) override;
virtual HRESULT STDMETHODCALLTYPE GetFVF(DWORD *pFVF) override;
virtual HRESULT STDMETHODCALLTYPE CreateVertexShader(const DWORD *pFunction, IDirect3DVertexShader9 **ppShader) override;
virtual HRESULT STDMETHODCALLTYPE SetVertexShader(IDirect3DVertexShader9 *pShader) override;
virtual HRESULT STDMETHODCALLTYPE GetVertexShader(IDirect3DVertexShader9 **ppShader) override;
virtual HRESULT STDMETHODCALLTYPE SetVertexShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount) override;
virtual HRESULT STDMETHODCALLTYPE GetVertexShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount) override;
virtual HRESULT STDMETHODCALLTYPE SetVertexShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount) override;
virtual HRESULT STDMETHODCALLTYPE GetVertexShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount) override;
virtual HRESULT STDMETHODCALLTYPE SetVertexShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount) override;
virtual HRESULT STDMETHODCALLTYPE GetVertexShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount) override;
virtual HRESULT STDMETHODCALLTYPE SetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 *pStreamData, UINT OffsetInBytes, UINT Stride) override;
virtual HRESULT STDMETHODCALLTYPE GetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 **ppStreamData, UINT *OffsetInBytes, UINT *pStride) override;
virtual HRESULT STDMETHODCALLTYPE SetStreamSourceFreq(UINT StreamNumber, UINT Divider) override;
virtual HRESULT STDMETHODCALLTYPE GetStreamSourceFreq(UINT StreamNumber, UINT *Divider) override;
virtual HRESULT STDMETHODCALLTYPE SetIndices(IDirect3DIndexBuffer9 *pIndexData) override;
virtual HRESULT STDMETHODCALLTYPE GetIndices(IDirect3DIndexBuffer9 **ppIndexData) override;
virtual HRESULT STDMETHODCALLTYPE CreatePixelShader(const DWORD *pFunction, IDirect3DPixelShader9 **ppShader) override;
virtual HRESULT STDMETHODCALLTYPE SetPixelShader(IDirect3DPixelShader9 *pShader) override;
virtual HRESULT STDMETHODCALLTYPE GetPixelShader(IDirect3DPixelShader9 **ppShader) override;
virtual HRESULT STDMETHODCALLTYPE SetPixelShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount) override;
virtual HRESULT STDMETHODCALLTYPE GetPixelShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount) override;
virtual HRESULT STDMETHODCALLTYPE SetPixelShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount) override;
virtual HRESULT STDMETHODCALLTYPE GetPixelShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount) override;
virtual HRESULT STDMETHODCALLTYPE SetPixelShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount) override;
virtual HRESULT STDMETHODCALLTYPE GetPixelShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount) override;
virtual HRESULT STDMETHODCALLTYPE DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo) override;
virtual HRESULT STDMETHODCALLTYPE DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo) override;
virtual HRESULT STDMETHODCALLTYPE DeletePatch(UINT Handle) override;
virtual HRESULT STDMETHODCALLTYPE CreateQuery(D3DQUERYTYPE Type, IDirect3DQuery9 **ppQuery) override;
virtual HRESULT STDMETHODCALLTYPE SetConvolutionMonoKernel(UINT width, UINT height, float *rows, float *columns) override;
virtual HRESULT STDMETHODCALLTYPE ComposeRects(IDirect3DSurface9 *pSrc, IDirect3DSurface9 *pDst, IDirect3DVertexBuffer9 *pSrcRectDescs, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescs, D3DCOMPOSERECTSOP Operation, int Xoffset, int Yoffset) override;
virtual HRESULT STDMETHODCALLTYPE PresentEx(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags) override;
virtual HRESULT STDMETHODCALLTYPE GetGPUThreadPriority(INT *pPriority) override;
virtual HRESULT STDMETHODCALLTYPE SetGPUThreadPriority(INT Priority) override;
virtual HRESULT STDMETHODCALLTYPE WaitForVBlank(UINT iSwapChain) override;
virtual HRESULT STDMETHODCALLTYPE CheckResourceResidency(IDirect3DResource9 **pResourceArray, UINT32 NumResources) override;
virtual HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT MaxLatency) override;
virtual HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(UINT *pMaxLatency) override;
virtual HRESULT STDMETHODCALLTYPE CheckDeviceState(HWND hDestinationWindow) override;
virtual HRESULT STDMETHODCALLTYPE CreateRenderTargetEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) override;
virtual HRESULT STDMETHODCALLTYPE CreateOffscreenPlainSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) override;
virtual HRESULT STDMETHODCALLTYPE CreateDepthStencilSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) override;
virtual HRESULT STDMETHODCALLTYPE ResetEx(D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode) override;
virtual HRESULT STDMETHODCALLTYPE GetDisplayModeEx(UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) override;
ULONG mRef;
IDirect3D9 *const mD3D;
IDirect3DDevice9 *const mOrig;
Direct3DSwapChain9 *mImplicitSwapChain;
std::vector<Direct3DSwapChain9 *> mAdditionalSwapChains;
IDirect3DSurface9 *mAutoDepthStencil;
};
struct Direct3DSwapChain9 : public IDirect3DSwapChain9Ex, private boost::noncopyable
{
friend struct Direct3DDevice9;
Direct3DSwapChain9(Direct3DDevice9 *device, IDirect3DSwapChain9 *originalSwapChain, const std::shared_ptr<ReShade::Runtimes::D3D9Runtime> runtime) : mRef(1), mDevice(device), mOrig(originalSwapChain), mRuntime(runtime)
{
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override;
virtual ULONG STDMETHODCALLTYPE AddRef() override;
virtual ULONG STDMETHODCALLTYPE Release() override;
virtual HRESULT STDMETHODCALLTYPE Present(CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) override;
virtual HRESULT STDMETHODCALLTYPE GetFrontBufferData(IDirect3DSurface9 *pDestSurface) override;
virtual HRESULT STDMETHODCALLTYPE GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer) override;
virtual HRESULT STDMETHODCALLTYPE GetRasterStatus(D3DRASTER_STATUS *pRasterStatus) override;
virtual HRESULT STDMETHODCALLTYPE GetDisplayMode(D3DDISPLAYMODE *pMode) override;
virtual HRESULT STDMETHODCALLTYPE GetDevice(IDirect3DDevice9 **ppDevice) override;
virtual HRESULT STDMETHODCALLTYPE GetPresentParameters(D3DPRESENT_PARAMETERS *pPresentationParameters) override;
virtual HRESULT STDMETHODCALLTYPE GetLastPresentCount(UINT *pLastPresentCount) override;
virtual HRESULT STDMETHODCALLTYPE GetPresentStats(D3DPRESENTSTATS *pPresentationStatistics) override;
virtual HRESULT STDMETHODCALLTYPE GetDisplayModeEx(D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) override;
ULONG mRef;
Direct3DDevice9 *const mDevice;
IDirect3DSwapChain9 *const mOrig;
std::shared_ptr<ReShade::Runtimes::D3D9Runtime> mRuntime;
};
LPCSTR GetErrorString(HRESULT hr)
{
switch (hr)
{
case E_INVALIDARG:
return "E_INVALIDARG";
case D3DERR_NOTAVAILABLE:
return "D3DERR_NOTAVAILABLE";
case D3DERR_INVALIDCALL:
return "D3DERR_INVALIDCALL";
case D3DERR_INVALIDDEVICE:
return "D3DERR_INVALIDDEVICE";
case D3DERR_DEVICEHUNG:
return "D3DERR_DEVICEHUNG";
case D3DERR_DEVICELOST:
return "D3DERR_DEVICELOST";
case D3DERR_DEVICENOTRESET:
return "D3DERR_DEVICENOTRESET";
case D3DERR_WASSTILLDRAWING:
return "D3DERR_WASSTILLDRAWING";
default:
__declspec(thread) static CHAR buf[20];
sprintf_s(buf, "0x%lx", hr);
return buf;
}
}
void DumpPresentParameters(const D3DPRESENT_PARAMETERS *pp)
{
LOG(TRACE) << "> Dumping Presentation Parameters:";
LOG(TRACE) << " +-----------------------------------------+-----------------------------------------+";
LOG(TRACE) << " | Parameter | Value |";
LOG(TRACE) << " +-----------------------------------------+-----------------------------------------+";
char value[40];
sprintf_s(value, "%-39u", pp->BackBufferWidth);
LOG(TRACE) << " | BackBufferWidth | " << value << " |";
sprintf_s(value, "%-39u", pp->BackBufferHeight);
LOG(TRACE) << " | BackBufferHeight | " << value << " |";
sprintf_s(value, "%-39u", pp->BackBufferFormat);
LOG(TRACE) << " | BackBufferFormat | " << value << " |";
sprintf_s(value, "%-39u", pp->BackBufferCount);
LOG(TRACE) << " | BackBufferCount | " << value << " |";
sprintf_s(value, "%-39u", pp->MultiSampleType);
LOG(TRACE) << " | MultiSampleType | " << value << " |";
sprintf_s(value, "%-39u", pp->MultiSampleQuality);
LOG(TRACE) << " | MultiSampleQuality | " << value << " |";
sprintf_s(value, "%-39u", pp->SwapEffect);
LOG(TRACE) << " | SwapEffect | " << value << " |";
sprintf_s(value, "0x%037IX", static_cast<const void *>(pp->hDeviceWindow));
LOG(TRACE) << " | hDeviceWindow | " << value << " |";
sprintf_s(value, "%-39d", pp->Windowed);
LOG(TRACE) << " | Windowed | " << value << " |";
sprintf_s(value, "%-39d", pp->EnableAutoDepthStencil);
LOG(TRACE) << " | EnableAutoDepthStencil | " << value << " |";
sprintf_s(value, "%-39u", pp->AutoDepthStencilFormat);
LOG(TRACE) << " | AutoDepthStencilFormat | " << value << " |";
sprintf_s(value, "0x%037X", pp->Flags);
LOG(TRACE) << " | Flags | " << value << " |";
sprintf_s(value, "%-39u", pp->FullScreen_RefreshRateInHz);
LOG(TRACE) << " | FullScreen_RefreshRateInHz | " << value << " |";
sprintf_s(value, "%-39u", pp->PresentationInterval);
LOG(TRACE) << " | PresentationInterval | " << value << " |";
LOG(TRACE) << " +-----------------------------------------+-----------------------------------------+";
}
void AdjustPresentParameters(D3DPRESENT_PARAMETERS *pp)
{
DumpPresentParameters(pp);
if (pp->SwapEffect != D3DSWAPEFFECT_COPY && pp->PresentationInterval != D3DPRESENT_INTERVAL_IMMEDIATE && pp->BackBufferCount < 2)
{
LOG(WARNING) << "> Forcing tripple buffering.";
pp->BackBufferCount = 2;
}
if (pp->MultiSampleType != D3DMULTISAMPLE_NONE)
{
LOG(WARNING) << "> Multisampling is enabled. This is not compatible with depthbuffer access, which was therefore disabled.";
}
}
}
// -----------------------------------------------------------------------------------------------------
// IDirect3DSwapChain9
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::QueryInterface(REFIID riid, void **ppvObj)
{
const HRESULT hr = this->mOrig->QueryInterface(riid, ppvObj);
if (SUCCEEDED(hr) && (riid == __uuidof(IUnknown) || riid == __uuidof(IDirect3DSwapChain9) || riid == __uuidof(IDirect3DSwapChain9Ex)))
{
this->mRef++;
*ppvObj = this;
}
return hr;
}
ULONG STDMETHODCALLTYPE Direct3DSwapChain9::AddRef()
{
++this->mRef;
return this->mOrig->AddRef();
}
ULONG STDMETHODCALLTYPE Direct3DSwapChain9::Release()
{
if (--this->mRef == 0)
{
assert(this->mRuntime != nullptr);
this->mRuntime->OnDeleteInternal();
this->mRuntime.reset();
}
const ULONG ref = this->mOrig->Release();
if (ref == 0)
{
const auto it = std::find(this->mDevice->mAdditionalSwapChains.begin(), this->mDevice->mAdditionalSwapChains.end(), this);
if (it != this->mDevice->mAdditionalSwapChains.end())
{
this->mDevice->mAdditionalSwapChains.erase(it);
}
delete this;
}
return ref;
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags)
{
assert(this->mRuntime != nullptr);
this->mRuntime->OnPresentInternal();
return this->mOrig->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetFrontBufferData(IDirect3DSurface9 *pDestSurface)
{
return this->mOrig->GetFrontBufferData(pDestSurface);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer)
{
return this->mOrig->GetBackBuffer(iBackBuffer, Type, ppBackBuffer);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetRasterStatus(D3DRASTER_STATUS *pRasterStatus)
{
return this->mOrig->GetRasterStatus(pRasterStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDisplayMode(D3DDISPLAYMODE *pMode)
{
return this->mOrig->GetDisplayMode(pMode);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDevice(IDirect3DDevice9 **ppDevice)
{
if (ppDevice == nullptr)
{
return D3DERR_INVALIDCALL;
}
assert(this->mDevice != nullptr);
this->mDevice->AddRef();
*ppDevice = this->mDevice;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetPresentParameters(D3DPRESENT_PARAMETERS *pPresentationParameters)
{
return this->mOrig->GetPresentParameters(pPresentationParameters);
}
// IDirect3DSwapChain9Ex
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetLastPresentCount(UINT *pLastPresentCount)
{
return static_cast<IDirect3DSwapChain9Ex *>(this->mOrig)->GetLastPresentCount(pLastPresentCount);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetPresentStats(D3DPRESENTSTATS *pPresentationStatistics)
{
return static_cast<IDirect3DSwapChain9Ex *>(this->mOrig)->GetPresentStats(pPresentationStatistics);
}
HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDisplayModeEx(D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation)
{
return static_cast<IDirect3DSwapChain9Ex *>(this->mOrig)->GetDisplayModeEx(pMode, pRotation);
}
// IDirect3DDevice9
HRESULT STDMETHODCALLTYPE Direct3DDevice9::QueryInterface(REFIID riid, void **ppvObj)
{
const HRESULT hr = this->mOrig->QueryInterface(riid, ppvObj);
if (SUCCEEDED(hr) && (riid == __uuidof(IUnknown) || riid == __uuidof(IDirect3DDevice9) || riid == __uuidof(IDirect3DDevice9Ex)))
{
this->mRef++;
*ppvObj = this;
}
return hr;
}
ULONG STDMETHODCALLTYPE Direct3DDevice9::AddRef()
{
++this->mRef;
return this->mOrig->AddRef();
}
ULONG STDMETHODCALLTYPE Direct3DDevice9::Release()
{
if (--this->mRef == 0)
{
if (this->mAutoDepthStencil != nullptr)
{
this->mAutoDepthStencil->Release();
this->mAutoDepthStencil = nullptr;
}
assert(this->mImplicitSwapChain != nullptr);
this->mImplicitSwapChain->Release();
this->mImplicitSwapChain = nullptr;
}
const ULONG ref = this->mOrig->Release();
if (ref == 0)
{
delete this;
}
return ref;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::TestCooperativeLevel()
{
return this->mOrig->TestCooperativeLevel();
}
UINT STDMETHODCALLTYPE Direct3DDevice9::GetAvailableTextureMem()
{
return this->mOrig->GetAvailableTextureMem();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EvictManagedResources()
{
return this->mOrig->EvictManagedResources();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDirect3D(IDirect3D9 **ppD3D9)
{
return this->mOrig->GetDirect3D(ppD3D9);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDeviceCaps(D3DCAPS9 *pCaps)
{
return this->mOrig->GetDeviceCaps(pCaps);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayMode(UINT iSwapChain, D3DDISPLAYMODE *pMode)
{
assert(iSwapChain == 0);
return this->mOrig->GetDisplayMode(0, pMode);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
return this->mOrig->GetCreationParameters(pParameters);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9 *pCursorBitmap)
{
return this->mOrig->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap);
}
void STDMETHODCALLTYPE Direct3DDevice9::SetCursorPosition(int X, int Y, DWORD Flags)
{
return this->mOrig->SetCursorPosition(X, Y, Flags);
}
BOOL STDMETHODCALLTYPE Direct3DDevice9::ShowCursor(BOOL bShow)
{
return this->mOrig->ShowCursor(bShow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DSwapChain9 **ppSwapChain)
{
LOG(INFO) << "Redirecting '" << "IDirect3DDevice9::CreateAdditionalSwapChain" << "(" << this << ", " << pPresentationParameters << ", " << ppSwapChain << ")' ...";
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
AdjustPresentParameters(pPresentationParameters);
const HRESULT hr = this->mOrig->CreateAdditionalSwapChain(pPresentationParameters, ppSwapChain);
if (SUCCEEDED(hr))
{
IDirect3DDevice9 *device = this->mOrig;
IDirect3DSwapChain9 *swapchain = *ppSwapChain;
D3DPRESENT_PARAMETERS pp;
swapchain->GetPresentParameters(&pp);
const std::shared_ptr<ReShade::Runtimes::D3D9Runtime> runtime = std::make_shared<ReShade::Runtimes::D3D9Runtime>(device, swapchain);
if (!runtime->OnCreateInternal(pp))
{
LOG(ERROR) << "Failed to initialize Direct3D9 renderer!";
}
Direct3DSwapChain9 *swapchainProxy = new Direct3DSwapChain9(this, swapchain, runtime);
this->mAdditionalSwapChains.push_back(swapchainProxy);
*ppSwapChain = swapchainProxy;
}
else
{
LOG(WARNING) << "> 'IDirect3DDevice9::CreateAdditionalSwapChain' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSwapChain(UINT iSwapChain, IDirect3DSwapChain9 **ppSwapChain)
{
if (ppSwapChain == nullptr)
{
return D3DERR_INVALIDCALL;
}
assert(iSwapChain == 0);
assert(this->mImplicitSwapChain != nullptr);
this->mImplicitSwapChain->AddRef();
*ppSwapChain = this->mImplicitSwapChain;
return D3D_OK;
}
UINT STDMETHODCALLTYPE Direct3DDevice9::GetNumberOfSwapChains()
{
return 1;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Reset(D3DPRESENT_PARAMETERS *pPresentationParameters)
{
LOG(INFO) << "Redirecting '" << "IDirect3DDevice9::Reset" << "(" << this << ", " << pPresentationParameters << ")' ...";
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
AdjustPresentParameters(pPresentationParameters);
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
ReShade::Runtimes::D3D9Runtime *runtime = this->mImplicitSwapChain->mRuntime.get();
runtime->OnDeleteInternal();
if (this->mAutoDepthStencil != nullptr)
{
this->mAutoDepthStencil->Release();
this->mAutoDepthStencil = nullptr;
}
const HRESULT hr = this->mOrig->Reset(pPresentationParameters);
if (SUCCEEDED(hr))
{
D3DPRESENT_PARAMETERS pp;
this->mImplicitSwapChain->GetPresentParameters(&pp);
if (!runtime->OnCreateInternal(pp))
{
LOG(ERROR) << "Failed to reset Direct3D9 renderer!";
}
if (pp.EnableAutoDepthStencil != FALSE)
{
this->mOrig->GetDepthStencilSurface(&this->mAutoDepthStencil);
SetDepthStencilSurface(this->mAutoDepthStencil);
}
}
else
{
LOG(ERROR) << "'IDirect3DDevice9::Reset' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
ReShade::Runtimes::D3D9Runtime *runtime = this->mImplicitSwapChain->mRuntime.get();
runtime->OnPresentInternal();
return this->mOrig->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetBackBuffer(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer)
{
assert(iSwapChain == 0);
assert(this->mImplicitSwapChain != nullptr);
return this->mImplicitSwapChain->GetBackBuffer(iBackBuffer, Type, ppBackBuffer);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRasterStatus(UINT iSwapChain, D3DRASTER_STATUS *pRasterStatus)
{
assert(iSwapChain == 0);
return this->mOrig->GetRasterStatus(0, pRasterStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDialogBoxMode(BOOL bEnableDialogs)
{
return this->mOrig->SetDialogBoxMode(bEnableDialogs);
}
void STDMETHODCALLTYPE Direct3DDevice9::SetGammaRamp(UINT iSwapChain, DWORD Flags, const D3DGAMMARAMP *pRamp)
{
assert(iSwapChain == 0);
return this->mOrig->SetGammaRamp(0, Flags, pRamp);
}
void STDMETHODCALLTYPE Direct3DDevice9::GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP *pRamp)
{
assert(iSwapChain == 0);
return this->mOrig->GetGammaRamp(0, pRamp);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9 **ppTexture, HANDLE *pSharedHandle)
{
return this->mOrig->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9 **ppVolumeTexture, HANDLE *pSharedHandle)
{
return this->mOrig->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9 **ppCubeTexture, HANDLE *pSharedHandle)
{
return this->mOrig->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9 **ppVertexBuffer, HANDLE *pSharedHandle)
{
return this->mOrig->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9 **ppIndexBuffer, HANDLE *pSharedHandle)
{
return this->mOrig->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return this->mOrig->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return this->mOrig->CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateSurface(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestinationSurface, const POINT *pDestPoint)
{
return this->mOrig->UpdateSurface(pSourceSurface, pSourceRect, pDestinationSurface, pDestPoint);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateTexture(IDirect3DBaseTexture9 *pSourceTexture, IDirect3DBaseTexture9 *pDestinationTexture)
{
return this->mOrig->UpdateTexture(pSourceTexture, pDestinationTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTargetData(IDirect3DSurface9 *pRenderTarget, IDirect3DSurface9 *pDestSurface)
{
return this->mOrig->GetRenderTargetData(pRenderTarget, pDestSurface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFrontBufferData(UINT iSwapChain, IDirect3DSurface9 *pDestSurface)
{
assert(iSwapChain == 0);
return this->mOrig->GetFrontBufferData(0, pDestSurface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::StretchRect(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestSurface, const RECT *pDestRect, D3DTEXTUREFILTERTYPE Filter)
{
return this->mOrig->StretchRect(pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ColorFill(IDirect3DSurface9 *pSurface, const RECT *pRect, D3DCOLOR color)
{
return this->mOrig->ColorFill(pSurface, pRect, color);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return this->mOrig->CreateOffscreenPlainSurface(Width, Height, Format, Pool, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 *pRenderTarget)
{
return this->mOrig->SetRenderTarget(RenderTargetIndex, pRenderTarget);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 **ppRenderTarget)
{
return this->mOrig->GetRenderTarget(RenderTargetIndex, ppRenderTarget);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDepthStencilSurface(IDirect3DSurface9 *pNewZStencil)
{
if (pNewZStencil != nullptr)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnSetDepthStencilSurface(pNewZStencil);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime != nullptr);
swapchain->mRuntime->OnSetDepthStencilSurface(pNewZStencil);
}
}
return this->mOrig->SetDepthStencilSurface(pNewZStencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDepthStencilSurface(IDirect3DSurface9 **ppZStencilSurface)
{
const HRESULT hr = this->mOrig->GetDepthStencilSurface(ppZStencilSurface);
if (SUCCEEDED(hr))
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnGetDepthStencilSurface(*ppZStencilSurface);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime);
swapchain->mRuntime->OnGetDepthStencilSurface(*ppZStencilSurface);
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginScene()
{
return this->mOrig->BeginScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndScene()
{
return this->mOrig->EndScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
return this->mOrig->Clear(Count, pRects, Flags, Color, Z, Stencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return this->mOrig->SetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix)
{
return this->mOrig->GetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return this->mOrig->MultiplyTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetViewport(const D3DVIEWPORT9 *pViewport)
{
return this->mOrig->SetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetViewport(D3DVIEWPORT9 *pViewport)
{
return this->mOrig->GetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaterial(const D3DMATERIAL9 *pMaterial)
{
return this->mOrig->SetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaterial(D3DMATERIAL9 *pMaterial)
{
return this->mOrig->GetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetLight(DWORD Index, const D3DLIGHT9 *pLight)
{
return this->mOrig->SetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLight(DWORD Index, D3DLIGHT9 *pLight)
{
return this->mOrig->GetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::LightEnable(DWORD Index, BOOL Enable)
{
return this->mOrig->LightEnable(Index, Enable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLightEnable(DWORD Index, BOOL *pEnable)
{
return this->mOrig->GetLightEnable(Index, pEnable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipPlane(DWORD Index, const float *pPlane)
{
return this->mOrig->SetClipPlane(Index, pPlane);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipPlane(DWORD Index, float *pPlane)
{
return this->mOrig->GetClipPlane(Index, pPlane);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value)
{
return this->mOrig->SetRenderState(State, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue)
{
return this->mOrig->GetRenderState(State, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateStateBlock(D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9 **ppSB)
{
return this->mOrig->CreateStateBlock(Type, ppSB);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginStateBlock()
{
return this->mOrig->BeginStateBlock();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndStateBlock(IDirect3DStateBlock9 **ppSB)
{
return this->mOrig->EndStateBlock(ppSB);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipStatus(const D3DCLIPSTATUS9 *pClipStatus)
{
return this->mOrig->SetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipStatus(D3DCLIPSTATUS9 *pClipStatus)
{
return this->mOrig->GetClipStatus( pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTexture(DWORD Stage, IDirect3DBaseTexture9 **ppTexture)
{
return this->mOrig->GetTexture(Stage, ppTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture)
{
return this->mOrig->SetTexture(Stage, pTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue)
{
return this->mOrig->GetTextureStageState(Stage, Type, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
return this->mOrig->SetTextureStageState(Stage, Type, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD *pValue)
{
return this->mOrig->GetSamplerState(Sampler, Type, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value)
{
return this->mOrig->SetSamplerState(Sampler, Type, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ValidateDevice(DWORD *pNumPasses)
{
return this->mOrig->ValidateDevice( pNumPasses);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries)
{
return this->mOrig->SetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries)
{
return this->mOrig->GetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCurrentTexturePalette(UINT PaletteNumber)
{
return this->mOrig->SetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCurrentTexturePalette(UINT *PaletteNumber)
{
return this->mOrig->GetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetScissorRect(const RECT *pRect)
{
return this->mOrig->SetScissorRect( pRect);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetScissorRect(RECT *pRect)
{
return this->mOrig->GetScissorRect( pRect);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSoftwareVertexProcessing(BOOL bSoftware)
{
return this->mOrig->SetSoftwareVertexProcessing(bSoftware);
}
BOOL STDMETHODCALLTYPE Direct3DDevice9::GetSoftwareVertexProcessing()
{
return this->mOrig->GetSoftwareVertexProcessing();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetNPatchMode(float nSegments)
{
return this->mOrig->SetNPatchMode(nSegments);
}
float STDMETHODCALLTYPE Direct3DDevice9::GetNPatchMode()
{
return this->mOrig->GetNPatchMode();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime != nullptr);
swapchain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
}
return this->mOrig->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime != nullptr);
swapchain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
}
return this->mOrig->DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, StartIndex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime != nullptr);
swapchain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
}
return this->mOrig->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
this->mImplicitSwapChain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
for (Direct3DSwapChain9 *swapchain : this->mAdditionalSwapChains)
{
assert(swapchain->mRuntime != nullptr);
swapchain->mRuntime->OnDrawInternal(PrimitiveType, PrimitiveCount);
}
return this->mOrig->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9 *pDestBuffer, IDirect3DVertexDeclaration9 *pVertexDecl, DWORD Flags)
{
return this->mOrig->ProcessVertices( SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexDeclaration(const D3DVERTEXELEMENT9 *pVertexElements, IDirect3DVertexDeclaration9 **ppDecl)
{
return this->mOrig->CreateVertexDeclaration( pVertexElements, ppDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexDeclaration(IDirect3DVertexDeclaration9 *pDecl)
{
return this->mOrig->SetVertexDeclaration(pDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexDeclaration(IDirect3DVertexDeclaration9 **ppDecl)
{
return this->mOrig->GetVertexDeclaration(ppDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetFVF(DWORD FVF)
{
return this->mOrig->SetFVF(FVF);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFVF(DWORD *pFVF)
{
return this->mOrig->GetFVF(pFVF);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexShader(const DWORD *pFunction, IDirect3DVertexShader9 **ppShader)
{
return this->mOrig->CreateVertexShader(pFunction, ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShader(IDirect3DVertexShader9 *pShader)
{
return this->mOrig->SetVertexShader(pShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShader(IDirect3DVertexShader9 **ppShader)
{
return this->mOrig->GetVertexShader(ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount)
{
return this->mOrig->SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount)
{
return this->mOrig->GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount)
{
return this->mOrig->SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount)
{
return this->mOrig->GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount)
{
return this->mOrig->SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount)
{
return this->mOrig->GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 *pStreamData, UINT OffsetInBytes, UINT Stride)
{
return this->mOrig->SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 **ppStreamData, UINT *OffsetInBytes, UINT *pStride)
{
return this->mOrig->GetStreamSource(StreamNumber, ppStreamData, OffsetInBytes, pStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSourceFreq(UINT StreamNumber, UINT Divider)
{
return this->mOrig->SetStreamSourceFreq(StreamNumber, Divider);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSourceFreq(UINT StreamNumber, UINT *Divider)
{
return this->mOrig->GetStreamSourceFreq(StreamNumber, Divider);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetIndices(IDirect3DIndexBuffer9 *pIndexData)
{
return this->mOrig->SetIndices(pIndexData);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetIndices(IDirect3DIndexBuffer9 **ppIndexData)
{
return this->mOrig->GetIndices(ppIndexData);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreatePixelShader(const DWORD *pFunction, IDirect3DPixelShader9 **ppShader)
{
return this->mOrig->CreatePixelShader(pFunction, ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShader(IDirect3DPixelShader9 *pShader)
{
return this->mOrig->SetPixelShader(pShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShader(IDirect3DPixelShader9 **ppShader)
{
return this->mOrig->GetPixelShader(ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount)
{
return this->mOrig->SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount)
{
return this->mOrig->GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount)
{
return this->mOrig->SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount)
{
return this->mOrig->GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount)
{
return this->mOrig->SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount)
{
return this->mOrig->GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo)
{
return this->mOrig->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo)
{
return this->mOrig->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DeletePatch(UINT Handle)
{
return this->mOrig->DeletePatch(Handle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateQuery(D3DQUERYTYPE Type, IDirect3DQuery9 **ppQuery)
{
return this->mOrig->CreateQuery(Type, ppQuery);
}
// IDirect3DDevice9Ex
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetConvolutionMonoKernel(UINT width, UINT height, float *rows, float *columns)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->SetConvolutionMonoKernel(width, height, rows, columns);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ComposeRects(IDirect3DSurface9 *pSrc, IDirect3DSurface9 *pDst, IDirect3DVertexBuffer9 *pSrcRectDescs, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescs, D3DCOMPOSERECTSOP Operation, int Xoffset, int Yoffset)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->ComposeRects(pSrc, pDst, pSrcRectDescs, NumRects, pDstRectDescs, Operation, Xoffset, Yoffset);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::PresentEx(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags)
{
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
ReShade::Runtimes::D3D9Runtime *runtime = this->mImplicitSwapChain->mRuntime.get();
runtime->OnPresentInternal();
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->PresentEx(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetGPUThreadPriority(INT *pPriority)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->GetGPUThreadPriority(pPriority);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetGPUThreadPriority(INT Priority)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->SetGPUThreadPriority(Priority);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::WaitForVBlank(UINT iSwapChain)
{
assert(iSwapChain == 0);
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->WaitForVBlank(0);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckResourceResidency(IDirect3DResource9 **pResourceArray, UINT32 NumResources)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->CheckResourceResidency(pResourceArray, NumResources);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaximumFrameLatency(UINT MaxLatency)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->SetMaximumFrameLatency(MaxLatency);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaximumFrameLatency(UINT *pMaxLatency)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->GetMaximumFrameLatency(pMaxLatency);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckDeviceState(HWND hDestinationWindow)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->CheckDeviceState(hDestinationWindow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTargetEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->CreateRenderTargetEx(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->CreateOffscreenPlainSurfaceEx(Width, Height, Format, Pool, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->CreateDepthStencilSurfaceEx(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ResetEx(D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode)
{
LOG(INFO) << "Redirecting '" << "IDirect3DDevice9Ex::ResetEx" << "(" << this << ", " << pPresentationParameters << ", " << pFullscreenDisplayMode << ")' ...";
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
AdjustPresentParameters(pPresentationParameters);
assert(this->mImplicitSwapChain != nullptr);
assert(this->mImplicitSwapChain->mRuntime != nullptr);
ReShade::Runtimes::D3D9Runtime *runtime = this->mImplicitSwapChain->mRuntime.get();
runtime->OnDeleteInternal();
if (this->mAutoDepthStencil != nullptr)
{
this->mAutoDepthStencil->Release();
this->mAutoDepthStencil = nullptr;
}
const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(this->mOrig)->ResetEx(pPresentationParameters, pFullscreenDisplayMode);
if (SUCCEEDED(hr))
{
D3DPRESENT_PARAMETERS pp;
this->mImplicitSwapChain->GetPresentParameters(&pp);
if (!runtime->OnCreateInternal(pp))
{
LOG(ERROR) << "Failed to reset Direct3D9 renderer!";
}
if (pp.EnableAutoDepthStencil != FALSE)
{
this->mOrig->GetDepthStencilSurface(&this->mAutoDepthStencil);
SetDepthStencilSurface(this->mAutoDepthStencil);
}
}
else
{
LOG(ERROR) << "'IDirect3DDevice9Ex::ResetEx' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayModeEx(UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation)
{
assert(iSwapChain == 0);
return static_cast<IDirect3DDevice9Ex *>(this->mOrig)->GetDisplayModeEx(0, pMode, pRotation);
}
// IDirect3D9
HRESULT STDMETHODCALLTYPE IDirect3D9_CreateDevice(IDirect3D9 *pD3D, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DDevice9 **ppReturnedDeviceInterface)
{
LOG(INFO) << "Redirecting '" << "IDirect3D9::CreateDevice" << "(" << pD3D << ", " << Adapter << ", " << DeviceType << ", " << hFocusWindow << ", " << BehaviorFlags << ", " << pPresentationParameters << ", " << ppReturnedDeviceInterface << ")' ...";
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
AdjustPresentParameters(pPresentationParameters);
const HRESULT hr = ReShade::Hooks::Call(&IDirect3D9_CreateDevice)(pD3D, Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
if (SUCCEEDED(hr))
{
IDirect3DDevice9 *device = *ppReturnedDeviceInterface;
IDirect3DSwapChain9 *swapchain = nullptr;
device->GetSwapChain(0, &swapchain);
assert(swapchain != nullptr);
D3DPRESENT_PARAMETERS pp;
swapchain->GetPresentParameters(&pp);
const std::shared_ptr<ReShade::Runtimes::D3D9Runtime> runtime = std::make_shared<ReShade::Runtimes::D3D9Runtime>(device, swapchain);
if (!runtime->OnCreateInternal(pp))
{
LOG(ERROR) << "Failed to initialize Direct3D9 renderer!";
}
Direct3DDevice9 *deviceProxy = new Direct3DDevice9(pD3D, device);
Direct3DSwapChain9 *swapchainProxy = new Direct3DSwapChain9(deviceProxy, swapchain, runtime);
deviceProxy->mImplicitSwapChain = swapchainProxy;
*ppReturnedDeviceInterface = deviceProxy;
if (pp.EnableAutoDepthStencil != FALSE)
{
device->GetDepthStencilSurface(&deviceProxy->mAutoDepthStencil);
deviceProxy->SetDepthStencilSurface(deviceProxy->mAutoDepthStencil);
}
}
else
{
LOG(WARNING) << "> 'IDirect3D9::CreateDevice' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
}
// IDirect3D9Ex
HRESULT STDMETHODCALLTYPE IDirect3D9Ex_CreateDeviceEx(IDirect3D9Ex *pD3D, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode, IDirect3DDevice9Ex **ppReturnedDeviceInterface)
{
LOG(INFO) << "Redirecting '" << "IDirect3D9Ex::CreateDeviceEx" << "(" << pD3D << ", " << Adapter << ", " << DeviceType << ", " << hFocusWindow << ", " << BehaviorFlags << ", " << pPresentationParameters << ", " << pFullscreenDisplayMode << ", " << ppReturnedDeviceInterface << ")' ...";
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
AdjustPresentParameters(pPresentationParameters);
const HRESULT hr = ReShade::Hooks::Call(&IDirect3D9Ex_CreateDeviceEx)(pD3D, Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, pFullscreenDisplayMode, ppReturnedDeviceInterface);
if (SUCCEEDED(hr))
{
IDirect3DDevice9Ex *device = *ppReturnedDeviceInterface;
IDirect3DSwapChain9 *swapchain = nullptr;
device->GetSwapChain(0, &swapchain);
assert(swapchain != nullptr);
D3DPRESENT_PARAMETERS pp;
swapchain->GetPresentParameters(&pp);
const std::shared_ptr<ReShade::Runtimes::D3D9Runtime> runtime = std::make_shared<ReShade::Runtimes::D3D9Runtime>(device, swapchain);
if (!runtime->OnCreateInternal(pp))
{
LOG(ERROR) << "Failed to initialize Direct3D9 renderer!";
}
Direct3DDevice9 *deviceProxy = new Direct3DDevice9(pD3D, device);
Direct3DSwapChain9 *swapchainProxy = new Direct3DSwapChain9(deviceProxy, swapchain, runtime);
deviceProxy->mImplicitSwapChain = swapchainProxy;
*ppReturnedDeviceInterface = deviceProxy;
if (pp.EnableAutoDepthStencil != FALSE)
{
device->GetDepthStencilSurface(&deviceProxy->mAutoDepthStencil);
deviceProxy->SetDepthStencilSurface(deviceProxy->mAutoDepthStencil);
}
}
else
{
LOG(WARNING) << "> 'IDirect3D9Ex::CreateDeviceEx' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
}
// PIX
EXPORT int WINAPI D3DPERF_BeginEvent(D3DCOLOR col, LPCWSTR wszName)
{
UNREFERENCED_PARAMETER(col);
UNREFERENCED_PARAMETER(wszName);
return 0;
}
EXPORT int WINAPI D3DPERF_EndEvent()
{
return 0;
}
EXPORT void WINAPI D3DPERF_SetMarker(D3DCOLOR col, LPCWSTR wszName)
{
UNREFERENCED_PARAMETER(col);
UNREFERENCED_PARAMETER(wszName);
}
EXPORT void WINAPI D3DPERF_SetRegion(D3DCOLOR col, LPCWSTR wszName)
{
UNREFERENCED_PARAMETER(col);
UNREFERENCED_PARAMETER(wszName);
}
EXPORT BOOL WINAPI D3DPERF_QueryRepeatFrame()
{
return FALSE;
}
EXPORT void WINAPI D3DPERF_SetOptions(DWORD dwOptions)
{
UNREFERENCED_PARAMETER(dwOptions);
#ifdef _DEBUG
static const auto trampoline = ReShade::Hooks::Call(&D3DPERF_SetOptions);
trampoline(0);
#endif
}
EXPORT DWORD WINAPI D3DPERF_GetStatus()
{
return 0;
}
// D3D9
EXPORT IDirect3D9 *WINAPI Direct3DCreate9(UINT SDKVersion)
{
LOG(INFO) << "Redirecting '" << "Direct3DCreate9" << "(" << SDKVersion << ")' ...";
IDirect3D9 *res = ReShade::Hooks::Call(&Direct3DCreate9)(SDKVersion);
if (res != nullptr)
{
ReShade::Hooks::Register(VTABLE(res)[16], reinterpret_cast<ReShade::Hook::Function>(&IDirect3D9_CreateDevice));
}
else
{
LOG(WARNING) << "> 'Direct3DCreate9' failed!";
}
return res;
}
EXPORT HRESULT WINAPI Direct3DCreate9Ex(UINT SDKVersion, IDirect3D9Ex **ppD3D)
{
LOG(INFO) << "Redirecting '" << "Direct3DCreate9Ex" << "(" << SDKVersion << ", " << ppD3D << ")' ...";
const HRESULT hr = ReShade::Hooks::Call(&Direct3DCreate9Ex)(SDKVersion, ppD3D);
if (SUCCEEDED(hr))
{
ReShade::Hooks::Register(VTABLE(*ppD3D)[16], reinterpret_cast<ReShade::Hook::Function>(&IDirect3D9_CreateDevice));
ReShade::Hooks::Register(VTABLE(*ppD3D)[20], reinterpret_cast<ReShade::Hook::Function>(&IDirect3D9Ex_CreateDeviceEx));
}
else
{
LOG(WARNING) << "> 'Direct3DCreate9Ex' failed with '" << GetErrorString(hr) << "'!";
}
return hr;
} |
zqannnnn/Project-staging | 08-start-redux/src/app.js | <reponame>zqannnnn/Project-staging
import { createStore } from 'redux';
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
/**
* 使用这个reducer纯函数代替上面的函数,会发现:
* 当state为对象时,如果在reducer中修改state,
* 将会导致新旧state指向一个地址
*/
// function counter(state = { val: 0 }, action) {
// switch (action.type) {
// case 'INCREMENT':
// state.val++;
// return state;
// case 'DECREMENT':
// state.val--;
// return state;
// default:
// return state;
// }
// }
const store = createStore(counter);
let currentValue = store.getState();
const listener = () => {
const previousValue = currentValue;
currentValue = store.getState();
console.log('pre state:', previousValue, 'next state:', currentValue);
};
store.subscribe(listener);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
|
amckay7777/hedera-services | hedera-node/src/main/java/com/hedera/services/state/expiry/MonotonicFullQueueExpiries.java | package com.hedera.services.state.expiry;
/*-
*
* Hedera Services Node
*
* Copyright (C) 2018 - 2021 Hedera Hashgraph, 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.
*
*/
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Queue of expiration events in which events are in the order of insertion
*/
public class MonotonicFullQueueExpiries<K> implements KeyedExpirations<K> {
private long now = 0L;
private Deque<ExpiryEvent<K>> allExpiries = new ArrayDeque<>();
@Override
public void reset() {
now = 0L;
allExpiries.clear();
}
@Override
public void track(K id, long expiry) {
if (expiry < now) {
throw new IllegalArgumentException(String.format("Track time %d for %s not later than %d", expiry, id, now));
}
now = expiry;
allExpiries.add(new ExpiryEvent<>(id, expiry));
}
@Override
public boolean hasExpiringAt(long now) {
return !allExpiries.isEmpty() && allExpiries.peekFirst().isExpiredAt(now);
}
@Override
public K expireNextAt(long now) {
if (allExpiries.isEmpty()) {
throw new IllegalStateException("No ids are queued for expiration!");
}
if (!allExpiries.peek().isExpiredAt(now)) {
throw new IllegalArgumentException(String.format("Argument 'now=%d' is earlier than the next expiry!",
now));
}
return allExpiries.removeFirst().getId();
}
Deque<ExpiryEvent<K>> getAllExpiries() {
return allExpiries;
}
long getNow() {
return now;
}
}
|
masud-technope/ACER-Replication-Package-ASE2017 | corpus/class/eclipse.jdt.ui/7290.java | package p;
class A {
static void k() {
}
}
class B extends A {
static void m() {
}
;
}
class Test {
void f() {
new A().k();
A.k();
new B().m();
B.m();
}
}
|
BohdanMosiyuk/samples | snippets/cpp/VS_Snippets_CLR/AssemblyName_Constructor_2/CPP/source.cpp | // REDMOND\glennha
// Simplified snippet per SuzCook tech review.
// <Snippet1>
using namespace System;
using namespace System::Reflection;
int main()
{
// Create an AssemblyName, specifying the display name, and then
// print the properties.
AssemblyName^ myAssemblyName =
gcnew AssemblyName("Example, Version=1.0.0.2001, Culture=en-US, PublicKeyToken=null");
Console::WriteLine("Name: {0}", myAssemblyName->Name);
Console::WriteLine("Version: {0}", myAssemblyName->Version);
Console::WriteLine("CultureInfo: {0}", myAssemblyName->CultureInfo);
Console::WriteLine("FullName: {0}", myAssemblyName->FullName);
}
/* This code example produces output similar to the following:
Name: Example
Version: 1.0.0.2001
CultureInfo: en-US
FullName: Example, Version=1.0.0.2001, Culture=en-US, PublicKeyToken=null
*/
// </Snippet1>
|
alpavlenko/EvoGuess | executor/module/shaping/impl/chunks.py | <gh_stars>1-10
from ..shaping import *
from util.array import slice_by_size
from numpy.random.mtrand import RandomState
class Chunks(Shaping):
slug = 'shaping:chunks'
name = 'Shaping: Chunks'
def __init__(self, chunk_rate, *args, **kwargs):
self.chunk_rate = chunk_rate
super().__init__()
def get(self, size, tasks):
chunks_count = max(1, self.chunk_rate * size)
chunk_size = max(1, int(len(tasks) // chunks_count))
return slice_by_size(chunk_size, tasks)
def __info__(self):
return {
**super().__info__(),
'chunk_rate': self.chunk_rate
}
|
Joanguitar/docker-nextepc | virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/lib/examples/usrp_capture.c | <gh_stars>0
/**
*
* \section COPYRIGHT
*
* Copyright 2013-2015 Software Radio Systems Limited
*
* \section LICENSE
*
* This file is part of the srsLTE library.
*
* srsLTE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* srsLTE 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 Affero General Public License for more details.
*
* A copy of the GNU Affero General Public License can be found in
* the LICENSE file in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/.
*
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include "srslte/srslte.h"
#include "srslte/phy/rf/rf.h"
#include "srslte/phy/io/filesink.h"
static bool keep_running = true;
char *output_file_name;
char *rf_args="";
float rf_gain=40.0, rf_freq=-1.0, rf_rate=0.96e6;
int nof_samples = -1;
int nof_rx_antennas = 1;
void int_handler(int dummy) {
keep_running = false;
}
void usage(char *prog) {
printf("Usage: %s [agrnv] -f rx_frequency_hz -o output_file\n", prog);
printf("\t-a RF args [Default %s]\n", rf_args);
printf("\t-g RF Gain [Default %.2f dB]\n", rf_gain);
printf("\t-r RF Rate [Default %.6f Hz]\n", rf_rate);
printf("\t-n nof_samples [Default %d]\n", nof_samples);
printf("\t-A nof_rx_antennas [Default %d]\n", nof_rx_antennas);
printf("\t-v srslte_verbose\n");
}
void parse_args(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "agrnvfoA")) != -1) {
switch (opt) {
case 'o':
output_file_name = argv[optind];
break;
case 'a':
rf_args = argv[optind];
break;
case 'g':
rf_gain = atof(argv[optind]);
break;
case 'r':
rf_rate = atof(argv[optind]);
break;
case 'f':
rf_freq = atof(argv[optind]);
break;
case 'n':
nof_samples = atoi(argv[optind]);
break;
case 'A':
nof_rx_antennas = atoi(argv[optind]);
break;
case 'v':
srslte_verbose++;
break;
default:
usage(argv[0]);
exit(-1);
}
}
if (rf_freq < 0) {
usage(argv[0]);
exit(-1);
}
}
int main(int argc, char **argv) {
cf_t *buffer[SRSLTE_MAX_PORTS];
int sample_count, n;
srslte_rf_t rf;
srslte_filesink_t sink;
uint32_t buflen;
signal(SIGINT, int_handler);
parse_args(argc, argv);
buflen = 4800;
sample_count = 0;
for (int i = 0; i < nof_rx_antennas; i++) {
buffer[i] = malloc(sizeof(cf_t) * buflen);
if (!buffer[i]) {
perror("malloc");
exit(-1);
}
}
srslte_filesink_init(&sink, output_file_name, SRSLTE_COMPLEX_FLOAT_BIN);
printf("Opening RF device...\n");
if (srslte_rf_open_multi(&rf, rf_args, nof_rx_antennas)) {
fprintf(stderr, "Error opening rf\n");
exit(-1);
}
srslte_rf_set_master_clock_rate(&rf, 30.72e6);
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGINT);
sigprocmask(SIG_UNBLOCK, &sigset, NULL);
printf("Set RX freq: %.2f MHz\n", srslte_rf_set_rx_freq(&rf, rf_freq) / 1000000);
printf("Set RX gain: %.2f dB\n", srslte_rf_set_rx_gain(&rf, rf_gain));
float srate = srslte_rf_set_rx_srate(&rf, rf_rate);
if (srate != rf_rate) {
if (srate < 10e6) {
srslte_rf_set_master_clock_rate(&rf, 4*rf_rate);
} else {
srslte_rf_set_master_clock_rate(&rf, rf_rate);
}
srate = srslte_rf_set_rx_srate(&rf, rf_rate);
if (srate != rf_rate) {
fprintf(stderr, "Errror setting samplign frequency %.2f MHz\n", rf_rate*1e-6);
exit(-1);
}
}
printf("Correctly RX rate: %.2f MHz\n", srate*1e-6);
srslte_rf_rx_wait_lo_locked(&rf);
srslte_rf_start_rx_stream(&rf, false);
while((sample_count < nof_samples || nof_samples == -1)
&& keep_running){
n = srslte_rf_recv_with_time_multi(&rf, (void**) buffer, buflen, true, NULL, NULL);
if (n < 0) {
fprintf(stderr, "Error receiving samples\n");
exit(-1);
}
srslte_filesink_write_multi(&sink, (void**) buffer, buflen, nof_rx_antennas);
sample_count += buflen;
}
for (int i = 0; i < nof_rx_antennas; i++) {
if (buffer[i]) {
free(buffer[i]);
}
}
srslte_filesink_free(&sink);
srslte_rf_close(&rf);
printf("Ok - wrote %d samples\n", sample_count);
exit(0);
}
|
TJKoury/is_chrome_broken | Source/Shaders/Builtin/Constants/oneOverTwoPi.js | //This file is automatically rebuilt by the Cesium build process.
export default "const float czm_oneOverTwoPi = 0.15915494309189535;\n\
";
|
robinandeer/grommet | src/js/components/Markdown/doc.js | import { describe, PropTypes } from 'react-desc';
import { getAvailableAtBadge } from '../../utils';
export const doc = Markdown => {
const DocumentedMarkdown = describe(Markdown)
.availableAt(getAvailableAtBadge('Markdown'))
.description('Markdown formatting using Grommet components.')
.usage(
`import { Markdown } from 'grommet';
<Markdown>{content}</Markdown>`,
)
.intrinsicElement('div');
DocumentedMarkdown.propTypes = {
components: PropTypes.shape({}).description(
`Custom components and props to override html elements such as 'img'
or 'pre'. By default 'a', 'p', 'img', and table elements are overriden
with grommet components`,
),
};
return DocumentedMarkdown;
};
|
vrk-kpa/opendata-ckan | modules/ckanext-ytp_main/ckanext/ytp/harvesters/syke_harvester.py |
import datetime
import six
from ckan.lib.helpers import json, date_str_to_datetime
from ckan.plugins import toolkit
from ckan.lib.munge import munge_tag
from ckanext.harvest.model import HarvestObject
from ckanext.harvest.harvesters.ckanharvester import CKANHarvester
import logging
log = logging.getLogger(__name__)
_category_mapping = {
'alueet-ja-kaupungit': ['boundaries', 'planningCadastre', 'imageryBaseMapsEarthCover', 'location'],
'liikenne': ['transportation'],
'maatalous-kalastus-metsatalous-ja-elintarvikkeet': ['farming'],
'oikeus-oikeusjarjestelma-ja-yleinen-turvallisuus': ['intelligenceMilitary'],
'rakennettu-ymparisto-ja-infrastruktuuri': ['utilitiesCommunication', 'structure'],
'talous-ja-rahoitus': ['economy'],
'terveys': ['health'],
'vaesto-ja-yhteiskunta': ['society'],
'ymparisto-ja-luonto': ['climatologyMeteorologyAtmosphere', 'elevation', 'environment',
'geoscientificInformation', 'biota', 'inlandWaters', 'oceans']
}
class SYKEHarvester(CKANHarvester):
def info(self):
return {
'name': 'syke',
'title': 'SYKE',
'description': 'Harvests remote CKAN instance of SYKE',
'form_config_interface': 'Text'
}
def modify_package_dict(self, package_dict, harvest_object):
package_dict['title_translated'] = {
"fi": package_dict.get('title', '')
}
package_dict['notes_translated'] = {
"fi": package_dict.get('notes', '')
}
package_dict['collection_type'] = 'Open Data'
package_dict['license_id'] = 'cc-by-4.0'
package_dict['maintainer_website'] = 'https://www.syke.fi'
package_dict['resources'] = [
dict(resource.items() + {'name_translated': {'fi': resource.get('name')}}.items())
for resource in package_dict.get('resources', [])
]
# Remove tags as we don't use them
package_dict.pop('tags', None)
extras = package_dict.get('extras', [])
for k, v, i in [(extra['key'], extra['value'], i) for i, extra in enumerate(extras)]:
if k == 'responsible-party':
responsible_party = json.loads(v)[0]
package_dict['maintainer'] = responsible_party.get('name', '')
package_dict['maintainer_email'] = responsible_party.get('email', '')
if k == 'keywords':
keywords = [keywords.get('keyword', []) for keywords in json.loads(v)]
parsed_keywords = [munge_tag(item) for sublist in keywords for item in sublist]
package_dict['keywords'] = {
'fi': parsed_keywords
}
# Remove keywords from extras as same key cannot be in schema and in extras
extras.pop(i)
if k == 'lineage':
package_dict['notes_translated']['fi'] += '\n\n' + v
if k == 'use_constraints':
package_dict['copyright_notice_translated'] = {
'fi': json.loads(v)[0]
}
if k == 'metadata-date':
metadata_date_isoformat = "%s.000000" % date_str_to_datetime(v).isoformat().split('+', 2)[0]
package_dict['date_released'] = metadata_date_isoformat
if k == 'temporal-extent-begin':
try:
package_dict['valid_from'] = date_str_to_datetime(v)
except ValueError:
log.info("Invalid date for valid_from, ignoring..")
pass
if k == 'temporal-extent-end':
try:
package_dict['valid_until'] = date_str_to_datetime(v)
except ValueError:
log.info("Invalid date for valid_until, ignoring..")
pass
if k == 'topic-category':
topic_categories = json.loads(v)
categories = [category for topic_category in topic_categories
for category, iso_topic_categories in six.iteritems(_category_mapping)
if topic_category in iso_topic_categories]
package_dict['categories'] = categories
return package_dict
def gather_stage(self, harvest_job):
log.debug('In SYKEHarvester gather_stage (%s)',
harvest_job.source.url)
toolkit.requires_ckan_version(min_version='2.0')
get_all_packages = True
self._set_config(harvest_job.source.config)
# Get source URL
remote_ckan_base_url = harvest_job.source.url.rstrip('/')
# Filter in/out datasets from particular organizations
fq_terms = []
org_filter_include = self.config.get('organizations_filter_include', [])
org_filter_exclude = self.config.get('organizations_filter_exclude', [])
if org_filter_include:
fq_terms.append(' OR '.join(
'organization:%s' % org_name for org_name in org_filter_include))
elif org_filter_exclude:
fq_terms.extend(
'-organization:%s' % org_name for org_name in org_filter_exclude)
groups_filter_include = self.config.get('groups_filter_include', [])
groups_filter_exclude = self.config.get('groups_filter_exclude', [])
if groups_filter_include:
fq_terms.append(' OR '.join(
'groups:%s' % group_name for group_name in groups_filter_include))
elif groups_filter_exclude:
fq_terms.extend(
'-groups:%s' % group_name for group_name in groups_filter_exclude)
# Ideally we can request from the remote CKAN only those datasets
# modified since the last completely successful harvest.
last_error_free_job = self.last_error_free_job(harvest_job)
log.debug('Last error-free job: %r', last_error_free_job)
if (last_error_free_job and
not self.config.get('force_all', False)):
get_all_packages = False
# Request only the datasets modified since
last_time = last_error_free_job.gather_started
# Note: SOLR works in UTC, and gather_started is also UTC, so
# this should work as long as local and remote clocks are
# relatively accurate. Going back a little earlier, just in case.
get_changes_since = \
(last_time - datetime.timedelta(hours=1)).isoformat()
log.info('Searching for datasets modified since: %s UTC',
get_changes_since)
fq_since_last_time = 'metadata_modified:[{since}Z TO *]' \
.format(since=get_changes_since)
try:
pkg_dicts = self._search_for_datasets(
remote_ckan_base_url,
fq_terms + [fq_since_last_time])
except SearchError as e:
log.info('Searching for datasets changed since last time '
'gave an error: %s', e)
get_all_packages = True
if not get_all_packages and not pkg_dicts:
log.info('No datasets have been updated on the remote '
'CKAN instance since the last harvest job %s',
last_time)
return []
# Fall-back option - request all the datasets from the remote CKAN
if get_all_packages:
# Request all remote packages
try:
pkg_dicts = self._search_for_datasets(remote_ckan_base_url,
fq_terms)
except SearchError as e:
log.info('Searching for all datasets gave an error: %s', e)
self._save_gather_error(
'Unable to search remote CKAN for datasets:%s url:%s'
'terms:%s' % (e, remote_ckan_base_url, fq_terms),
harvest_job)
return None
if not pkg_dicts:
self._save_gather_error(
'No datasets found at CKAN: %s' % remote_ckan_base_url,
harvest_job)
return []
# Create harvest objects for each dataset
try:
package_ids = set()
object_ids = []
for pkg_dict in pkg_dicts:
if pkg_dict['id'] in package_ids:
log.info('Discarding duplicate dataset %s - probably due '
'to datasets being changed at the same time as '
'when the harvester was paging through',
pkg_dict['id'])
continue
if 'CC BY 4.0' not in pkg_dict.get('notes', ""):
log.info("Not under CC BY 4.0 license, skipping..")
continue
package_ids.add(pkg_dict['id'])
log.debug('Creating HarvestObject for %s %s',
pkg_dict['name'], pkg_dict['id'])
obj = HarvestObject(guid=pkg_dict['id'],
job=harvest_job,
content=json.dumps(pkg_dict))
obj.save()
object_ids.append(obj.id)
return object_ids
except Exception as e:
self._save_gather_error('%r' % e.message, harvest_job)
class ContentFetchError(Exception):
pass
class ContentNotFoundError(ContentFetchError):
pass
class RemoteResourceError(Exception):
pass
class SearchError(Exception):
pass
|
MochalovaAn/llvm | llvm/tools/sycl-post-link/SpecConstants.h | //===----- SpecConstants.h - SYCL Specialization Constants Pass -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// A transformation pass which converts symbolic id-based specialization
// constant intrinsics to integer id-based ones to later map to SPIRV spec
// constant operations. The spec constant IDs are symbolic before linkage to
// make separate compilation possible. After linkage all spec constants are
// available to the pass, and it can assign consistent integer IDs.
//===----------------------------------------------------------------------===//
#pragma once
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include <map>
#include <vector>
namespace llvm {
class StringRef;
}
// Represents either an element of a composite specialization constant or a
// single scalar specialization constant - at SYCL RT level composite
// specialization constants are being represented as a single byte-array, while
// at SPIR-V level they are represented by a number of scalar specialization
// constants.
// The same representation is re-used for scalar specialization constants in
// order to unify they processing with composite ones.
struct SpecConstantDescriptor {
// Encodes ID of a scalar specialization constants which is a leaf of some
// composite specialization constant.
unsigned ID;
// Encodes offset from the beginning of composite, where scalar resides, i.e.
// location of the scalar value within a byte-array containing the whole
// composite specialization constant. If descriptor is used to represent a
// whole scalar specialization constant instead of an element of a composite,
// this field should be contain zero.
unsigned Offset;
// Encodes size of scalar specialization constant.
unsigned Size;
};
using SpecIDMapTy =
std::map<llvm::StringRef, std::vector<SpecConstantDescriptor>>;
class SpecConstantsPass : public llvm::PassInfoMixin<SpecConstantsPass> {
public:
// SetValAtRT parameter controls spec constant lowering mode:
// - if true, it is lowered to SPIRV intrinsic which retrieves constant value
// - if false, it is replaced with C++ default (used for AOT compilers)
SpecConstantsPass(bool SetValAtRT = true) : SetValAtRT(SetValAtRT) {}
llvm::PreservedAnalyses run(llvm::Module &M,
llvm::ModuleAnalysisManager &MAM);
// Searches given module for occurrences of specialization constant-specific
// metadata and builds "spec constant name" -> vector<"spec constant int ID">
// map
static bool collectSpecConstantMetadata(llvm::Module &M, SpecIDMapTy &IDMap);
private:
bool SetValAtRT;
};
|
M155K4R4/Tensorflow | tensorflow/contrib/periodic_resample/kernels/periodic_resample_op.h | // =============================================================================
// Copyright 2016 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#ifndef TENSORFLOW_KERNELS_PERIODICRESAMPLE_OP_H_
#define TENSORFLOW_KERNELS_PERIODICRESAMPLE_OP_H_
#include <cmath>
#include <type_traits>
#include <vector>
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
namespace {
template <class IndexVecT, class IndexT>
IndexT compute_input_index(
IndexVecT* target_dimensions, const IndexT& output_index,
const IndexVecT& original_dimensions, const int& adjustable_dimension,
const std::vector<tensorflow::int64>& dimension_ceiling,
const std::vector<tensorflow::int64>& cumulative_dimensions, IndexT* result,
std::vector<IndexT>* output_indices, const int& rank) {
*result = 0;
output_indices->clear();
// un-rasterize the output index
auto last_reduced_i = output_index;
for (auto r = rank - 1; r >= 0; --r) {
(*output_indices)[r] = last_reduced_i % (*target_dimensions)[r];
last_reduced_i =
(last_reduced_i - (*output_indices)[r]) / (*target_dimensions)[r];
}
// rasterize the input index
IndexT last_index_factor = 1;
for (auto r = rank - 1; r >= 0; --r) {
IndexT index = 0;
if (r != adjustable_dimension)
index = (*output_indices)[r] / dimension_ceiling[r];
else {
for (int qi = 0; qi < rank; ++qi) {
if (qi == adjustable_dimension) continue;
index += cumulative_dimensions[qi] *
((*output_indices)[qi] % dimension_ceiling[qi]);
}
index *= (*target_dimensions)[adjustable_dimension];
index += (*output_indices)[r];
}
*result += last_index_factor * index;
last_index_factor *= original_dimensions[r];
}
return *result;
}
template <class InputDataT,
class IndexVecT> // both types are needed here b/c IndexVecT and
// InputDataT are not related
void
fill_periodic_tensor(
tensorflow::OpKernelContext* context,
const IndexVecT& desired_shape,
const tensorflow::Tensor& input_tensor) {
// input is a strided array (last index is fastest, C-ordered)
auto input = input_tensor.flat<InputDataT>();
const int rank = input_tensor.dims();
// original and target dimensions
std::vector<tensorflow::int64> original_dimensions(rank),
target_dimensions(rank);
tensorflow::int64 total_size(input_tensor.NumElements()), new_sliced_size(1);
// factors by which original_dimensions increases/decreases w.r.t.
// target_dimensions
std::vector<tensorflow::int64> dimension_ceiling(rank),
cumulative_dimensions(rank);
// index of adjustable dimension
int adjustable_dimension;
tensorflow::TensorShape output_shape;
// requires that the rank of the input tensor and length of the desired shape
// are equal
OP_REQUIRES(context, rank == desired_shape.size(),
tensorflow::errors::InvalidArgument(
"periodic_resample expects the rank of the input tensor, ",
rank, ", to be the same as the length of the desired shape, ",
desired_shape.size(), "."));
bool found = false;
const auto& input_tensor_shape = input_tensor.shape();
for (int i = 0; i < rank; ++i) {
// if (desired_shape(i) < 1) {
if (desired_shape[i] < 1) {
// only one index can be adjustable
OP_REQUIRES(context, !found,
tensorflow::errors::InvalidArgument(
"periodic_resample expects only "
"one index to be marked as adjustable."));
adjustable_dimension = i;
found = true;
} else {
OP_REQUIRES(
context, desired_shape[i] >= input_tensor_shape.dim_size(i),
tensorflow::errors::InvalidArgument(
"periodic_resample expects the size of non-adjustable "
"dimensions be at least as large as size of input tensor."
" Dimension ",
i, " input tensor has size ", input_tensor_shape.dim_size(i),
", desired shape has size ", desired_shape[i], "."));
// target_dimensions[i] = desired_shape(i);
target_dimensions[i] = desired_shape[i];
new_sliced_size *= target_dimensions[i];
}
}
// at least one index needs to be adjustable
OP_REQUIRES(context, found,
tensorflow::errors::InvalidArgument(
"periodic_resample expects at least "
"one index to be marked as adjustable."));
int count = 0;
for (const auto dim_info : input_tensor.shape()) {
original_dimensions[count] = dim_info.size;
++count;
}
target_dimensions[adjustable_dimension] = total_size / new_sliced_size;
count = 0;
for (int i = 0; i < input_tensor.shape().dims(); ++i) {
dimension_ceiling[count] = tensorflow::int64(std::ceil(
float(target_dimensions[count]) / float(original_dimensions[count])));
if (count == 0)
cumulative_dimensions[count] = 1;
else
cumulative_dimensions[count] =
cumulative_dimensions[count - 1] * dimension_ceiling[count - 1];
++count;
}
// ensure that the new dimension is greater than zero
OP_REQUIRES(context, target_dimensions[adjustable_dimension] > 0,
tensorflow::errors::InvalidArgument(
"periodic_resample found that the "
"adjustable dimension, ",
adjustable_dimension, ", isn't greater than zero, ",
target_dimensions[adjustable_dimension], "."));
for (int i = 0; i < rank; ++i) {
output_shape.AddDim(target_dimensions[i]);
}
const auto new_size =
new_sliced_size * target_dimensions[adjustable_dimension];
// Create an output tensor and attach it to the current context
tensorflow::Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, output_shape, &output_tensor));
auto output = output_tensor->flat<InputDataT>();
// memory is allocated for these variables outside the inner loop for
// efficiency (although, I could create a separate class scope for
// this purpose instead)
tensorflow::int64 result = 0;
std::vector<tensorflow::int64> output_indices(target_dimensions.size());
// Fill output tensor with periodically resampled input tensor values
for (tensorflow::int64 output_index = 0; output_index < new_size;
++output_index) {
output(output_index) = input(compute_input_index(
&target_dimensions, output_index, original_dimensions,
adjustable_dimension, dimension_ceiling, cumulative_dimensions, &result,
&output_indices, rank));
}
}
void create_output_tensor(
tensorflow::OpKernelContext* context,
const tensorflow::Tensor& input_tensor,
const tensorflow::DataType& input_tensor_type,
const tensorflow::PartialTensorShape& desired_shape_tensor) {
auto desired_shape = desired_shape_tensor.dim_sizes();
// obligatory type switch
switch (input_tensor_type) {
case tensorflow::DataTypeToEnum<float>::value:
fill_periodic_tensor<float>(context, desired_shape, input_tensor);
break;
case tensorflow::DataTypeToEnum<double>::value:
fill_periodic_tensor<double>(context, desired_shape, input_tensor);
break;
case tensorflow::DataTypeToEnum<tensorflow::int32>::value:
fill_periodic_tensor<tensorflow::int32>(context, desired_shape,
input_tensor);
break;
case tensorflow::DataTypeToEnum<tensorflow::int64>::value:
fill_periodic_tensor<tensorflow::int64>(context, desired_shape,
input_tensor);
break;
default:;
}
}
} // namespace
class PeriodicResampleOp : public tensorflow::OpKernel {
public:
explicit PeriodicResampleOp(tensorflow::OpKernelConstruction* context)
: tensorflow::OpKernel(context) {
// Get the desired shape
OP_REQUIRES_OK(context, context->GetAttr("shape", &desired_shape));
}
void Compute(tensorflow::OpKernelContext* context) override {
// Grab the input tensor
const tensorflow::Tensor& input_tensor = context->input(0);
const tensorflow::DataType input_tensor_type = context->input_dtype(0);
create_output_tensor(context, input_tensor, input_tensor_type,
desired_shape);
}
private:
tensorflow::PartialTensorShape desired_shape;
};
#endif // TENSORFLOW_KERNELS_PERIODICRESAMPLE_OP_H_
|
cbograt-company/test | proxies/com/microsoft/bingads/v11/campaignmanagement/CampaignCriterionType.java | <reponame>cbograt-company/test
package com.microsoft.bingads.v11.campaignmanagement;
/**
* Enum class for CampaignCriterionType.
*/
public enum CampaignCriterionType {
PRODUCT_SCOPE("ProductScope"),
WEBPAGE("Webpage"),
TARGETS("Targets"),
AGE("Age"),
DAY_TIME("DayTime"),
GENDER("Gender"),
LOCATION("Location"),
RADIUS("Radius"),
DEVICE("Device"),
LOCATION_INTENT("LocationIntent");
private final String value;
CampaignCriterionType(String v) {
value = v;
}
public String value() {
return value;
}
public static CampaignCriterionType fromValue(String v) {
for (CampaignCriterionType c : CampaignCriterionType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
} |
kc980602/IVE-FYP-AI-Trvel-Planner | Triple/app/src/main/java/com/triple/triple/Helper/CheckLogin.java | package com.triple.triple.Helper;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.triple.triple.Presenter.Account.LoginActivity;
/**
* Created by Kevin on 2018/2/6.
*/
public class CheckLogin {
public static Boolean directLogin(Context context) {
if (!UserDataHelper.checkTokenExist(context)) {
Log.d("sss", "sss`");
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
return true;
}
return false;
}
}
|
robertb-r/fiji | src-plugins/pal-optimization/src/main/java/pal/math/MultivariateFunction.java | // MultivariateFunction.java
//
// (c) 1999-2001 PAL Development Core Team
//
// This package may be distributed under the
// terms of the Lesser GNU General Public License (LGPL)
package pal.math;
/**
* interface for a function of several variables
*
* @author <NAME>
*/
public interface MultivariateFunction
{
/**
* compute function value
*
* @param argument function argument (vector)
*
* @return function value
*/
double evaluate(double[] argument);
/**
* get number of arguments
*
* @return number of arguments
*/
int getNumArguments();
/**
* get lower bound of argument n
*
* @param n argument number
*
* @return lower bound
*/
double getLowerBound(int n);
/**
* get upper bound of argument n
*
* @param n argument number
*
* @return upper bound
*/
double getUpperBound(int n);
}
|
XiuYuLi/deepcore_source_code | deepcore_device/deepcore_device/fft/sfft/sfft16x16_r2c_perm2d.h | __global__ void dk_sfft16x16_r2c_perm2d( float2* d_c,
const float* __restrict__ d_r, const float* __restrict__ d_RF,
unsigned int nx, unsigned int ny, unsigned int ldc, unsigned int ldr, int n_cells )
{
const int brev[]={0,4,2,6,1,5,3,7};
__shared__ float smem[16*145];
__shared__ float2 s_RF[8];
float2 c[9];
unsigned int tid=threadIdx.x;
unsigned int bid=blockIdx.x;
unsigned int x=tid&15;
unsigned int y=tid>>4;
unsigned int u=x&1;
unsigned int v=x>>1;
unsigned int icell=(bid<<4)+y;
float* spx=&smem[y*144+x];
float* spy=&smem[y*144+v*18+u];
d_c+=y*ldc+(bid<<4)+x;
d_r+=(icell<<8)+x;
if(y==0){ ((float*)s_RF)[x]=d_RF[x]; }
if(icell<n_cells){
#pragma unroll
for( int i=0; i<8; ++i ){
c[i].x=d_r[(i*2+0)*16];
c[i].y=d_r[(i*2+1)*16];
}
} __syncthreads();
s_vfft16( c, spx, spy, s_RF, brev );
s_hfft16( c, &smem[y*144+v*18+u*8], spx, s_RF, brev, x, u );
s_store9( d_c, &smem[y*145+x], &smem[x*145+y], c, ldc<<4 );
}
__global__ void dk_sfft16x16_r2c_perm2d_ext( float2* d_c,
const float* __restrict__ d_r, const float* __restrict__ d_RF,
unsigned int nx, unsigned int ny, unsigned int ldc, unsigned int ldr, int n_cells )
{
const int brev[]={0,4,2,6,1,5,3,7};
__shared__ float smem[16*145];
__shared__ float2 s_RF[8];
float2 c[9];
unsigned int tid=threadIdx.x;
unsigned int bid=blockIdx.x;
unsigned int y=tid>>4;
unsigned int x=tid&15;
unsigned int u=x&1;
unsigned int v=x>>1;
unsigned int icell=(bid<<4)+y;
float* spx=&smem[y*144+x];
float* spy=&smem[y*144+v*18+u];
d_c+=y*ldc+(bid<<4)+x;
d_r+=icell*ldr+x;
CLEAR8C(c)
if(y==0){ ((float*)s_RF)[x]=d_RF[x]; }
if((icell<n_cells)&(x<nx)){
#pragma unroll
for( int i=0; i<8; ++i ){
if((2*i+0)<ny){ c[i].x=*d_r; } d_r+=nx;
if((2*i+1)<ny){ c[i].y=*d_r; } d_r+=nx;
}
} __syncthreads();
s_vfft16( c, spx, spy, s_RF, brev );
s_hfft16( c, &smem[y*144+v*18+u*8], spx, s_RF, brev, x, u );
s_store9( d_c, &smem[y*145+x], &smem[x*145+y], c, ldc<<4 );
}
__global__ void dk_sfft16x16_r2c_perm2d_pad( float2* d_c,
const float* __restrict__ d_r, const float* __restrict__ d_RF,
unsigned int nx, unsigned int ny, unsigned int ldc, unsigned int ldr, int n_cells,
int pad_x, int pad_y )
{
const int brev[]={0,4,2,6,1,5,3,7};
__shared__ float smem[16*145];
__shared__ float2 s_RF[8];
float2 c[9];
unsigned int tid=threadIdx.x;
unsigned int bid=blockIdx.x;
unsigned int x=tid&15;
unsigned int y=tid>>4;
unsigned int u=x&1;
unsigned int v=x>>1;
unsigned int icell=(bid<<4)+y;
int ox=(int)x-pad_x;
int oy=-pad_y;
float* spx=&smem[y*144+x];
float* spy=&smem[y*144+v*18+u];
d_c+=y*ldc+(bid<<4)+x;
d_r+=icell*ldr+ox;
CLEAR8C(c)
if(y==0){ ((float*)s_RF)[x]=d_RF[x]; }
if((icell<n_cells)&(ox>=0)&(ox<nx)){
#pragma unroll
for( int i=0; i<8; ++i ){
if((oy>=0)&(oy<ny)){ c[i].x=*d_r; d_r+=nx; } ++oy;
if((oy>=0)&(oy<ny)){ c[i].y=*d_r; d_r+=nx; } ++oy;
}
} __syncthreads();
s_vfft16( c, spx, spy, s_RF, brev );
s_hfft16( c, &smem[y*144+v*18+u*8], spx, s_RF, brev, x, u );
s_store9( d_c, &smem[y*145+x], &smem[x*145+y], c, ldc<<4 );
}
__global__ void dk_sfft16x16_r2c_perm2d_flip( float2* d_c,
const float* __restrict__ d_r, const float* __restrict__ d_RF,
unsigned int nx, unsigned int ny, unsigned int ldc, unsigned int ldr, int n_cells )
{
const int brev[]={0,4,2,6,1,5,3,7};
__shared__ float smem[16*145];
__shared__ float2 s_RF[8];
float2 c[9];
unsigned int tid=threadIdx.x;
unsigned int bid=blockIdx.x;
unsigned int x=tid&15;
unsigned int y=tid>>4;
unsigned int u=x&1;
unsigned int v=x>>1;
unsigned int icell=(bid<<4)+y;
float* spx=&smem[y*144+x];
float* spy=&smem[y*144+v*18+u];
d_c+=y*ldc+(bid<<4)+x;
d_r+=icell*ldr+nx*ny-x-1;
CLEAR8C(c)
if(y==0){ ((float*)s_RF)[x]=d_RF[x]; }
if((icell<n_cells)&(x<nx)){
c[0].x=*d_r;
c[0].y=*(d_r-nx);
#pragma unroll
for( int i=1; i<8; ++i ){
if((2*i+0)<ny){ c[i].x=*(d_r-=nx); }
if((2*i+1)<ny){ c[i].y=*(d_r-=nx); }
}
} __syncthreads();
s_vfft16( c, spx, spy, s_RF, brev );
s_hfft16( c, &smem[y*144+v*18+u*8], spx, s_RF, brev, x, u );
s_store9( d_c, &smem[y*145+x], &smem[x*145+y], c, ldc<<4 );
} |
siu91/myboot | myboot-demo-ganxu/ganxu-core/src/main/java/org/siu/myboot/server/entity/po/QProduct.java | package org.siu.myboot.server.entity.po;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import org.siu.myboot.core.data.jpa.querydsljpa.QBuiler;
import java.util.Objects;
/**
* QUserInfo is a Querydsl query type for UserInfo
*/
@Generated("com.querydsl.codegen.EntitySerializer")
public class QProduct extends EntityPathBase<Product> implements QBuiler {
private static final long serialVersionUID = 1L;
public static final QProduct product = new QProduct("product");
public final NumberPath<Long> id = createNumber("id", Long.class);
public final NumberPath<Long> productCode = createNumber("productCode", Long.class);
public final StringPath productName = createString("productName");
public final StringPath barCode = createString("barCode");
public final NumberPath<Long> brandId = createNumber("brandId", Long.class);
public final NumberPath<Long> category1Id = createNumber("category1Id", Long.class);
public final NumberPath<Long> category2Id = createNumber("category2Id", Long.class);
public final NumberPath<Long> category3Id = createNumber("category3Id", Long.class);
public final NumberPath<Long> supplierId = createNumber("supplierId", Long.class);
public final NumberPath<Long> price = createNumber("price", Long.class);
public final NumberPath<Long> originPrice = createNumber("originPrice", Long.class);
public final NumberPath<Long> averageCost = createNumber("averageCost", Long.class);
public final NumberPath<Integer> publishStatus = createNumber("publishStatus", Integer.class);
public final NumberPath<Integer> auditStatus = createNumber("auditStatus", Integer.class);
public final NumberPath<Double> weight = createNumber("weight", Double.class);
public final NumberPath<Double> length = createNumber("length", Double.class);
public final NumberPath<Double> height = createNumber("height", Double.class);
public final NumberPath<Double> width = createNumber("width", Double.class);
public final NumberPath<Integer> unit = createNumber("unit", Integer.class);
public final NumberPath<Integer> color = createNumber("color", Integer.class);
public final StringPath productionDate = createString("productionDate");
public final StringPath expirationDate = createString("expirationDate");
public final StringPath desc = createString("desc");
public final DateTimePath<java.util.Date> createTime = createDateTime("createTime", java.util.Date.class);
public final DateTimePath<java.util.Date> upateTime = createDateTime("upateTime", java.util.Date.class);
/**
* get path by property
*
* @param property
* @return
*/
private Path path(String property) {
if (Objects.isNull(property)) {
return null;
}
switch (property) {
case "id":
return id;
case "productCode":
return productCode;
case "productName":
return productName;
case "barCode":
return barCode;
case "brandId":
return brandId;
case "category1Id":
return category1Id;
case "category2Id":
return category2Id;
case "category3Id":
return category3Id;
case "supplierId":
return supplierId;
case "price":
return price;
case "originPrice":
return originPrice;
case "averageCost":
return averageCost;
case "publishStatus":
return publishStatus;
case "auditStatus":
return auditStatus;
case "weight":
return weight;
case "length":
return length;
case "height":
return height;
case "width":
return width;
case "unit":
return unit;
case "color":
return color;
case "productionDate":
return productionDate;
case "expirationDate":
return expirationDate;
case "desc":
return desc;
case "createTime":
return createTime;
case "upateTime":
return upateTime;
default:
return null;
}
}
/**
* get property
*
* @param property
* @return
*/
@Override
public ComparableExpressionBase order(String property) {
return (ComparableExpressionBase) this.path(property);
}
/**
* get property
*
* @param property
* @return
*/
@Override
public SimpleExpression condition(String property) {
return (SimpleExpression) this.path(property);
}
public QProduct(String variable) {
super(Product.class, forVariable(variable));
}
public QProduct(Path<? extends Product> path) {
super(path.getType(), path.getMetadata());
}
public QProduct(PathMetadata metadata) {
super(Product.class, metadata);
}
}
|
jalizadeh/ToDocial-Social-Todo-Manager | src/main/java/com/jalizadeh/springboot/web/controller/admin/model/SettingsGeneralConfig.java | package com.jalizadeh.springboot.web.controller.admin.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* This object holds the latest settings, from startup and while run time
* If other controllers need to get the latest settings, they can access
* this object.
*/
@Configuration
@PropertySource("classpath:settings-default.properties")
public class SettingsGeneralConfig {
@Value("${site.name:ToDocial}")
private String siteName;
@Value("${footer.copyright:© 2020 ToDocial}")
private String footerCopyright;
@Value("${site.description:}")
private String siteDescription;
@Value("${anyone.can.register:true}")
private boolean anyoneCanRegister;
@Value("${default.role:ROLE_USER}")
private String defaultRole;
@Value("${server.local.time:+0 UTC}")
private String serverLocalTime;
@Value("${date.structure:long}")
private String dateStructure;
@Value("${time.structure:short}")
private String timeStructure;
@Value("${language:en_US}")
private String language;
public SettingsGeneralConfig() {
super();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public String getSiteName() {
return siteName;
}
public String getSiteDescription() {
return siteDescription;
}
public boolean isAnyoneCanRegister() {
return anyoneCanRegister;
}
public String getDefaultRole() {
return defaultRole;
}
public String getServerLocalTime() {
return serverLocalTime;
}
public String getDateStructure() {
return dateStructure;
}
public String getTimeStructure() {
return timeStructure;
}
public String getLanguage() {
return language;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public void setSiteDescription(String siteDescription) {
this.siteDescription = siteDescription;
}
public void setAnyoneCanRegister(boolean anyoneCanRegister) {
this.anyoneCanRegister = anyoneCanRegister;
}
public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole;
}
public void setServerLocalTime(String serverLocalTime) {
this.serverLocalTime = serverLocalTime;
}
public void setDateStructure(String dateStructure) {
this.dateStructure = dateStructure;
}
public void setTimeStructure(String timeStructure) {
this.timeStructure = timeStructure;
}
public void setLanguage(String language) {
this.language = language;
}
public String getFooterCopyright() {
return footerCopyright;
}
public void setFooterCopyright(String footerCopyright) {
this.footerCopyright = footerCopyright;
}
}
|
lzbgithubcode/ZBCategories | ZBCategories/Classes/UIKit/UIView/UIView+Extension.h | <reponame>lzbgithubcode/ZBCategories
//
// UIView+Extension.h
// ZBCategories
//
// Created by lzb on 2018/8/14.
// Copyright © 2018年 lzb. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (Extension)
/**
清楚子视图
*/
-(void)removeAllSubViews;
/**
判断View是否在屏幕上
*/
- (BOOL)isDisplayedInScreen;
/**
子视图失去第一响应
*/
-(void)resAllInputViews;
/**
当前视图第一响应者
@return view
*/
-(UIView*)findFirstResponder ;
/**
找到视图所在的第一控制器
@return vc
*/
-(UIViewController *)findViewController;
/**
根据需求调节圆弧度
@param Radius 弧度
@param borderWidth 边宽
@param color 颜色
*/
- (void)viewRadiusWithRadius:(int )Radius borderWidth:(int )borderWidth color:(UIColor *)color;
@end
|
Graalex/personal-cabinet-azovgaz | src/components/Popup/index.js | <gh_stars>0
import Popup from './Popup';
export {Popup}; |
testim407/nexl-js | tests/storage-backup-tests/storage-backup-tests.js | const os = require('os');
const fs = require('fs');
const fsx = require('fs-extra');
const path = require('path');
const unzipper = require('unzipper');
const recursive = require("recursive-readdir");
const testAPI = require('../test-api');
const confConsts = require('../../backend/common/conf-constants');
const confMgmt = require('../../backend/api/conf-mgmt');
const storageUtil = require('../../backend/api/storage-utils');
const MAX_BACKUPS = 5;
const FILE_CNT = 8;
const storageBackupDir = path.join(os.tmpdir(), 'nexl-stroage-backup-test-' + Math.random());
// --------------------------------------------------------------------------------
function init(predefinedNexlJSFIlesDir, tmpNexlJSFilesDir) {
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.STORAGE_DIR] = predefinedNexlJSFIlesDir;
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.AUTOMATIC_BACKUP_DEST_DIR] = storageBackupDir;
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.AUTOMATIC_BACKUP_MAX_BACKUPS] = MAX_BACKUPS;
return Promise.resolve();
}
function zipUnZipTestInner() {
const files = fs.readdirSync(storageBackupDir);
const zipFile = path.join(storageBackupDir, files[0]); // must only 1 file
// unzipping
return fs.createReadStream(zipFile)
.pipe(unzipper.Extract({path: storageBackupDir}))
.promise()
.then(_ => recursive(storageBackupDir))
.then((files, err) => {
if (err) {
return Promise.reject(err);
}
if (files.length !== FILE_CNT + 1) { // 1 for Zip itself
return Promise.reject("Unzipped files count doesn't match");
}
fsx.removeSync(storageBackupDir);
return Promise.resolve();
});
}
function zipUnZipTest() {
fs.mkdirSync(storageBackupDir);
return storageUtil.backupStorage().then(zipUnZipTestInner);
}
function delay() {
return new Promise((resolve, reject) => {
console.log('Sleeping...');
setTimeout(_ => {
resolve();
}, 1000);
});
}
function maxBackupsTest() {
fs.mkdirSync(storageBackupDir);
return Promise.resolve()
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(storageUtil.backupStorage)
.then(delay)
.then(_ => recursive(storageBackupDir))
.then((files, err) => {
fsx.removeSync(storageBackupDir);
if (err) {
return Promise.reject(err);
}
if (files.length !== MAX_BACKUPS) {
return Promise.reject(`Backups count must be [${MAX_BACKUPS}], but got a [${files.length}] count`);
}
return Promise.resolve();
})
}
function nonExistingDirsTest() {
const randomDir = `c:\\xxx-${Math.random()}-${Math.random()}`;
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.AUTOMATIC_BACKUP_DEST_DIR] = randomDir;
let result;
return storageUtil.backupStorage()
.then(() => {
result = true;
return Promise.resolve();
})
.catch((err) => {
result = false;
return Promise.resolve();
})
.then(() => {
return result ? Promise.reject("ZIP destination dir doesn't exist, but got a positive test result") : Promise.resolve();
})
.then(() => {
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.AUTOMATIC_BACKUP_DEST_DIR] = storageBackupDir;
confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.STORAGE_DIR] = randomDir;
return storageUtil.backupStorage();
})
.then(() => {
result = true;
return Promise.resolve();
})
.catch((err) => {
result = false;
return Promise.resolve();
})
.then(() => {
return result ? Promise.reject("nexl home dir doesn't exist, but got a positive test result") : Promise.resolve();
});
}
function run() {
return Promise.resolve()
.then(zipUnZipTest)
.then(maxBackupsTest)
.then(nonExistingDirsTest);
}
function done() {
return Promise.resolve();
}
testAPI.startNexlApp(init, run, done); |
ShoutToMe/stm-sdk-android | shout-to-me-sdk/src/main/java/me/shoutto/sdk/internal/usecases/DeleteTopicPreference.java | package me.shoutto.sdk.internal.usecases;
import android.util.Log;
import me.shoutto.sdk.StmBaseEntity;
import me.shoutto.sdk.StmCallback;
import me.shoutto.sdk.StmError;
import me.shoutto.sdk.TopicPreference;
import me.shoutto.sdk.internal.http.HttpMethod;
import me.shoutto.sdk.internal.http.StmRequestProcessor;
/**
* Deletes a topic preference from the user's record
*/
public class DeleteTopicPreference extends BaseUseCase<StmBaseEntity, Void> {
private static final String TAG = DeleteTopicPreference.class.getSimpleName();
public DeleteTopicPreference(StmRequestProcessor<StmBaseEntity> stmRequestProcessor) {
super(stmRequestProcessor);
}
public void delete(String topic, StmCallback<Void> callback) {
if (topic == null || "".equals(topic)) {
String validationErrorMessage = "topic is required for creating a topic preference";
if (callback != null) {
StmError error = new StmError(validationErrorMessage, false, StmError.SEVERITY_MINOR);
callback.onError(error);
} else {
Log.w(TAG, validationErrorMessage);
}
stmRequestProcessor.deleteObserver(this);
return;
}
this.callback = callback;
TopicPreference topicPreference = new TopicPreference();
topicPreference.setTopic(topic);
stmRequestProcessor.processRequest(HttpMethod.DELETE, topicPreference);
}
}
|
venovako/VecKog | src/mem.h | <filename>src/mem.h
#ifndef MEM_H
#define MEM_H
#include "common.h"
typedef struct {
double *A11, *A21, *A12, *A22;
double *U11, *U21, *U12, *U22;
double *V11, *V21, *V12, *V22;
} matrices;
typedef struct {
double *S1, *S2;
double *s;
} vectors;
typedef struct {
matrices r;
vectors v;
} Dmem;
typedef struct {
matrices r, i;
vectors v;
} Zmem;
typedef struct {
wide *K2, *RE, *OU, *OV;
} Tout;
extern double *Valloc(const size_t n);
extern double *Vfree(double *const d);
extern Dmem *Dalloc(const size_t n);
extern Dmem *Dfree(Dmem *const d);
extern Zmem *Zalloc(const size_t n);
extern Zmem *Zfree(Zmem *const z);
extern Tout *Talloc(const size_t n);
extern Tout *Tfree(Tout *const t);
#endif /* !MEM_H */
|
prospero78/goTk | atk/lib/tk/basewidget_test.go | <reponame>prospero78/goTk<gh_stars>0
// Copyright 2018 visualfc. All rights reserved.
package tk
import (
"strings"
"testing"
)
func init() {
registerTest("TestWidgetId", testWidgetId)
registerTest("TestWidgetParent", testWidgetParent)
}
type TestWidget struct {
BaseWidget
}
func (w *TestWidget) Type() WidgetType {
return WidgetTypeLast + 1
}
func (w *TestWidget) Attach(id string) error {
w.id = id
w.info = &WidgetInfo{WidgetTypeCanvas, "TestWidget", false, nil}
RegisterWidget(w)
return nil
}
func NewTestWidget(parent Widget, id string) *TestWidget {
w := &TestWidget{}
w.Attach(makeNamedWidgetId(parent, id))
return w
}
func testWidgetId(t *testing.T) {
var id string
parent := NewTestWidget(nil, "base")
id = makeNamedWidgetId(nil, "atk_wtest")
if !strings.HasPrefix(id, ".atk_wtest") {
t.Fatal(id)
}
id = makeNamedWidgetId(parent, "atk_wchild")
if !strings.HasPrefix(id, ".base1.atk_wchild1") {
t.Fatal(id)
}
id = makeNamedWidgetId(nil, "idtest")
if id != ".idtest1" {
t.Fatal(id)
}
id = makeNamedWidgetId(parent, "idtest")
if id != ".base1.idtest1" {
t.Fatal(id)
}
id = makeNamedWidgetId(parent, "idtest")
if id != ".base1.idtest2" {
t.Fatal(id)
}
DestroyWidget(parent)
}
func findOfList(w Widget, list []Widget) bool {
for _, v := range list {
if v == w {
return true
}
}
return false
}
func testWidgetParent(t *testing.T) {
a1 := NewTestWidget(nil, "a1")
a2 := NewTestWidget(nil, "a2")
defer a1.Destroy()
defer a2.Destroy()
a1_b1 := NewTestWidget(a1, "b1")
a1_b1_c1 := NewTestWidget(a1_b1, "c1")
a1_b1_c2 := NewTestWidget(a1_b1, "c2")
a1_b1_c3 := NewTestWidget(a1_b1, "c3")
a2_b1 := NewTestWidget(a2, "b1")
a2_b1_c1 := NewTestWidget(a2_b1, "c1")
a2_b1_c2 := NewTestWidget(a2_b1, "c2")
a2_b1_c3 := NewTestWidget(a2_b1, "c3")
if p := ParentOfWidget(a1); p != RootWindow() {
t.Fatal("ParentWidget", p)
}
if p := ParentOfWidget(a1_b1); p != a1 {
t.Fatal("ParentWidget", p)
}
if p := ParentOfWidget(a1_b1_c1); p != a1_b1 {
t.Fatal("ParentWidget", p)
}
list := ChildrenOfWidget(rootWindow)
if !findOfList(a1, list) || !findOfList(a2, list) {
t.Fatal("ChildrenOfWidget", list)
}
list = ChildrenOfWidget(a1_b1)
if len(list) != 3 || !findOfList(a1_b1_c1, list) || !findOfList(a1_b1_c2, list) || !findOfList(a1_b1_c3, list) {
t.Fatal("ChildrenOfWidget", list)
}
DestroyWidget(a1_b1_c3)
list = ChildrenOfWidget(a1_b1)
if len(list) != 2 {
t.Fatal("DestroyWidget", list)
}
DestroyWidget(a1)
list = ChildrenOfWidget(rootWindow)
if findOfList(a1, list) {
t.Fatal("DestroyWidget", list)
}
if IsValidWidget(a1_b1_c1) {
t.Fatal("IsValidWidget", a1_b1_c1)
}
list = a2_b1.Children()
if len(list) != 3 {
t.Fatal("Children", list)
}
a2_b1_c3.Destroy()
if a2_b1_c1.Parent() != a2_b1 || a2_b1_c2.Parent() != a2_b1 {
t.Fatal("Destroy")
}
a2_b1.DestroyChildren()
if a2_b1_c2.IsValid() {
t.Fatal("DestroyChildren", a2_b1_c2)
}
}
|
cmgl/product-model-toolkit | pkg/http/rest/handler_importer.go | <gh_stars>0
// SPDX-FileCopyrightText: 2020 <NAME>-Nürnberg (FAU)
//
// SPDX-License-Identifier: Apache-2.0
package rest
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/labstack/echo/v4"
"github.com/osrgroup/product-model-toolkit/model"
"github.com/osrgroup/product-model-toolkit/pkg/importing"
"github.com/pkg/errors"
)
func importFromScanner(iSrv importing.Service) echo.HandlerFunc {
return func(c echo.Context) error {
scanner := strings.ToLower(c.Param("scanner"))
r := c.Request().Body
if scanner == "scancode" || scanner == "spdx" {
doc, err := iSrv.SPDX(r)
if err != nil {
c.Error(errors.Wrap(err, "Unable to perform SPDX import"))
}
return c.String(
http.StatusOK,
fmt.Sprintf("Successfully parsed SPDX document.\nFound %v packages", len(doc.Packages)),
)
}
var prod *model.Product
var err error
switch scanner {
case "composer":
prod, err = iSrv.ComposerImport(r)
case "file-hasher":
prod, err = iSrv.FileHasherImport(r)
default:
return c.String(
http.StatusOK,
fmt.Sprintf("Received result file with content length %d, but will not import content, because there is no importer for the scanner '%s'", c.Request().ContentLength, scanner))
}
if err != nil {
c.Error(errors.Wrap(err, fmt.Sprintf("Unable to perform import for scanner %s", scanner)))
}
loc := productLocation(c.Path(), prod.ID)
c.Response().Header().Set(echo.HeaderLocation, loc)
return c.String(
http.StatusCreated,
fmt.Sprintf("Successfully parsed content from scanner %s.\n Found %v packages\n", scanner, len(prod.Components)),
)
}
}
func productLocation(path string, id int) string {
i := strings.LastIndex(path, "/")
prodPath := path[:i+1]
return fmt.Sprintf("%s%s", prodPath, strconv.Itoa(id))
}
|
changelime/canvas | canvas2d/excercise/rotate/js/index.js | import $ from "jquery";
import Node from "canvas2d/lib/node";
import { drawAnimation, angToRad, getDistance } from "canvas2d/lib/util";
import { randomHash } from "canvas2d/lib/color";
let $canvas = $("#canvas");
let context = $canvas[0].getContext("2d");
let width = $canvas.width();
let height = $canvas.height();
var center = {
x : width/2,
y : height/2
};
var base = 50;
var s = new Node(width/2, base, 20);
var m = new Node(width/2, base + 60, 25);
var h = new Node(width/2, base + 130, 30);
s.setColor(randomHash());
m.setColor(randomHash());
h.setColor(randomHash());
var drawUntil = function(limt, o, context){
var r = getDistance(center, o.getXY());
o.setX( center.x + Math.cos(limt) * r );
o.setY( center.y + Math.sin(limt) * r );
o.draw(context);
};
drawAnimation(()=>{
context.fillStyle = "rgba(0, 0, 0, 0.05)";
context.fillRect(0, 0, width, height);
var time = ((Date.now() % 86400000) / 1000);
var secon = time % 60;
var min = time / 60 % 60;
var hor = (time / 60 / 60 + 8) % 12;
drawUntil(angToRad((secon * 6) - 90 ), s, context);
drawUntil(angToRad((min * 6) - 90 ), m, context);
drawUntil(angToRad((hor * 30) - 90 ), h, context);
}); |
typical000/jss-landing | src/components/Menu/styles.js | <reponame>typical000/jss-landing
export default {
menu: {
padding: [20, 30]
}
}
|
lzekrini/CONNECT | Product/Production/Services/CORE_X12DocumentSubmissionCore/src/test/java/gov/hhs/fha/nhinc/corex12/ds/audit/transform/X12BatchAuditTransformsTest.java | /*
* Copyright (c) 2009-2018, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.corex12.ds.audit.transform;
import com.services.nhinc.schema.auditmessage.ParticipantObjectIdentificationType;
import gov.hhs.fha.nhinc.audit.AuditTransformsConstants;
import gov.hhs.fha.nhinc.audit.transform.AuditTransforms;
import gov.hhs.fha.nhinc.audit.transform.AuditTransformsTest;
import gov.hhs.fha.nhinc.common.auditlog.LogEventRequestType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerException;
import gov.hhs.fha.nhinc.corex12.ds.audit.X12AuditDataTransformConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import java.net.UnknownHostException;
import java.util.Properties;
import org.caqh.soap.wsdl.corerule2_2_0.COREEnvelopeBatchSubmission;
import org.caqh.soap.wsdl.corerule2_2_0.COREEnvelopeBatchSubmissionResponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
/**
*
* @author achidamb
*/
public class X12BatchAuditTransformsTest extends
AuditTransformsTest<COREEnvelopeBatchSubmission, COREEnvelopeBatchSubmissionResponse> {
@Test
public void transformRequestToAuditMsg() throws ConnectionManagerException, UnknownHostException {
final String localIp = "10.10.10.10";
final String remoteIp = "16.14.13.12";
final String remoteObjectUrl = "http://" + remoteIp + ":9090/source/AuditService";
final String wsRequestUrl = "http://" + remoteIp + ":9090/AuditService";
Properties webContextProperties = new Properties();
webContextProperties.setProperty(NhincConstants.WEB_SERVICE_REQUEST_URL, wsRequestUrl);
webContextProperties.setProperty(NhincConstants.REMOTE_HOST_ADDRESS, remoteIp);
X12BatchAuditTransforms transforms = new X12BatchAuditTransforms() {
@Override
protected String getLocalHostAddress() {
return localIp;
}
@Override
protected String getRemoteHostAddress(Properties webContextProperties) {
if (webContextProperties != null && !webContextProperties.isEmpty() && webContextProperties
.getProperty(NhincConstants.REMOTE_HOST_ADDRESS) != null) {
return webContextProperties.getProperty(NhincConstants.REMOTE_HOST_ADDRESS);
}
return AuditTransformsConstants.ACTIVE_PARTICIPANT_UNKNOWN_IP_ADDRESS;
}
@Override
protected String getWebServiceUrlFromRemoteObject(NhinTargetSystemType target, String serviceName) {
return remoteObjectUrl;
}
};
AssertionType assertion = createAssertion();
LogEventRequestType auditRequest = transforms.transformRequestToAuditMsg(
createCOREEnvelopeBatchSubmissionRequest(), assertion, createNhinTarget(),
NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE, Boolean.TRUE,
webContextProperties, NhincConstants.CORE_X12DS_GENERICBATCH_REQUEST_SERVICE_NAME);
testGetEventIdentificationType(auditRequest, NhincConstants.CORE_X12DS_REALTIME_SERVICE_NAME, Boolean.TRUE);
testGetActiveParticipantSource(auditRequest, Boolean.TRUE, webContextProperties, localIp);
testGetActiveParticipantDestination(auditRequest, Boolean.TRUE, webContextProperties, remoteObjectUrl);
testAuditSourceIdentification(auditRequest.getAuditMessage().getAuditSourceIdentification(), assertion);
testCreateActiveParticipantFromUser(auditRequest, Boolean.TRUE, assertion);
assertParticipantObjectIdentification(auditRequest);
}
@Test
public void transformResponseToAuditMsg() throws ConnectionManagerException, UnknownHostException {
final String localIp = "10.10.10.10";
final String remoteIp = "16.14.13.12";
final String remoteObjectUrl = "http://" + remoteIp + ":9090/source/AuditService";
final String wsRequestUrl = "http://" + remoteIp + ":9090/AuditService";
Properties webContextProperties = new Properties();
webContextProperties.setProperty(NhincConstants.WEB_SERVICE_REQUEST_URL, wsRequestUrl);
webContextProperties.setProperty(NhincConstants.REMOTE_HOST_ADDRESS, remoteIp);
X12BatchAuditTransforms transforms = new X12BatchAuditTransforms() {
@Override
protected String getLocalHostAddress() {
return localIp;
}
@Override
protected String getRemoteHostAddress(Properties webContextProperties) {
if (webContextProperties != null && !webContextProperties.isEmpty() && webContextProperties
.getProperty(NhincConstants.REMOTE_HOST_ADDRESS) != null) {
return webContextProperties.getProperty(NhincConstants.REMOTE_HOST_ADDRESS);
}
return AuditTransformsConstants.ACTIVE_PARTICIPANT_UNKNOWN_IP_ADDRESS;
}
@Override
protected String getWebServiceUrlFromRemoteObject(NhinTargetSystemType target, String serviceName) {
return remoteObjectUrl;
}
};
AssertionType assertion = createAssertion();
LogEventRequestType auditRequest = transforms.transformResponseToAuditMsg(
createCOREEnvelopeBatchSubmissionRequest(), createCOREEnvelopeBatchSubmissionResponse(), assertion,
createNhinTarget(), NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE,
Boolean.TRUE, webContextProperties, NhincConstants.CORE_X12DS_REALTIME_SERVICE_NAME);
testGetEventIdentificationType(auditRequest, NhincConstants.CORE_X12DS_REALTIME_SERVICE_NAME, Boolean.TRUE);
testGetActiveParticipantSource(auditRequest, Boolean.TRUE, webContextProperties, localIp);
testGetActiveParticipantDestination(auditRequest, Boolean.TRUE, webContextProperties, remoteObjectUrl);
testAuditSourceIdentification(auditRequest.getAuditMessage().getAuditSourceIdentification(), assertion);
testCreateActiveParticipantFromUser(auditRequest, Boolean.TRUE, assertion);
assertParticipantObjectIdentification(auditRequest);
}
// TODO: Too many hard-coded inline values below
private COREEnvelopeBatchSubmission createCOREEnvelopeBatchSubmissionRequest() {
COREEnvelopeBatchSubmission request = new COREEnvelopeBatchSubmission();
request.setCORERuleVersion("2.2.0");
request.setPayloadID("5");
request.setPayloadType("X12_270_Request_005010X279A1");
request.setProcessingMode("RealTime");
request.setPayloadID("f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
request.setSenderID("HospitalA");
request.setReceiverID("PayerB");
return request;
}
private COREEnvelopeBatchSubmissionResponse createCOREEnvelopeBatchSubmissionResponse() {
COREEnvelopeBatchSubmissionResponse response = new COREEnvelopeBatchSubmissionResponse();
response.setCORERuleVersion("2.2.0");
response.setPayloadID("5");
response.setPayloadType("X12_270_Request_005010X279A1");
response.setProcessingMode("RealTime");
response.setPayloadID("f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
response.setSenderID("HospitalA");
response.setReceiverID("PayerB");
return response;
}
private void assertParticipantObjectIdentification(LogEventRequestType auditRequest) {
assertNotNull("auditRequest is null", auditRequest);
assertNotNull("AuditMessage is null", auditRequest.getAuditMessage());
assertNotNull("ParticipantObjectIdentification is null", auditRequest.getAuditMessage()
.getParticipantObjectIdentification());
assertFalse("ParticipantObjectIdentification list is missing test values", auditRequest.getAuditMessage()
.getParticipantObjectIdentification().isEmpty());
ParticipantObjectIdentificationType participantPatient = auditRequest.getAuditMessage()
.getParticipantObjectIdentification().get(0);
assertEquals("ParticipantPatient.ParticipantObjectID mismatch", "f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
participantPatient.getParticipantObjectID());
// TODO: assertSame vs assertEquals consistency when returning constants
assertSame("ParticipantPatient.ParticipantObjectTypeCode object reference mismatch",
X12AuditDataTransformConstants.PARTICIPANT_OJB_TYPE_CODE_SYSTEM,
participantPatient.getParticipantObjectTypeCode());
assertSame("ParticipantPatient.ParticipantObjectTypeCodeRole object reference mismatch",
X12AuditDataTransformConstants.PARTICIPANT_OBJ_TYPE_CODE_ROLE_X12,
participantPatient.getParticipantObjectTypeCodeRole());
assertEquals("ParticipantPatient.ParticipantObjectIDTypeCode.Code mismatch",
"f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
participantPatient.getParticipantObjectIDTypeCode().getCode());
assertEquals("ParticipantPatient.ParticipantObjectIDTypeCode.CodeSystemName mismatch",
X12AuditDataTransformConstants.CAQH_X12_CONNECTIVITY_CODED_SYS_NAME,
participantPatient.getParticipantObjectIDTypeCode().getCodeSystemName());
assertEquals("ParticipantPatient.ParticipantObjectIDTypeCode.DisplayName mismatch",
X12AuditDataTransformConstants.CAQH_X12_CONNECTIVITY_CODED_SYS_DISPLAY_NAME,
participantPatient.getParticipantObjectIDTypeCode().getDisplayName());
}
@Override
protected AuditTransforms<COREEnvelopeBatchSubmission, COREEnvelopeBatchSubmissionResponse> getAuditTransforms() {
return new X12BatchAuditTransforms();
}
}
|
tubone24/tech_blog_spider | src/util/harperdb.py | from interface.util.harperdb import HarperDB
from harperdb import HarperDB as Hdb
class HarperDBImpl(HarperDB):
def __init__(self, url: str, username: str, password: str):
self.db = Hdb(url=url, username=username, password=password)
def get_instance(self):
return self.db
|
goutomroy/uva.onlinejudge | solved/568 Just The Facts.cpp | #include<stdio.h>
int last[10001],c, fact[35670];
void factorial()
{
unsigned int i, j, k, c=0;
unsigned long sum;
last[c++] = 1; fact[35669] = 1; fact[35668]= -1;
for(i=1;i<=10000;i++)
{
sum = 0;
for(j=35669; ;j--)
{
if(fact[j]!=-1)
{
sum = sum + i*fact[j];
fact[j] = sum%10;
sum = sum/10;
}
if(sum!=0 && fact[j-1]==-1)
{
for(j= j-1;sum!=0;j--)
{
fact[j] = sum%10 ;
sum = 0;
}
fact[j] = -1;
}
if(sum==0 && fact[j]==-1) break;
}
for(k=35669;;k--)
if(fact[k]!=0){ last[c++] = fact[k] ; break;}
}
}
void main()
{
factorial();
int n;
for(;scanf("%d",&n)==1;)
printf("%5d -> %d\n",n,last[n]);
} |
gianricardo/OpcUaStack | src/OpcUaServer/Server/ServerMain.cpp | /*
Copyright 2015-2016 <NAME> (<EMAIL>)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: <NAME> (<EMAIL>)
*/
#include "OpcUaStackCore/Base/os.h"
#include "OpcUaServer/Server/Server.h"
#include "OpcUaStackCore/Base/Config.h"
#include "OpcUaStackCore/Utility/Environment.h"
#include "BuildConfig.h"
#include <iostream>
#include "OpcUaServer/Server/ServerApplication.h"
#include "OpcUaServer/Service/WindowsService.h"
#include "OpcUaServer/Service/LinuxService.h"
using namespace OpcUaStackCore;
int main(int argc, char** argv)
{
OpcUaServer::ServerApplication serverApplication;
#if _WIN32
OpcUaServer::WindowsService* service = OpcUaServer::WindowsService::instance();
#else
OpcUaServer::LinuxService* service = OpcUaServer::LinuxService::instance();
#endif
service->serverApplicationIf(&serverApplication);
service->main(argc, argv);
}
|
ElementAI/bytesteady | bytesteady/infer_test.cpp | /*
* Copyright 2021 ServiceNow
* 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 "bytesteady/infer.hpp"
#include "bytesteady/integer.hpp"
#include "gtest/gtest.h"
namespace bytesteady {
namespace {
template < typename T >
void inferTest() {
typedef T infer_type;
typedef typename T::callback_type callback_type;
typedef typename T::data_type data_type;
typedef typename T::loss_type loss_type;
typedef typename T::model_type model_type;
typedef typename T::local_type local_type;
typedef typename T::size_tensor size_tensor;
typedef typename data_type::byte_array byte_array;
typedef typename data_type::field_array field_array;
typedef typename data_type::format_array format_array;
typedef typename data_type::index_array index_array;
typedef typename model_type::gram_array gram_array;
typedef typename model_type::size_storage size_storage;
typedef typename model_type::size_type size_type;
typedef typename model_type::tensor_array tensor_array;
typedef typename model_type::tensor_type tensor_type;
typedef typename model_type::value_type value_type;
// Create data
::std::string data_file = "bytesteady/unittest_infer.txt";
format_array data_format = {kBytes, kIndex};
data_type data(data_file, data_format);
// Create model
size_storage model_input_size = {1000000, 16};
size_type model_output_size = 4;
size_type model_dimension = 10;
gram_array model_gram = {{1,2,4,8},{}};
uint64_t model_seed = 1946;
value_type model_mu = 0.0;
value_type model_sigma = 1.0;
model_type model(model_input_size, model_output_size, model_dimension,
model_gram, model_seed);
model.initialize(model_mu, model_sigma);
// Create loss
loss_type loss;
// Create infer object
::std::string infer_file = "bytesteady/unittest_result.txt";
size_type label_size = 2;
T infer(&data, &model, &loss, infer_file, label_size);
// Create a callback
callback_type callback =
[&](const local_type &local) -> void
{
using ::std::printf;
// Print infer
printf("Infer count = %lu, data_position = %lu",
infer.count(), local.data_position(0));
// Print data and universum
const field_array &data_input = local.data_input;
for (size_type i = 0; i < data_input.size(); ++i) {
if (data.format()[i] == kIndex) {
const index_array field_index = ::std::get< index_array >(
data_input[i]);
printf(", data_input[%lu] = [%lu", i, field_index.size());
for (size_type j = 0; j < field_index.size(); ++j) {
printf(", %lu:%g", field_index[j].first, field_index[j].second);
}
printf("]");
} else if (data.format()[i] == kBytes) {
const byte_array field_bytes = ::std::get< byte_array >(
data_input[i]);
printf(", data_input[%lu] = [%lu, ", i, field_bytes.size());
for (size_type j = 0; j < field_bytes.size(); ++j) {
printf("%2.2x", field_bytes[j]);
}
printf("]");
}
}
// Print model and loss
const tensor_array &input_embedding = model.input_embedding();
const tensor_type &output_embedding = model.output_embedding();
const tensor_type &output = model.output();
const tensor_type &feature = model.feature();
for (size_type i = 0; i < input_embedding.size(); ++i) {
printf(", input_embedding[%lu] = [%lu, %lu, %.8g, %.8g, %.8g, %.8g]",
i, input_embedding[i].size(0), input_embedding[i].size(1),
input_embedding[i].mean(), input_embedding[i].std(),
input_embedding[i].min(), input_embedding[i].max());
}
printf(", output_embedding = [%lu, %lu, %.8g, %.8g, %.8g, %8g]",
output_embedding.size(0), output_embedding.size(1),
output_embedding.mean(), output_embedding.std(),
output_embedding.min(), output_embedding.max());
printf(", output = [%lu, %.8g, %.8g, %.8g, %.8g]", output.size(0),
output.mean(), output.std(), output.min(), output.max());
printf(", feature = [%lu, %.8g, %.8g, %.8g, %.8g]", feature.size(0),
feature.mean(), feature.std(), feature.min(), feature.max());
printf("\n");
};
EXPECT_TRUE(infer.infer(callback));
EXPECT_EQ(20, data.count());
EXPECT_EQ(20, infer.count());
}
TEST(InferTest, inferTest) {
inferTest< DoubleFNVNLLInfer >();
}
} // namespace
} // namespace bytesteady
|
danchia/ddb | vendor/go.opencensus.io/exporter/jaeger/internal/gen-go/dependency/dependency.go | // Autogenerated by Thrift Compiler (0.11.0)
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
package dependency
import (
"bytes"
"context"
"fmt"
"reflect"
"git.apache.org/thrift.git/lib/go/thrift"
)
// (needed to ensure safety because of naive import list construction.)
var _ = thrift.ZERO
var _ = fmt.Printf
var _ = context.Background
var _ = reflect.DeepEqual
var _ = bytes.Equal
// Attributes:
// - Parent
// - Child
// - CallCount
type DependencyLink struct {
Parent string `thrift:"parent,1,required" db:"parent" json:"parent"`
Child string `thrift:"child,2,required" db:"child" json:"child"`
// unused field # 3
CallCount int64 `thrift:"callCount,4,required" db:"callCount" json:"callCount"`
}
func NewDependencyLink() *DependencyLink {
return &DependencyLink{}
}
func (p *DependencyLink) GetParent() string {
return p.Parent
}
func (p *DependencyLink) GetChild() string {
return p.Child
}
func (p *DependencyLink) GetCallCount() int64 {
return p.CallCount
}
func (p *DependencyLink) Read(iprot thrift.TProtocol) error {
if _, err := iprot.ReadStructBegin(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
}
var issetParent bool = false
var issetChild bool = false
var issetCallCount bool = false
for {
_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if err != nil {
return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.STRING {
if err := p.ReadField1(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
issetParent = true
case 2:
if fieldTypeId == thrift.STRING {
if err := p.ReadField2(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
issetChild = true
case 4:
if fieldTypeId == thrift.I64 {
if err := p.ReadField4(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
issetCallCount = true
default:
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
if err := iprot.ReadFieldEnd(); err != nil {
return err
}
}
if err := iprot.ReadStructEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
if !issetParent {
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("Required field Parent is not set"))
}
if !issetChild {
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("Required field Child is not set"))
}
if !issetCallCount {
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("Required field CallCount is not set"))
}
return nil
}
func (p *DependencyLink) ReadField1(iprot thrift.TProtocol) error {
if v, err := iprot.ReadString(); err != nil {
return thrift.PrependError("error reading field 1: ", err)
} else {
p.Parent = v
}
return nil
}
func (p *DependencyLink) ReadField2(iprot thrift.TProtocol) error {
if v, err := iprot.ReadString(); err != nil {
return thrift.PrependError("error reading field 2: ", err)
} else {
p.Child = v
}
return nil
}
func (p *DependencyLink) ReadField4(iprot thrift.TProtocol) error {
if v, err := iprot.ReadI64(); err != nil {
return thrift.PrependError("error reading field 4: ", err)
} else {
p.CallCount = v
}
return nil
}
func (p *DependencyLink) Write(oprot thrift.TProtocol) error {
if err := oprot.WriteStructBegin("DependencyLink"); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
}
if p != nil {
if err := p.writeField1(oprot); err != nil {
return err
}
if err := p.writeField2(oprot); err != nil {
return err
}
if err := p.writeField4(oprot); err != nil {
return err
}
}
if err := oprot.WriteFieldStop(); err != nil {
return thrift.PrependError("write field stop error: ", err)
}
if err := oprot.WriteStructEnd(); err != nil {
return thrift.PrependError("write struct stop error: ", err)
}
return nil
}
func (p *DependencyLink) writeField1(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("parent", thrift.STRING, 1); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:parent: ", p), err)
}
if err := oprot.WriteString(string(p.Parent)); err != nil {
return thrift.PrependError(fmt.Sprintf("%T.parent (1) field write error: ", p), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 1:parent: ", p), err)
}
return err
}
func (p *DependencyLink) writeField2(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("child", thrift.STRING, 2); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:child: ", p), err)
}
if err := oprot.WriteString(string(p.Child)); err != nil {
return thrift.PrependError(fmt.Sprintf("%T.child (2) field write error: ", p), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 2:child: ", p), err)
}
return err
}
func (p *DependencyLink) writeField4(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("callCount", thrift.I64, 4); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:callCount: ", p), err)
}
if err := oprot.WriteI64(int64(p.CallCount)); err != nil {
return thrift.PrependError(fmt.Sprintf("%T.callCount (4) field write error: ", p), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 4:callCount: ", p), err)
}
return err
}
func (p *DependencyLink) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DependencyLink(%+v)", *p)
}
// Attributes:
// - Links
type Dependencies struct {
Links []*DependencyLink `thrift:"links,1,required" db:"links" json:"links"`
}
func NewDependencies() *Dependencies {
return &Dependencies{}
}
func (p *Dependencies) GetLinks() []*DependencyLink {
return p.Links
}
func (p *Dependencies) Read(iprot thrift.TProtocol) error {
if _, err := iprot.ReadStructBegin(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
}
var issetLinks bool = false
for {
_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if err != nil {
return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.LIST {
if err := p.ReadField1(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
issetLinks = true
default:
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
if err := iprot.ReadFieldEnd(); err != nil {
return err
}
}
if err := iprot.ReadStructEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
if !issetLinks {
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("Required field Links is not set"))
}
return nil
}
func (p *Dependencies) ReadField1(iprot thrift.TProtocol) error {
_, size, err := iprot.ReadListBegin()
if err != nil {
return thrift.PrependError("error reading list begin: ", err)
}
tSlice := make([]*DependencyLink, 0, size)
p.Links = tSlice
for i := 0; i < size; i++ {
_elem0 := &DependencyLink{}
if err := _elem0.Read(iprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem0), err)
}
p.Links = append(p.Links, _elem0)
}
if err := iprot.ReadListEnd(); err != nil {
return thrift.PrependError("error reading list end: ", err)
}
return nil
}
func (p *Dependencies) Write(oprot thrift.TProtocol) error {
if err := oprot.WriteStructBegin("Dependencies"); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
}
if p != nil {
if err := p.writeField1(oprot); err != nil {
return err
}
}
if err := oprot.WriteFieldStop(); err != nil {
return thrift.PrependError("write field stop error: ", err)
}
if err := oprot.WriteStructEnd(); err != nil {
return thrift.PrependError("write struct stop error: ", err)
}
return nil
}
func (p *Dependencies) writeField1(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("links", thrift.LIST, 1); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:links: ", p), err)
}
if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Links)); err != nil {
return thrift.PrependError("error writing list begin: ", err)
}
for _, v := range p.Links {
if err := v.Write(oprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err)
}
}
if err := oprot.WriteListEnd(); err != nil {
return thrift.PrependError("error writing list end: ", err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 1:links: ", p), err)
}
return err
}
func (p *Dependencies) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("Dependencies(%+v)", *p)
}
type Dependency interface {
// Parameters:
// - TraceId
GetDependenciesForTrace(ctx context.Context, traceId string) (r *Dependencies, err error)
// Parameters:
// - Dependencies
SaveDependencies(ctx context.Context, dependencies *Dependencies) (err error)
}
type DependencyClient struct {
c thrift.TClient
}
// Deprecated: Use NewDependency instead
func NewDependencyClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *DependencyClient {
return &DependencyClient{
c: thrift.NewTStandardClient(f.GetProtocol(t), f.GetProtocol(t)),
}
}
// Deprecated: Use NewDependency instead
func NewDependencyClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *DependencyClient {
return &DependencyClient{
c: thrift.NewTStandardClient(iprot, oprot),
}
}
func NewDependencyClient(c thrift.TClient) *DependencyClient {
return &DependencyClient{
c: c,
}
}
// Parameters:
// - TraceId
func (p *DependencyClient) GetDependenciesForTrace(ctx context.Context, traceId string) (r *Dependencies, err error) {
var _args1 DependencyGetDependenciesForTraceArgs
_args1.TraceId = traceId
var _result2 DependencyGetDependenciesForTraceResult
if err = p.c.Call(ctx, "getDependenciesForTrace", &_args1, &_result2); err != nil {
return
}
return _result2.GetSuccess(), nil
}
// Parameters:
// - Dependencies
func (p *DependencyClient) SaveDependencies(ctx context.Context, dependencies *Dependencies) (err error) {
var _args3 DependencySaveDependenciesArgs
_args3.Dependencies = dependencies
if err := p.c.Call(ctx, "saveDependencies", &_args3, nil); err != nil {
return err
}
return nil
}
type DependencyProcessor struct {
processorMap map[string]thrift.TProcessorFunction
handler Dependency
}
func (p *DependencyProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) {
p.processorMap[key] = processor
}
func (p *DependencyProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) {
processor, ok = p.processorMap[key]
return processor, ok
}
func (p *DependencyProcessor) ProcessorMap() map[string]thrift.TProcessorFunction {
return p.processorMap
}
func NewDependencyProcessor(handler Dependency) *DependencyProcessor {
self4 := &DependencyProcessor{handler: handler, processorMap: make(map[string]thrift.TProcessorFunction)}
self4.processorMap["getDependenciesForTrace"] = &dependencyProcessorGetDependenciesForTrace{handler: handler}
self4.processorMap["saveDependencies"] = &dependencyProcessorSaveDependencies{handler: handler}
return self4
}
func (p *DependencyProcessor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
name, _, seqId, err := iprot.ReadMessageBegin()
if err != nil {
return false, err
}
if processor, ok := p.GetProcessorFunction(name); ok {
return processor.Process(ctx, seqId, iprot, oprot)
}
iprot.Skip(thrift.STRUCT)
iprot.ReadMessageEnd()
x5 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function "+name)
oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId)
x5.Write(oprot)
oprot.WriteMessageEnd()
oprot.Flush()
return false, x5
}
type dependencyProcessorGetDependenciesForTrace struct {
handler Dependency
}
func (p *dependencyProcessorGetDependenciesForTrace) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
args := DependencyGetDependenciesForTraceArgs{}
if err = args.Read(iprot); err != nil {
iprot.ReadMessageEnd()
x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
oprot.WriteMessageBegin("getDependenciesForTrace", thrift.EXCEPTION, seqId)
x.Write(oprot)
oprot.WriteMessageEnd()
oprot.Flush()
return false, err
}
iprot.ReadMessageEnd()
result := DependencyGetDependenciesForTraceResult{}
var retval *Dependencies
var err2 error
if retval, err2 = p.handler.GetDependenciesForTrace(ctx, args.TraceId); err2 != nil {
x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getDependenciesForTrace: "+err2.Error())
oprot.WriteMessageBegin("getDependenciesForTrace", thrift.EXCEPTION, seqId)
x.Write(oprot)
oprot.WriteMessageEnd()
oprot.Flush()
return true, err2
} else {
result.Success = retval
}
if err2 = oprot.WriteMessageBegin("getDependenciesForTrace", thrift.REPLY, seqId); err2 != nil {
err = err2
}
if err2 = result.Write(oprot); err == nil && err2 != nil {
err = err2
}
if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
err = err2
}
if err2 = oprot.Flush(); err == nil && err2 != nil {
err = err2
}
if err != nil {
return
}
return true, err
}
type dependencyProcessorSaveDependencies struct {
handler Dependency
}
func (p *dependencyProcessorSaveDependencies) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
args := DependencySaveDependenciesArgs{}
if err = args.Read(iprot); err != nil {
iprot.ReadMessageEnd()
return false, err
}
iprot.ReadMessageEnd()
var err2 error
if err2 = p.handler.SaveDependencies(ctx, args.Dependencies); err2 != nil {
return true, err2
}
return true, nil
}
// HELPER FUNCTIONS AND STRUCTURES
// Attributes:
// - TraceId
type DependencyGetDependenciesForTraceArgs struct {
TraceId string `thrift:"traceId,1,required" db:"traceId" json:"traceId"`
}
func NewDependencyGetDependenciesForTraceArgs() *DependencyGetDependenciesForTraceArgs {
return &DependencyGetDependenciesForTraceArgs{}
}
func (p *DependencyGetDependenciesForTraceArgs) GetTraceId() string {
return p.TraceId
}
func (p *DependencyGetDependenciesForTraceArgs) Read(iprot thrift.TProtocol) error {
if _, err := iprot.ReadStructBegin(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
}
var issetTraceId bool = false
for {
_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if err != nil {
return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.STRING {
if err := p.ReadField1(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
issetTraceId = true
default:
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
if err := iprot.ReadFieldEnd(); err != nil {
return err
}
}
if err := iprot.ReadStructEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
if !issetTraceId {
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("Required field TraceId is not set"))
}
return nil
}
func (p *DependencyGetDependenciesForTraceArgs) ReadField1(iprot thrift.TProtocol) error {
if v, err := iprot.ReadString(); err != nil {
return thrift.PrependError("error reading field 1: ", err)
} else {
p.TraceId = v
}
return nil
}
func (p *DependencyGetDependenciesForTraceArgs) Write(oprot thrift.TProtocol) error {
if err := oprot.WriteStructBegin("getDependenciesForTrace_args"); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
}
if p != nil {
if err := p.writeField1(oprot); err != nil {
return err
}
}
if err := oprot.WriteFieldStop(); err != nil {
return thrift.PrependError("write field stop error: ", err)
}
if err := oprot.WriteStructEnd(); err != nil {
return thrift.PrependError("write struct stop error: ", err)
}
return nil
}
func (p *DependencyGetDependenciesForTraceArgs) writeField1(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("traceId", thrift.STRING, 1); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:traceId: ", p), err)
}
if err := oprot.WriteString(string(p.TraceId)); err != nil {
return thrift.PrependError(fmt.Sprintf("%T.traceId (1) field write error: ", p), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 1:traceId: ", p), err)
}
return err
}
func (p *DependencyGetDependenciesForTraceArgs) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DependencyGetDependenciesForTraceArgs(%+v)", *p)
}
// Attributes:
// - Success
type DependencyGetDependenciesForTraceResult struct {
Success *Dependencies `thrift:"success,0" db:"success" json:"success,omitempty"`
}
func NewDependencyGetDependenciesForTraceResult() *DependencyGetDependenciesForTraceResult {
return &DependencyGetDependenciesForTraceResult{}
}
var DependencyGetDependenciesForTraceResult_Success_DEFAULT *Dependencies
func (p *DependencyGetDependenciesForTraceResult) GetSuccess() *Dependencies {
if !p.IsSetSuccess() {
return DependencyGetDependenciesForTraceResult_Success_DEFAULT
}
return p.Success
}
func (p *DependencyGetDependenciesForTraceResult) IsSetSuccess() bool {
return p.Success != nil
}
func (p *DependencyGetDependenciesForTraceResult) Read(iprot thrift.TProtocol) error {
if _, err := iprot.ReadStructBegin(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
}
for {
_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if err != nil {
return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 0:
if fieldTypeId == thrift.STRUCT {
if err := p.ReadField0(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
default:
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
if err := iprot.ReadFieldEnd(); err != nil {
return err
}
}
if err := iprot.ReadStructEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
return nil
}
func (p *DependencyGetDependenciesForTraceResult) ReadField0(iprot thrift.TProtocol) error {
p.Success = &Dependencies{}
if err := p.Success.Read(iprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
}
return nil
}
func (p *DependencyGetDependenciesForTraceResult) Write(oprot thrift.TProtocol) error {
if err := oprot.WriteStructBegin("getDependenciesForTrace_result"); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
}
if p != nil {
if err := p.writeField0(oprot); err != nil {
return err
}
}
if err := oprot.WriteFieldStop(); err != nil {
return thrift.PrependError("write field stop error: ", err)
}
if err := oprot.WriteStructEnd(); err != nil {
return thrift.PrependError("write struct stop error: ", err)
}
return nil
}
func (p *DependencyGetDependenciesForTraceResult) writeField0(oprot thrift.TProtocol) (err error) {
if p.IsSetSuccess() {
if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err)
}
if err := p.Success.Write(oprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err)
}
}
return err
}
func (p *DependencyGetDependenciesForTraceResult) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DependencyGetDependenciesForTraceResult(%+v)", *p)
}
// Attributes:
// - Dependencies
type DependencySaveDependenciesArgs struct {
Dependencies *Dependencies `thrift:"dependencies,1" db:"dependencies" json:"dependencies"`
}
func NewDependencySaveDependenciesArgs() *DependencySaveDependenciesArgs {
return &DependencySaveDependenciesArgs{}
}
var DependencySaveDependenciesArgs_Dependencies_DEFAULT *Dependencies
func (p *DependencySaveDependenciesArgs) GetDependencies() *Dependencies {
if !p.IsSetDependencies() {
return DependencySaveDependenciesArgs_Dependencies_DEFAULT
}
return p.Dependencies
}
func (p *DependencySaveDependenciesArgs) IsSetDependencies() bool {
return p.Dependencies != nil
}
func (p *DependencySaveDependenciesArgs) Read(iprot thrift.TProtocol) error {
if _, err := iprot.ReadStructBegin(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
}
for {
_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if err != nil {
return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.STRUCT {
if err := p.ReadField1(iprot); err != nil {
return err
}
} else {
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
default:
if err := iprot.Skip(fieldTypeId); err != nil {
return err
}
}
if err := iprot.ReadFieldEnd(); err != nil {
return err
}
}
if err := iprot.ReadStructEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
return nil
}
func (p *DependencySaveDependenciesArgs) ReadField1(iprot thrift.TProtocol) error {
p.Dependencies = &Dependencies{}
if err := p.Dependencies.Read(iprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Dependencies), err)
}
return nil
}
func (p *DependencySaveDependenciesArgs) Write(oprot thrift.TProtocol) error {
if err := oprot.WriteStructBegin("saveDependencies_args"); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
}
if p != nil {
if err := p.writeField1(oprot); err != nil {
return err
}
}
if err := oprot.WriteFieldStop(); err != nil {
return thrift.PrependError("write field stop error: ", err)
}
if err := oprot.WriteStructEnd(); err != nil {
return thrift.PrependError("write struct stop error: ", err)
}
return nil
}
func (p *DependencySaveDependenciesArgs) writeField1(oprot thrift.TProtocol) (err error) {
if err := oprot.WriteFieldBegin("dependencies", thrift.STRUCT, 1); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:dependencies: ", p), err)
}
if err := p.Dependencies.Write(oprot); err != nil {
return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Dependencies), err)
}
if err := oprot.WriteFieldEnd(); err != nil {
return thrift.PrependError(fmt.Sprintf("%T write field end error 1:dependencies: ", p), err)
}
return err
}
func (p *DependencySaveDependenciesArgs) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DependencySaveDependenciesArgs(%+v)", *p)
}
|
WhatAKitty/ssm | biz/src/main/java/com/sccbv/system/rolespermissions/RolesPermissionsValidate.java | package com.sccbv.system.rolespermissions;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* 自定义验证注解
*
* @author yuhailun
* @date 2018/01/24
* @description
**/
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = RolesPermissionsValidator.class)
@Documented
public @interface RolesPermissionsValidate {
/**
* 验证返回信息
*
* @return 验证信息
*/
String message() default "";
/**
* 所属验证组
*
* @return 验证组类
*/
Class<?>[] groups() default {};
/**
* 数据载体类
*
* @return 类列表
*/
Class<? extends Payload>[] payload() default {};
}
|
josivantarcio/Udemy | Geek-Java/src/exercicios/secao03/Exercicio06.java | <filename>Geek-Java/src/exercicios/secao03/Exercicio06.java
package exercicios.secao03;
import java.util.Scanner;
public class Exercicio06 {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
float f, c;
System.out.print("Temperatura Cº ");
c = keyb.nextFloat();
f = c * (9/5) + 32;
System.out.println("Temperatura em Fº "+f);
keyb.close();
}
}
|
kubrafelek/AssesmentProject | project/src/main/java/tapu/com/project/model/enums/Exceptions.java | <reponame>kubrafelek/AssesmentProject
package tapu.com.project.model.enums;
public enum Exceptions {
UserAlreadyExistException,
BadRequestException
}
|
johnvoon/launch_school | exercise_sets_for_101_109/easy5/after_midnight.rb | <filename>exercise_sets_for_101_109/easy5/after_midnight.rb
MINUTES_PER_HOUR = 60
HOURS_PER_DAY = 24
MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR
def time_of_day(delta_minutes) # delta_minutes is the number of minutes to wind the clock backwards or forwards
delta_minutes = delta_minutes % MINUTES_PER_DAY # i.e. 1440. Let's say delta_minutes is 1440
hours, minutes = delta_minutes.divmod(MINUTES_PER_HOUR)
format('%02d:%02d', hours, minutes)
end
p time_of_day(-67) |
wuranjia/CMPPGate | src/main/java/com/zx/sms/codec/cmpp7F/Cmpp7FSubmitRequestMessageCodec.java | <reponame>wuranjia/CMPPGate
/**
*
*/
package com.zx.sms.codec.cmpp7F;
import static com.zx.sms.common.util.NettyByteBufUtil.toArray;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.ReferenceCountUtil;
import java.util.List;
import org.marre.sms.SmsDcs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zx.sms.codec.cmpp.msg.CmppSubmitRequestMessage;
import com.zx.sms.codec.cmpp.msg.Message;
import com.zx.sms.codec.cmpp.packet.CmppSubmitRequest;
import com.zx.sms.codec.cmpp.packet.PacketType;
import com.zx.sms.codec.cmpp.wap.LongMessageFrameHolder;
import com.zx.sms.codec.cmpp7F.packet.Cmpp7FPacketType;
import com.zx.sms.common.GlobalConstance;
import com.zx.sms.common.util.CMPPCommonUtil;
import com.zx.sms.common.util.DefaultMsgIdUtil;
import com.zx.sms.common.util.FstObjectSerializeUtil;
/**
* @author huzorro(<EMAIL>)
* @author Lihuanghe(<EMAIL>)
*/
public class Cmpp7FSubmitRequestMessageCodec extends MessageToMessageCodec<Message, CmppSubmitRequestMessage> {
private final Logger logger = LoggerFactory.getLogger(Cmpp7FSubmitRequestMessageCodec.class);
private PacketType packetType;
/**
*
*/
public Cmpp7FSubmitRequestMessageCodec() {
this(Cmpp7FPacketType.CMPPSUBMITREQUEST);
}
public Cmpp7FSubmitRequestMessageCodec(PacketType packetType) {
this.packetType = packetType;
}
@Override
protected void decode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
long commandId = ((Long) msg.getHeader().getCommandId()).longValue();
if (packetType.getCommandId() != commandId) {
// 不解析,交给下一个codec
out.add(msg);
return;
}
CmppSubmitRequestMessage requestMessage = new CmppSubmitRequestMessage(msg.getHeader());
ByteBuf bodyBuffer = Unpooled.wrappedBuffer(msg.getBodyBuffer());
requestMessage.setMsgid(DefaultMsgIdUtil.bytes2MsgId(toArray(bodyBuffer,CmppSubmitRequest.MSGID.getLength())));
requestMessage.setPktotal(bodyBuffer.readUnsignedByte());
requestMessage.setPknumber(bodyBuffer.readUnsignedByte());
requestMessage.setRegisteredDelivery(bodyBuffer.readUnsignedByte());
requestMessage.setMsglevel(bodyBuffer.readUnsignedByte());
requestMessage.setServiceId(bodyBuffer.readCharSequence(CmppSubmitRequest.SERVICEID.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setFeeUserType(bodyBuffer.readUnsignedByte());
requestMessage.setFeeterminalId(bodyBuffer.readCharSequence(CmppSubmitRequest.FEETERMINALID.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setFeeterminaltype(bodyBuffer.readUnsignedByte());
requestMessage.setTppid(bodyBuffer.readUnsignedByte());
requestMessage.setTpudhi(bodyBuffer.readUnsignedByte());
requestMessage.setMsgfmt(new SmsDcs((byte)bodyBuffer.readUnsignedByte()));
requestMessage.setMsgsrc(bodyBuffer.readCharSequence(CmppSubmitRequest.MSGSRC.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setFeeType(bodyBuffer.readCharSequence(CmppSubmitRequest.FEETYPE.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setFeeCode(bodyBuffer.readCharSequence(CmppSubmitRequest.FEECODE.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setValIdTime(bodyBuffer.readCharSequence(CmppSubmitRequest.VALIDTIME.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setAtTime(bodyBuffer.readCharSequence(CmppSubmitRequest.ATTIME.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setSrcId(bodyBuffer.readCharSequence(CmppSubmitRequest.SRCID.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
requestMessage.setDestUsrtl(bodyBuffer.readUnsignedByte());
String[] destTermId = new String[requestMessage.getDestUsrtl()];
for (int i = 0; i < requestMessage.getDestUsrtl(); i++) {
destTermId[i] = bodyBuffer.readCharSequence(CmppSubmitRequest.DESTTERMINALID.getLength(),GlobalConstance.defaultTransportCharset).toString().trim();
}
requestMessage.setDestterminalId(destTermId);
requestMessage.setDestterminaltype(bodyBuffer.readUnsignedByte());
short msgLength = (short)(LongMessageFrameHolder.getPayloadLength(requestMessage.getMsgfmt().getAlphabet(),bodyBuffer.readUnsignedByte()) & 0xffff);
byte[] contentbytes = new byte[msgLength];
bodyBuffer.readBytes(contentbytes);
requestMessage.setMsgContentBytes(contentbytes);
requestMessage.setMsgLength((short)msgLength);
requestMessage.setLinkID(bodyBuffer.readCharSequence(CmppSubmitRequest.LINKID.getLength(),GlobalConstance.defaultTransportCharset).toString().trim());
//在线公司自定义的字段
int attach = bodyBuffer.readInt();
if(attach != 0 ){
byte[] objbytes = new byte[attach];
bodyBuffer.readBytes(objbytes);
try{
requestMessage.setAttachment(FstObjectSerializeUtil.read(objbytes));
}catch(Exception ex){
logger.warn("Attachment decode error",ex);
}
}
out.add(requestMessage);
ReferenceCountUtil.release(bodyBuffer);
}
@Override
protected void encode(ChannelHandlerContext ctx, CmppSubmitRequestMessage requestMessage, List<Object> out) throws Exception {
ByteBuf bodyBuffer = Unpooled.buffer(CmppSubmitRequest.ATTIME.getBodyLength() + requestMessage.getMsgLength() + requestMessage.getDestUsrtl()
* CmppSubmitRequest.DESTTERMINALID.getLength());
bodyBuffer.writeBytes(DefaultMsgIdUtil.msgId2Bytes(requestMessage.getMsgid()));
bodyBuffer.writeByte(requestMessage.getPktotal());
bodyBuffer.writeByte(requestMessage.getPknumber());
bodyBuffer.writeByte(requestMessage.getRegisteredDelivery());
bodyBuffer.writeByte(requestMessage.getMsglevel());
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getServiceId().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.SERVICEID.getLength(), 0));
bodyBuffer.writeByte(requestMessage.getFeeUserType());
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getFeeterminalId().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.FEETERMINALID.getLength(), 0));
bodyBuffer.writeByte(requestMessage.getFeeterminaltype());
bodyBuffer.writeByte(requestMessage.getTppid());
bodyBuffer.writeByte(requestMessage.getTpudhi());
bodyBuffer.writeByte(requestMessage.getMsgfmt().getValue());
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getMsgsrc().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.MSGSRC.getLength(), 0));
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getFeeType().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.FEETYPE.getLength(), 0));
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getFeeCode().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.FEECODE.getLength(), 0));
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getValIdTime().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.VALIDTIME.getLength(), 0));
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getAtTime().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.ATTIME.getLength(), 0));
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getSrcId().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.SRCID.getLength(), 0));
bodyBuffer.writeByte(requestMessage.getDestUsrtl());
for (int i = 0; i < requestMessage.getDestUsrtl(); i++) {
String[] destTermId = requestMessage.getDestterminalId();
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(destTermId[i].getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.DESTTERMINALID.getLength(), 0));
}
bodyBuffer.writeByte(requestMessage.getDestterminaltype());
bodyBuffer.writeByte(requestMessage.getMsgLength());
bodyBuffer.writeBytes(requestMessage.getMsgContentBytes());
bodyBuffer.writeBytes(CMPPCommonUtil.ensureLength(requestMessage.getLinkID().getBytes(GlobalConstance.defaultTransportCharset),
CmppSubmitRequest.LINKID.getLength(), 0));
//在线公司自定义的字段
if(requestMessage.getAttachment()!=null){
try{
byte[] attach =FstObjectSerializeUtil.write(requestMessage.getAttachment());
bodyBuffer.writeInt(attach.length);
bodyBuffer.writeBytes(attach);
}catch(Exception ex){
logger.warn("Attachment Serializa error",ex);
bodyBuffer.writeInt(0);
}
}else{
bodyBuffer.writeInt(0);
}
requestMessage.setBodyBuffer(toArray(bodyBuffer,bodyBuffer.readableBytes()));
requestMessage.getHeader().setBodyLength(requestMessage.getBodyBuffer().length);
out.add(requestMessage);
ReferenceCountUtil.release(bodyBuffer);
}
}
|
cyllene-project/Rubric | src/draw/css/CSSValueList.h | <reponame>cyllene-project/Rubric<filename>src/draw/css/CSSValueList.h
/*
* (C) 1999-2003 <NAME> (<EMAIL>)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#pragma once
#include "CSSValue.h"
#include <vector>
#include <draw/css/ref_ptr.h>
using namespace rubric::draw::css;
namespace WebCore {
class CSSCustomPropertyValue;
struct CSSParserValue;
class CSSParserValueList;
class CSSValueList : public CSSValue {
public:
typedef std::vector<ref_ptr<CSSValue>>::iterator iterator;
typedef std::vector<ref_ptr<CSSValue>>::const_iterator const_iterator;
static ref_ptr<CSSValueList> createCommaSeparated()
{
return ref_ptr<CSSValueList>(CommaSeparator);
}
static ref_ptr<CSSValueList> createSpaceSeparated()
{
return ref_ptr<CSSValueList>(SpaceSeparator);
}
static ref_ptr<CSSValueList> createSlashSeparated()
{
return ref_ptr<CSSValueList>(SlashSeparator);
}
size_t length() const { return m_values.size(); }
CSSValue* item(size_t index) { return index < m_values.size() ? m_values[index].ptr() : nullptr; }
const CSSValue* item(size_t index) const { return index < m_values.size() ? m_values[index].ptr() : nullptr; }
CSSValue* itemWithoutBoundsCheck(size_t index) { return m_values[index].ptr(); }
const CSSValue* itemWithoutBoundsCheck(size_t index) const { assert(index < m_values.size()); return m_values[index].ptr(); }
const_iterator begin() const { return m_values.begin(); }
const_iterator end() const { return m_values.end(); }
iterator begin() { return m_values.begin(); }
iterator end() { return m_values.end(); }
void append(ref_ptr<CSSValue>&&);
void prepend(ref_ptr<CSSValue>&&);
bool removeAll(CSSValue*);
bool hasValue(CSSValue*) const;
ref_ptr<CSSValueList> copy();
std::string customCSSText() const;
bool equals(const CSSValueList&) const;
bool equals(const CSSValue&) const;
bool traverseSubresources(const std::function<bool (const CachedResource&)>& handler) const;
unsigned separator() const { return m_valueListSeparator; }
protected:
CSSValueList(ClassType, ValueListSeparator);
private:
explicit CSSValueList(ValueListSeparator);
std::vector<ref_ptr<CSSValue>> m_values;
};
inline void CSSValueList::append(ref_ptr<CSSValue>&& value)
{
m_values.push_back(std::move(value));
}
inline void CSSValueList::prepend(ref_ptr<CSSValue>&& value)
{
m_values.insert(m_values.begin(), std::move(value));
}
} // namespace WebCore
SPECIALIZE_TYPE_TRAITS_CSS_VALUE(CSSValueList, isValueList())
|
huydinhquang/BIS2019_MasterThesis | ECG_Evaluation/Views/RecordSetView.py | <reponame>huydinhquang/BIS2019_MasterThesis
import streamlit as st
def load_form():
# list_channel = st.sidebar.multiselect(
# 'Channel(s)',
# ['I', 'II', 'III',
# 'aVR', 'aVL', 'aVF',
# 'V1', 'V2', 'V3',
# 'V4', 'V5', 'V6',
# 'Vx', 'Vy', 'Vz'])
# source_name = st.sidebar.text_input('Source name')
load_source_list_clicked = st.sidebar.button('Load source list')
# with st.sidebar.form("my_form"):
# a = st.slider('sidebar for testing', 5, 10, 9)
# calculate = st.form_submit_button('Calculate')
# sample_rate = st.sidebar.number_input('Sample rate', min_value=0,max_value=10000,value=1000)
# export_unit = st.sidebar.number_input('Export unit', min_value=0, max_value=10000, value=10)
# return list_channel, sample_rate, export_unit, filter_source
return load_source_list_clicked
def filter_source():
source_name = st.text_input('Source name')
filter_source_clicked = st.button('Filter source')
return source_name, filter_source_clicked
def record_set():
st.write('### Record set creation')
with st.form('Record set creation'):
record_set_name = st.text_input('Record set name')
# region_start = st.number_input('Region start', min_value=0)
# region_end = st.number_input('Region end', min_value=0)
create_clicked = st.form_submit_button('Create')
return record_set_name, create_clicked
def render_download_section():
folder_download = st.text_input(label='Downloadable folder:', value="C:/Users/HuyDQ/OneDrive/HuyDQ/OneDrive/MasterThesis/Thesis/DB/Download")
if folder_download:
clicked = st.button('Download files')
return folder_download, clicked
def render_resample_signal():
clicked = st.button('Resample signals')
return clicked |
likianta/declare-qtquick | archived_projects_(dead)/declare_pyside/widgets/mouse_area.py | <reponame>likianta/declare-qtquick<filename>archived_projects_(dead)/declare_pyside/widgets/mouse_area.py<gh_stars>1-10
from .base_item import BaseItem
from .core.authorized_props import MouseAreaProps
from ..path_model import widgets_dir
class MouseArea(BaseItem, MouseAreaProps):
qmlfile = f'{widgets_dir}/qml_assets/MouseArea.qml'
|
techAi007/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartProperties.java | /*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.web.reactive;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader;
import org.springframework.util.unit.DataSize;
/**
* {@link ConfigurationProperties Configuration properties} for configuring multipart
* support in Spring Webflux. Used to configure the {@link DefaultPartHttpMessageReader}.
*
* @author <NAME>
* @since 2.6.0
*/
@ConfigurationProperties(prefix = "spring.webflux.multipart")
public class ReactiveMultipartProperties {
/**
* Maximum amount of memory allowed per part before it's written to disk. Set to -1 to
* store all contents in memory. Ignored when streaming is enabled.
*/
private DataSize maxInMemorySize = DataSize.ofKilobytes(256);
/**
* Maximum amount of memory allowed per headers section of each part. Set to -1 to
* enforce no limits.
*/
private DataSize maxHeadersSize = DataSize.ofKilobytes(10);
/**
* Maximum amount of disk space allowed per part. Default is -1 which enforces no
* limits. Ignored when streaming is enabled.
*/
private DataSize maxDiskUsagePerPart = DataSize.ofBytes(-1);
/**
* Maximum number of parts allowed in a given multipart request. Default is -1 which
* enforces no limits.
*/
private Integer maxParts = -1;
/**
* Whether to stream directly from the parsed input buffer stream without storing in
* memory nor file. Default is non-streaming.
*/
private Boolean streaming = Boolean.FALSE;
/**
* Directory used to store file parts larger than 'maxInMemorySize'. Default is a
* directory named 'spring-multipart' created under the system temporary directory.
* Ignored when streaming is enabled.
*/
private String fileStorageDirectory;
/**
* Character set used to decode headers.
*/
private Charset headersCharset = StandardCharsets.UTF_8;
public DataSize getMaxInMemorySize() {
return this.maxInMemorySize;
}
public void setMaxInMemorySize(DataSize maxInMemorySize) {
this.maxInMemorySize = maxInMemorySize;
}
public DataSize getMaxHeadersSize() {
return this.maxHeadersSize;
}
public void setMaxHeadersSize(DataSize maxHeadersSize) {
this.maxHeadersSize = maxHeadersSize;
}
public DataSize getMaxDiskUsagePerPart() {
return this.maxDiskUsagePerPart;
}
public void setMaxDiskUsagePerPart(DataSize maxDiskUsagePerPart) {
this.maxDiskUsagePerPart = maxDiskUsagePerPart;
}
public Integer getMaxParts() {
return this.maxParts;
}
public void setMaxParts(Integer maxParts) {
this.maxParts = maxParts;
}
public Boolean getStreaming() {
return this.streaming;
}
public void setStreaming(Boolean streaming) {
this.streaming = streaming;
}
public String getFileStorageDirectory() {
return this.fileStorageDirectory;
}
public void setFileStorageDirectory(String fileStorageDirectory) {
this.fileStorageDirectory = fileStorageDirectory;
}
public Charset getHeadersCharset() {
return this.headersCharset;
}
public void setHeadersCharset(Charset headersCharset) {
this.headersCharset = headersCharset;
}
}
|
annstella/Myportfolio | images/Sketch.app/Contents/Frameworks/SketchCloudKit.framework/Versions/A/Headers/SCKCollectionDiff.h | <gh_stars>0
// Created by <NAME> on 06-02-17.
// Copyright © 2017 Bohemian Coding.
#import "SCKDiff.h"
@class SCKObject;
@class SCKArtboard;
@interface SCKCollectionDiff : NSObject <SCKDiff>
- (nonnull instancetype)initWithObject:(nonnull NSArray<SCKObject<SCKDiffable> *> *)object comparedTo:(nonnull NSArray<SCKObject<SCKDiffable> *> *)otherObject;
- (nonnull instancetype)initWithCollectionDiffSet:(nonnull NSSet<SCKCollectionDiff *> *)diffSet;
@property (nonatomic, nonnull, copy, readonly) NSArray<SCKObject<SCKDiffable> *> *object;
@property (nonatomic, nonnull, copy, readonly) NSArray<SCKObject<SCKDiffable> *> *comparedObject;
/// All insertions in the compared collection, relative to the initial collection.
@property (nonatomic, nullable, readonly) NSSet<SCKObject<SCKDiffable> *> *insertions;
/// All updates in the compared collection, relative to the initial collection. Those updates are represented by diffs, so that specific changes for those updates can be retreived.
@property (nonatomic, nullable, readonly) NSSet<id<SCKDiff>> *updateDiffs;
/// All items that were removed from the initial collection, relative to the compared collection.
@property (nonatomic, nullable, readonly) NSSet<SCKObject<SCKDiffable> *> *deletions;
@end
|
GrieferAtWork/deemon | src/deemon/execute/code-exec-targets.c.inl | <filename>src/deemon/execute/code-exec-targets.c.inl
/* Copyright (c) 2018-2021 <EMAIL> *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement (see the following) in the product *
* documentation is required: *
* Portions Copyright (c) 2018-2021 <EMAIL> *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
/*[[[deemon
#include <file>
#include <util>
#include <fs>
fs::chdir(fs::path::head(__FILE__));
local codes = list([none] * 256);
local codes_f0 = list([none] * 256);
for (local l: file.open("../../../include/deemon/asm.h")) {
local name, code;
try name, code = l.scanf(" # define ASM%[^ ] 0x%[0-9a-fA-F]")...;
catch (...) continue;
code = (int)("0x" + code);
if (code <= 256) {
if (codes[code] is none && name !in ["_INC", "_DEC", "_PREFIXMIN", "_PREFIXMAX"])
codes[code] = name;
} else if (code >= 0xf000 && code <= 0xf0ff) {
if (codes_f0[code - 0xf000] is none && name !in ["_INCPOST", "_DECPOST"])
codes_f0[code - 0xf000] = name;
}
}
print "static void *const basic_targets[256] = {";
for (local i, name: util::enumerate(codes)) {
if (name is none || name.startswith("RESERVED")) {
print ("\t/" "* 0x%.2I8x *" "/" % i), "&&unknown_instruction,";
} else {
print ("\t/" "* 0x%.2I8x *" "/" % i), "&&target_ASM" + name + ",";
}
}
print "};";
print "static void *const f0_targets[256] = {";
for (local i, name: util::enumerate(codes_f0)) {
if (name is none || name.startswith("RESERVED")) {
print ("\t/" "* 0x%.2I8x *" "/" % i), "&&unknown_instruction,";
} else {
print ("\t/" "* 0x%.2I8x *" "/" % i), "&&target_ASM" + name + ",";
}
}
print "};";
]]]*/
static void *const basic_targets[256] = {
/* 0x00 */ &&target_ASM_RET_NONE,
/* 0x01 */ &&target_ASM_RET,
/* 0x02 */ &&target_ASM_YIELDALL,
/* 0x03 */ &&target_ASM_THROW,
/* 0x04 */ &&target_ASM_RETHROW,
/* 0x05 */ &&target_ASM_SETRET,
/* 0x06 */ &&target_ASM_ENDCATCH,
/* 0x07 */ &&target_ASM_ENDFINALLY,
/* 0x08 */ &&target_ASM_CALL_KW,
/* 0x09 */ &&target_ASM_CALL_TUPLE_KW,
/* 0x0a */ &&unknown_instruction,
/* 0x0b */ &&target_ASM_PUSH_BND_ARG,
/* 0x0c */ &&target_ASM_PUSH_BND_EXTERN,
/* 0x0d */ &&unknown_instruction,
/* 0x0e */ &&target_ASM_PUSH_BND_GLOBAL,
/* 0x0f */ &&target_ASM_PUSH_BND_LOCAL,
/* 0x10 */ &&target_ASM_JF,
/* 0x11 */ &&target_ASM_JF16,
/* 0x12 */ &&target_ASM_JT,
/* 0x13 */ &&target_ASM_JT16,
/* 0x14 */ &&target_ASM_JMP,
/* 0x15 */ &&target_ASM_JMP16,
/* 0x16 */ &&target_ASM_FOREACH,
/* 0x17 */ &&target_ASM_FOREACH16,
/* 0x18 */ &&target_ASM_JMP_POP,
/* 0x19 */ &&target_ASM_OPERATOR,
/* 0x1a */ &&target_ASM_OPERATOR_TUPLE,
/* 0x1b */ &&target_ASM_CALL,
/* 0x1c */ &&target_ASM_CALL_TUPLE,
/* 0x1d */ &&unknown_instruction,
/* 0x1e */ &&target_ASM_DEL_GLOBAL,
/* 0x1f */ &&target_ASM_DEL_LOCAL,
/* 0x20 */ &&target_ASM_SWAP,
/* 0x21 */ &&target_ASM_LROT,
/* 0x22 */ &&target_ASM_RROT,
/* 0x23 */ &&target_ASM_DUP,
/* 0x24 */ &&target_ASM_DUP_N,
/* 0x25 */ &&target_ASM_POP,
/* 0x26 */ &&target_ASM_POP_N,
/* 0x27 */ &&target_ASM_ADJSTACK,
/* 0x28 */ &&target_ASM_SUPER,
/* 0x29 */ &&target_ASM_SUPER_THIS_R,
/* 0x2a */ &&unknown_instruction,
/* 0x2b */ &&target_ASM_POP_STATIC,
/* 0x2c */ &&target_ASM_POP_EXTERN,
/* 0x2d */ &&unknown_instruction,
/* 0x2e */ &&target_ASM_POP_GLOBAL,
/* 0x2f */ &&target_ASM_POP_LOCAL,
/* 0x30 */ &&unknown_instruction,
/* 0x31 */ &&unknown_instruction,
/* 0x32 */ &&unknown_instruction,
/* 0x33 */ &&target_ASM_PUSH_NONE,
/* 0x34 */ &&target_ASM_PUSH_VARARGS,
/* 0x35 */ &&target_ASM_PUSH_VARKWDS,
/* 0x36 */ &&target_ASM_PUSH_MODULE,
/* 0x37 */ &&target_ASM_PUSH_ARG,
/* 0x38 */ &&target_ASM_PUSH_CONST,
/* 0x39 */ &&target_ASM_PUSH_REF,
/* 0x3a */ &&unknown_instruction,
/* 0x3b */ &&target_ASM_PUSH_STATIC,
/* 0x3c */ &&target_ASM_PUSH_EXTERN,
/* 0x3d */ &&unknown_instruction,
/* 0x3e */ &&target_ASM_PUSH_GLOBAL,
/* 0x3f */ &&target_ASM_PUSH_LOCAL,
/* 0x40 */ &&target_ASM_CAST_TUPLE,
/* 0x41 */ &&target_ASM_CAST_LIST,
/* 0x42 */ &&target_ASM_PACK_TUPLE,
/* 0x43 */ &&target_ASM_PACK_LIST,
/* 0x44 */ &&unknown_instruction,
/* 0x45 */ &&unknown_instruction,
/* 0x46 */ &&target_ASM_UNPACK,
/* 0x47 */ &&target_ASM_CONCAT,
/* 0x48 */ &&target_ASM_EXTEND,
/* 0x49 */ &&target_ASM_TYPEOF,
/* 0x4a */ &&target_ASM_CLASSOF,
/* 0x4b */ &&target_ASM_SUPEROF,
/* 0x4c */ &&target_ASM_INSTANCEOF,
/* 0x4d */ &&target_ASM_STR,
/* 0x4e */ &&target_ASM_REPR,
/* 0x4f */ &&unknown_instruction,
/* 0x50 */ &&target_ASM_BOOL,
/* 0x51 */ &&target_ASM_NOT,
/* 0x52 */ &&target_ASM_ASSIGN,
/* 0x53 */ &&target_ASM_MOVE_ASSIGN,
/* 0x54 */ &&target_ASM_COPY,
/* 0x55 */ &&target_ASM_DEEPCOPY,
/* 0x56 */ &&target_ASM_GETATTR,
/* 0x57 */ &&target_ASM_DELATTR,
/* 0x58 */ &&target_ASM_SETATTR,
/* 0x59 */ &&target_ASM_BOUNDATTR,
/* 0x5a */ &&target_ASM_GETATTR_C,
/* 0x5b */ &&target_ASM_DELATTR_C,
/* 0x5c */ &&target_ASM_SETATTR_C,
/* 0x5d */ &&target_ASM_GETATTR_THIS_C,
/* 0x5e */ &&target_ASM_DELATTR_THIS_C,
/* 0x5f */ &&target_ASM_SETATTR_THIS_C,
/* 0x60 */ &&target_ASM_CMP_EQ,
/* 0x61 */ &&target_ASM_CMP_NE,
/* 0x62 */ &&target_ASM_CMP_GE,
/* 0x63 */ &&target_ASM_CMP_LO,
/* 0x64 */ &&target_ASM_CMP_LE,
/* 0x65 */ &&target_ASM_CMP_GR,
/* 0x66 */ &&target_ASM_CLASS_C,
/* 0x67 */ &&target_ASM_CLASS_GC,
/* 0x68 */ &&target_ASM_CLASS_EC,
/* 0x69 */ &&target_ASM_DEFCMEMBER,
/* 0x6a */ &&target_ASM_GETCMEMBER_R,
/* 0x6b */ &&target_ASM_CALLCMEMBER_THIS_R,
/* 0x6c */ &&unknown_instruction,
/* 0x6d */ &&unknown_instruction,
/* 0x6e */ &&target_ASM_FUNCTION_C,
/* 0x6f */ &&target_ASM_FUNCTION_C_16,
/* 0x70 */ &&target_ASM_CAST_INT,
/* 0x71 */ &&target_ASM_INV,
/* 0x72 */ &&target_ASM_POS,
/* 0x73 */ &&target_ASM_NEG,
/* 0x74 */ &&target_ASM_ADD,
/* 0x75 */ &&target_ASM_SUB,
/* 0x76 */ &&target_ASM_MUL,
/* 0x77 */ &&target_ASM_DIV,
/* 0x78 */ &&target_ASM_MOD,
/* 0x79 */ &&target_ASM_SHL,
/* 0x7a */ &&target_ASM_SHR,
/* 0x7b */ &&target_ASM_AND,
/* 0x7c */ &&target_ASM_OR,
/* 0x7d */ &&target_ASM_XOR,
/* 0x7e */ &&target_ASM_POW,
/* 0x7f */ &&unknown_instruction,
/* 0x80 */ &&unknown_instruction,
/* 0x81 */ &&target_ASM_ADD_SIMM8,
/* 0x82 */ &&target_ASM_ADD_IMM32,
/* 0x83 */ &&target_ASM_SUB_SIMM8,
/* 0x84 */ &&target_ASM_SUB_IMM32,
/* 0x85 */ &&target_ASM_MUL_SIMM8,
/* 0x86 */ &&target_ASM_DIV_SIMM8,
/* 0x87 */ &&target_ASM_MOD_SIMM8,
/* 0x88 */ &&target_ASM_SHL_IMM8,
/* 0x89 */ &&target_ASM_SHR_IMM8,
/* 0x8a */ &&target_ASM_AND_IMM32,
/* 0x8b */ &&target_ASM_OR_IMM32,
/* 0x8c */ &&target_ASM_XOR_IMM32,
/* 0x8d */ &&target_ASM_ISNONE,
/* 0x8e */ &&unknown_instruction,
/* 0x8f */ &&target_ASM_DELOP,
/* 0x90 */ &&target_ASM_NOP,
/* 0x91 */ &&target_ASM_PRINT,
/* 0x92 */ &&target_ASM_PRINT_SP,
/* 0x93 */ &&target_ASM_PRINT_NL,
/* 0x94 */ &&target_ASM_PRINTNL,
/* 0x95 */ &&target_ASM_PRINTALL,
/* 0x96 */ &&target_ASM_PRINTALL_SP,
/* 0x97 */ &&target_ASM_PRINTALL_NL,
/* 0x98 */ &&unknown_instruction,
/* 0x99 */ &&target_ASM_FPRINT,
/* 0x9a */ &&target_ASM_FPRINT_SP,
/* 0x9b */ &&target_ASM_FPRINT_NL,
/* 0x9c */ &&target_ASM_FPRINTNL,
/* 0x9d */ &&target_ASM_FPRINTALL,
/* 0x9e */ &&target_ASM_FPRINTALL_SP,
/* 0x9f */ &&target_ASM_FPRINTALL_NL,
/* 0xa0 */ &&unknown_instruction,
/* 0xa1 */ &&target_ASM_PRINT_C,
/* 0xa2 */ &&target_ASM_PRINT_C_SP,
/* 0xa3 */ &&target_ASM_PRINT_C_NL,
/* 0xa4 */ &&target_ASM_RANGE_0_I16,
/* 0xa5 */ &&unknown_instruction,
/* 0xa6 */ &&target_ASM_ENTER,
/* 0xa7 */ &&target_ASM_LEAVE,
/* 0xa8 */ &&unknown_instruction,
/* 0xa9 */ &&target_ASM_FPRINT_C,
/* 0xaa */ &&target_ASM_FPRINT_C_SP,
/* 0xab */ &&target_ASM_FPRINT_C_NL,
/* 0xac */ &&target_ASM_RANGE,
/* 0xad */ &&target_ASM_RANGE_DEF,
/* 0xae */ &&target_ASM_RANGE_STEP,
/* 0xaf */ &&target_ASM_RANGE_STEP_DEF,
/* 0xb0 */ &&target_ASM_CONTAINS,
/* 0xb1 */ &&target_ASM_CONTAINS_C,
/* 0xb2 */ &&target_ASM_GETITEM,
/* 0xb3 */ &&target_ASM_GETITEM_I,
/* 0xb4 */ &&target_ASM_GETITEM_C,
/* 0xb5 */ &&target_ASM_GETSIZE,
/* 0xb6 */ &&target_ASM_SETITEM,
/* 0xb7 */ &&target_ASM_SETITEM_I,
/* 0xb8 */ &&target_ASM_SETITEM_C,
/* 0xb9 */ &&target_ASM_ITERSELF,
/* 0xba */ &&target_ASM_DELITEM,
/* 0xbb */ &&target_ASM_GETRANGE,
/* 0xbc */ &&target_ASM_GETRANGE_PN,
/* 0xbd */ &&target_ASM_GETRANGE_NP,
/* 0xbe */ &&target_ASM_GETRANGE_PI,
/* 0xbf */ &&target_ASM_GETRANGE_IP,
/* 0xc0 */ &&target_ASM_GETRANGE_NI,
/* 0xc1 */ &&target_ASM_GETRANGE_IN,
/* 0xc2 */ &&target_ASM_GETRANGE_II,
/* 0xc3 */ &&target_ASM_DELRANGE,
/* 0xc4 */ &&target_ASM_SETRANGE,
/* 0xc5 */ &&target_ASM_SETRANGE_PN,
/* 0xc6 */ &&target_ASM_SETRANGE_NP,
/* 0xc7 */ &&target_ASM_SETRANGE_PI,
/* 0xc8 */ &&target_ASM_SETRANGE_IP,
/* 0xc9 */ &&target_ASM_SETRANGE_NI,
/* 0xca */ &&target_ASM_SETRANGE_IN,
/* 0xcb */ &&target_ASM_SETRANGE_II,
/* 0xcc */ &&target_ASM_BREAKPOINT,
/* 0xcd */ &&target_ASM_UD,
/* 0xce */ &&target_ASM_CALLATTR_C_KW,
/* 0xcf */ &&target_ASM_CALLATTR_C_TUPLE_KW,
/* 0xd0 */ &&target_ASM_CALLATTR,
/* 0xd1 */ &&target_ASM_CALLATTR_TUPLE,
/* 0xd2 */ &&target_ASM_CALLATTR_C,
/* 0xd3 */ &&target_ASM_CALLATTR_C_TUPLE,
/* 0xd4 */ &&target_ASM_CALLATTR_THIS_C,
/* 0xd5 */ &&target_ASM_CALLATTR_THIS_C_TUPLE,
/* 0xd6 */ &&target_ASM_CALLATTR_C_SEQ,
/* 0xd7 */ &&target_ASM_CALLATTR_C_MAP,
/* 0xd8 */ &&unknown_instruction,
/* 0xd9 */ &&target_ASM_GETMEMBER_THIS_R,
/* 0xda */ &&target_ASM_DELMEMBER_THIS_R,
/* 0xdb */ &&target_ASM_SETMEMBER_THIS_R,
/* 0xdc */ &&target_ASM_BOUNDMEMBER_THIS_R,
/* 0xdd */ &&target_ASM_CALL_EXTERN,
/* 0xde */ &&target_ASM_CALL_GLOBAL,
/* 0xdf */ &&target_ASM_CALL_LOCAL,
/* 0xe0 */ &&unknown_instruction,
/* 0xe1 */ &&unknown_instruction,
/* 0xe2 */ &&unknown_instruction,
/* 0xe3 */ &&unknown_instruction,
/* 0xe4 */ &&unknown_instruction,
/* 0xe5 */ &&unknown_instruction,
/* 0xe6 */ &&unknown_instruction,
/* 0xe7 */ &&unknown_instruction,
/* 0xe8 */ &&unknown_instruction,
/* 0xe9 */ &&unknown_instruction,
/* 0xea */ &&unknown_instruction,
/* 0xeb */ &&unknown_instruction,
/* 0xec */ &&unknown_instruction,
/* 0xed */ &&unknown_instruction,
/* 0xee */ &&unknown_instruction,
/* 0xef */ &&unknown_instruction,
/* 0xf0 */ &&target_ASM_EXTENDED1,
/* 0xf1 */ &&target_ASM_RESERVED1,
/* 0xf2 */ &&target_ASM_RESERVED2,
/* 0xf3 */ &&target_ASM_RESERVED3,
/* 0xf4 */ &&target_ASM_RESERVED4,
/* 0xf5 */ &&target_ASM_RESERVED5,
/* 0xf6 */ &&target_ASM_RESERVED6,
/* 0xf7 */ &&target_ASM_RESERVED7,
/* 0xf8 */ &&unknown_instruction,
/* 0xf9 */ &&unknown_instruction,
/* 0xfa */ &&target_ASM_STACK,
/* 0xfb */ &&target_ASM_STATIC,
/* 0xfc */ &&target_ASM_EXTERN,
/* 0xfd */ &&unknown_instruction,
/* 0xfe */ &&target_ASM_GLOBAL,
/* 0xff */ &&target_ASM_LOCAL,
};
static void *const f0_targets[256] = {
/* 0x00 */ &&unknown_instruction,
/* 0x01 */ &&unknown_instruction,
/* 0x02 */ &&unknown_instruction,
/* 0x03 */ &&unknown_instruction,
/* 0x04 */ &&unknown_instruction,
/* 0x05 */ &&unknown_instruction,
/* 0x06 */ &&target_ASM_ENDCATCH_N,
/* 0x07 */ &&target_ASM_ENDFINALLY_N,
/* 0x08 */ &&target_ASM16_CALL_KW,
/* 0x09 */ &&target_ASM16_CALL_TUPLE_KW,
/* 0x0a */ &&unknown_instruction,
/* 0x0b */ &&target_ASM16_PUSH_BND_ARG,
/* 0x0c */ &&target_ASM16_PUSH_BND_EXTERN,
/* 0x0d */ &&unknown_instruction,
/* 0x0e */ &&target_ASM16_PUSH_BND_GLOBAL,
/* 0x0f */ &&target_ASM16_PUSH_BND_LOCAL,
/* 0x10 */ &&unknown_instruction,
/* 0x11 */ &&unknown_instruction,
/* 0x12 */ &&unknown_instruction,
/* 0x13 */ &&unknown_instruction,
/* 0x14 */ &&target_ASM32_JMP,
/* 0x15 */ &&unknown_instruction,
/* 0x16 */ &&unknown_instruction,
/* 0x17 */ &&unknown_instruction,
/* 0x18 */ &&target_ASM_JMP_POP_POP,
/* 0x19 */ &&target_ASM16_OPERATOR,
/* 0x1a */ &&target_ASM16_OPERATOR_TUPLE,
/* 0x1b */ &&target_ASM_CALL_SEQ,
/* 0x1c */ &&target_ASM_CALL_MAP,
/* 0x1d */ &&target_ASM_THISCALL_TUPLE,
/* 0x1e */ &&target_ASM16_DEL_GLOBAL,
/* 0x1f */ &&target_ASM16_DEL_LOCAL,
/* 0x20 */ &&target_ASM_CALL_TUPLE_KWDS,
/* 0x21 */ &&target_ASM16_LROT,
/* 0x22 */ &&target_ASM16_RROT,
/* 0x23 */ &&unknown_instruction,
/* 0x24 */ &&target_ASM16_DUP_N,
/* 0x25 */ &&unknown_instruction,
/* 0x26 */ &&target_ASM16_POP_N,
/* 0x27 */ &&target_ASM16_ADJSTACK,
/* 0x28 */ &&unknown_instruction,
/* 0x29 */ &&target_ASM16_SUPER_THIS_R,
/* 0x2a */ &&unknown_instruction,
/* 0x2b */ &&target_ASM16_POP_STATIC,
/* 0x2c */ &&target_ASM16_POP_EXTERN,
/* 0x2d */ &&unknown_instruction,
/* 0x2e */ &&target_ASM16_POP_GLOBAL,
/* 0x2f */ &&target_ASM16_POP_LOCAL,
/* 0x30 */ &&unknown_instruction,
/* 0x31 */ &&unknown_instruction,
/* 0x32 */ &&target_ASM_PUSH_EXCEPT,
/* 0x33 */ &&target_ASM_PUSH_THIS,
/* 0x34 */ &&target_ASM_PUSH_THIS_MODULE,
/* 0x35 */ &&target_ASM_PUSH_THIS_FUNCTION,
/* 0x36 */ &&target_ASM16_PUSH_MODULE,
/* 0x37 */ &&target_ASM16_PUSH_ARG,
/* 0x38 */ &&target_ASM16_PUSH_CONST,
/* 0x39 */ &&target_ASM16_PUSH_REF,
/* 0x3a */ &&unknown_instruction,
/* 0x3b */ &&target_ASM16_PUSH_STATIC,
/* 0x3c */ &&target_ASM16_PUSH_EXTERN,
/* 0x3d */ &&unknown_instruction,
/* 0x3e */ &&target_ASM16_PUSH_GLOBAL,
/* 0x3f */ &&target_ASM16_PUSH_LOCAL,
/* 0x40 */ &&target_ASM_CAST_HASHSET,
/* 0x41 */ &&target_ASM_CAST_DICT,
/* 0x42 */ &&target_ASM16_PACK_TUPLE,
/* 0x43 */ &&target_ASM16_PACK_LIST,
/* 0x44 */ &&unknown_instruction,
/* 0x45 */ &&unknown_instruction,
/* 0x46 */ &&target_ASM16_UNPACK,
/* 0x47 */ &&unknown_instruction,
/* 0x48 */ &&unknown_instruction,
/* 0x49 */ &&unknown_instruction,
/* 0x4a */ &&unknown_instruction,
/* 0x4b */ &&unknown_instruction,
/* 0x4c */ &&unknown_instruction,
/* 0x4d */ &&unknown_instruction,
/* 0x4e */ &&unknown_instruction,
/* 0x4f */ &&unknown_instruction,
/* 0x50 */ &&target_ASM_PUSH_TRUE,
/* 0x51 */ &&target_ASM_PUSH_FALSE,
/* 0x52 */ &&target_ASM_PACK_HASHSET,
/* 0x53 */ &&target_ASM_PACK_DICT,
/* 0x54 */ &&unknown_instruction,
/* 0x55 */ &&unknown_instruction,
/* 0x56 */ &&unknown_instruction,
/* 0x57 */ &&unknown_instruction,
/* 0x58 */ &&unknown_instruction,
/* 0x59 */ &&target_ASM_BOUNDITEM,
/* 0x5a */ &&target_ASM16_GETATTR_C,
/* 0x5b */ &&target_ASM16_DELATTR_C,
/* 0x5c */ &&target_ASM16_SETATTR_C,
/* 0x5d */ &&target_ASM16_GETATTR_THIS_C,
/* 0x5e */ &&target_ASM16_DELATTR_THIS_C,
/* 0x5f */ &&target_ASM16_SETATTR_THIS_C,
/* 0x60 */ &&target_ASM_CMP_SO,
/* 0x61 */ &&target_ASM_CMP_DO,
/* 0x62 */ &&target_ASM16_PACK_HASHSET,
/* 0x63 */ &&target_ASM16_PACK_DICT,
/* 0x64 */ &&target_ASM16_GETCMEMBER,
/* 0x65 */ &&target_ASM_CLASS,
/* 0x66 */ &&target_ASM16_CLASS_C,
/* 0x67 */ &&target_ASM16_CLASS_GC,
/* 0x68 */ &&target_ASM16_CLASS_EC,
/* 0x69 */ &&target_ASM16_DEFCMEMBER,
/* 0x6a */ &&target_ASM16_GETCMEMBER_R,
/* 0x6b */ &&target_ASM16_CALLCMEMBER_THIS_R,
/* 0x6c */ &&unknown_instruction,
/* 0x6d */ &&unknown_instruction,
/* 0x6e */ &&target_ASM16_FUNCTION_C,
/* 0x6f */ &&target_ASM16_FUNCTION_C_16,
/* 0x70 */ &&target_ASM_SUPERGETATTR_THIS_RC,
/* 0x71 */ &&target_ASM16_SUPERGETATTR_THIS_RC,
/* 0x72 */ &&target_ASM_SUPERCALLATTR_THIS_RC,
/* 0x73 */ &&target_ASM16_SUPERCALLATTR_THIS_RC,
/* 0x74 */ &&unknown_instruction,
/* 0x75 */ &&unknown_instruction,
/* 0x76 */ &&unknown_instruction,
/* 0x77 */ &&unknown_instruction,
/* 0x78 */ &&unknown_instruction,
/* 0x79 */ &&unknown_instruction,
/* 0x7a */ &&unknown_instruction,
/* 0x7b */ &&unknown_instruction,
/* 0x7c */ &&unknown_instruction,
/* 0x7d */ &&unknown_instruction,
/* 0x7e */ &&unknown_instruction,
/* 0x7f */ &&unknown_instruction,
/* 0x80 */ &&unknown_instruction,
/* 0x81 */ &&unknown_instruction,
/* 0x82 */ &&unknown_instruction,
/* 0x83 */ &&unknown_instruction,
/* 0x84 */ &&unknown_instruction,
/* 0x85 */ &&unknown_instruction,
/* 0x86 */ &&unknown_instruction,
/* 0x87 */ &&unknown_instruction,
/* 0x88 */ &&unknown_instruction,
/* 0x89 */ &&unknown_instruction,
/* 0x8a */ &&unknown_instruction,
/* 0x8b */ &&unknown_instruction,
/* 0x8c */ &&unknown_instruction,
/* 0x8d */ &&unknown_instruction,
/* 0x8e */ &&unknown_instruction,
/* 0x8f */ &&target_ASM16_DELOP,
/* 0x90 */ &&target_ASM16_NOP,
/* 0x91 */ &&target_ASM_REDUCE_MIN,
/* 0x92 */ &&target_ASM_REDUCE_MAX,
/* 0x93 */ &&target_ASM_REDUCE_SUM,
/* 0x94 */ &&target_ASM_REDUCE_ANY,
/* 0x95 */ &&target_ASM_REDUCE_ALL,
/* 0x96 */ &&unknown_instruction,
/* 0x97 */ &&unknown_instruction,
/* 0x98 */ &&unknown_instruction,
/* 0x99 */ &&unknown_instruction,
/* 0x9a */ &&unknown_instruction,
/* 0x9b */ &&unknown_instruction,
/* 0x9c */ &&unknown_instruction,
/* 0x9d */ &&unknown_instruction,
/* 0x9e */ &&unknown_instruction,
/* 0x9f */ &&unknown_instruction,
/* 0xa0 */ &&unknown_instruction,
/* 0xa1 */ &&target_ASM16_PRINT_C,
/* 0xa2 */ &&target_ASM16_PRINT_C_SP,
/* 0xa3 */ &&target_ASM16_PRINT_C_NL,
/* 0xa4 */ &&target_ASM_RANGE_0_I32,
/* 0xa5 */ &&unknown_instruction,
/* 0xa6 */ &&target_ASM_VARARGS_UNPACK,
/* 0xa7 */ &&target_ASM_PUSH_VARKWDS_NE,
/* 0xa8 */ &&unknown_instruction,
/* 0xa9 */ &&target_ASM16_FPRINT_C,
/* 0xaa */ &&target_ASM16_FPRINT_C_SP,
/* 0xab */ &&target_ASM16_FPRINT_C_NL,
/* 0xac */ &&target_ASM_VARARGS_CMP_EQ_SZ,
/* 0xad */ &&target_ASM_VARARGS_CMP_GR_SZ,
/* 0xae */ &&unknown_instruction,
/* 0xaf */ &&unknown_instruction,
/* 0xb0 */ &&unknown_instruction,
/* 0xb1 */ &&target_ASM16_CONTAINS_C,
/* 0xb2 */ &&target_ASM_VARARGS_GETITEM,
/* 0xb3 */ &&target_ASM_VARARGS_GETITEM_I,
/* 0xb4 */ &&target_ASM16_GETITEM_C,
/* 0xb5 */ &&target_ASM_VARARGS_GETSIZE,
/* 0xb6 */ &&unknown_instruction,
/* 0xb7 */ &&unknown_instruction,
/* 0xb8 */ &&target_ASM16_SETITEM_C,
/* 0xb9 */ &&target_ASM_ITERNEXT,
/* 0xba */ &&unknown_instruction,
/* 0xbb */ &&unknown_instruction,
/* 0xbc */ &&unknown_instruction,
/* 0xbd */ &&unknown_instruction,
/* 0xbe */ &&target_ASM_GETMEMBER,
/* 0xbf */ &&target_ASM16_GETMEMBER,
/* 0xc0 */ &&target_ASM_DELMEMBER,
/* 0xc1 */ &&target_ASM16_DELMEMBER,
/* 0xc2 */ &&target_ASM_SETMEMBER,
/* 0xc3 */ &&target_ASM16_SETMEMBER,
/* 0xc4 */ &&target_ASM_BOUNDMEMBER,
/* 0xc5 */ &&target_ASM16_BOUNDMEMBER,
/* 0xc6 */ &&target_ASM_GETMEMBER_THIS,
/* 0xc7 */ &&target_ASM16_GETMEMBER_THIS,
/* 0xc8 */ &&target_ASM_DELMEMBER_THIS,
/* 0xc9 */ &&target_ASM16_DELMEMBER_THIS,
/* 0xca */ &&target_ASM_SETMEMBER_THIS,
/* 0xcb */ &&target_ASM16_SETMEMBER_THIS,
/* 0xcc */ &&target_ASM_BOUNDMEMBER_THIS,
/* 0xcd */ &&target_ASM16_BOUNDMEMBER_THIS,
/* 0xce */ &&target_ASM16_CALLATTR_C_KW,
/* 0xcf */ &&target_ASM16_CALLATTR_C_TUPLE_KW,
/* 0xd0 */ &&target_ASM_CALLATTR_KWDS,
/* 0xd1 */ &&target_ASM_CALLATTR_TUPLE_KWDS,
/* 0xd2 */ &&target_ASM16_CALLATTR_C,
/* 0xd3 */ &&target_ASM16_CALLATTR_C_TUPLE,
/* 0xd4 */ &&target_ASM16_CALLATTR_THIS_C,
/* 0xd5 */ &&target_ASM16_CALLATTR_THIS_C_TUPLE,
/* 0xd6 */ &&target_ASM16_CALLATTR_C_SEQ,
/* 0xd7 */ &&target_ASM16_CALLATTR_C_MAP,
/* 0xd8 */ &&unknown_instruction,
/* 0xd9 */ &&target_ASM16_GETMEMBER_THIS_R,
/* 0xda */ &&target_ASM16_DELMEMBER_THIS_R,
/* 0xdb */ &&target_ASM16_SETMEMBER_THIS_R,
/* 0xdc */ &&target_ASM16_BOUNDMEMBER_THIS_R,
/* 0xdd */ &&target_ASM16_CALL_EXTERN,
/* 0xde */ &&target_ASM16_CALL_GLOBAL,
/* 0xdf */ &&target_ASM16_CALL_LOCAL,
/* 0xe0 */ &&unknown_instruction,
/* 0xe1 */ &&unknown_instruction,
/* 0xe2 */ &&unknown_instruction,
/* 0xe3 */ &&unknown_instruction,
/* 0xe4 */ &&unknown_instruction,
/* 0xe5 */ &&unknown_instruction,
/* 0xe6 */ &&unknown_instruction,
/* 0xe7 */ &&unknown_instruction,
/* 0xe8 */ &&unknown_instruction,
/* 0xe9 */ &&unknown_instruction,
/* 0xea */ &&unknown_instruction,
/* 0xeb */ &&unknown_instruction,
/* 0xec */ &&unknown_instruction,
/* 0xed */ &&unknown_instruction,
/* 0xee */ &&unknown_instruction,
/* 0xef */ &&unknown_instruction,
/* 0xf0 */ &&unknown_instruction,
/* 0xf1 */ &&unknown_instruction,
/* 0xf2 */ &&unknown_instruction,
/* 0xf3 */ &&unknown_instruction,
/* 0xf4 */ &&unknown_instruction,
/* 0xf5 */ &&unknown_instruction,
/* 0xf6 */ &&unknown_instruction,
/* 0xf7 */ &&unknown_instruction,
/* 0xf8 */ &&unknown_instruction,
/* 0xf9 */ &&unknown_instruction,
/* 0xfa */ &&target_ASM16_STACK,
/* 0xfb */ &&target_ASM16_STATIC,
/* 0xfc */ &&target_ASM16_EXTERN,
/* 0xfd */ &&unknown_instruction,
/* 0xfe */ &&target_ASM16_GLOBAL,
/* 0xff */ &&target_ASM16_LOCAL,
};
//[[[end]]]
|
Levi-Armstrong/ign-rendering | src/MeshDescriptor.cc | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* 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 <ignition/common/Console.hh>
#include <ignition/common/Mesh.hh>
#include <ignition/common/MeshManager.hh>
#include "ignition/rendering/MeshDescriptor.hh"
using namespace ignition;
using namespace rendering;
//////////////////////////////////////////////////
MeshDescriptor::MeshDescriptor()
{
}
//////////////////////////////////////////////////
MeshDescriptor::MeshDescriptor(const std::string &_meshName) :
meshName(_meshName)
{
}
//////////////////////////////////////////////////
MeshDescriptor::MeshDescriptor(const common::Mesh *_mesh) :
mesh(_mesh)
{
}
//////////////////////////////////////////////////
void MeshDescriptor::Load()
{
if (this->mesh)
{
this->meshName = this->mesh->Name();
}
else if (!this->meshName.empty())
{
this->mesh = common::MeshManager::Instance()->MeshByName(this->meshName);
if (!this->mesh)
{
ignerr << "Mesh manager can't find mesh named [" << this->meshName << "]"
<< std::endl;
}
}
else
{
ignerr << "Missing mesh or mesh name" << std::endl;
}
}
|
plagoa/big-data-plugin | impl/shim/mapreduce/src/test/java/org/pentaho/big/data/impl/shim/mapreduce/RunningJobMapReduceJobAdvancedImplTest.java | <filename>impl/shim/mapreduce/src/test/java/org/pentaho/big/data/impl/shim/mapreduce/RunningJobMapReduceJobAdvancedImplTest.java
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by <NAME> : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.impl.shim.mapreduce;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.bigdata.api.mapreduce.MapReduceService;
import org.pentaho.hadoop.shim.api.mapred.RunningJob;
import org.pentaho.hadoop.shim.api.mapred.TaskCompletionEvent;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created by bryan on 12/8/15.
*/
public class RunningJobMapReduceJobAdvancedImplTest {
private RunningJob runningJob;
private RunningJobMapReduceJobAdvancedImpl runningJobMapReduceJobAdvanced;
private MapReduceService.Stoppable stoppable;
@Before
public void setup() {
runningJob = mock( RunningJob.class );
runningJobMapReduceJobAdvanced = new RunningJobMapReduceJobAdvancedImpl( runningJob );
stoppable = mock( MapReduceService.Stoppable.class );
}
@Test
public void testKillJob() throws IOException {
runningJobMapReduceJobAdvanced.killJob();
verify( runningJob ).killJob();
}
@Test( timeout = 500 )
public void testWaitOnConCompletionStopped() throws IOException, InterruptedException {
when( stoppable.isStopped() ).thenReturn( true );
assertFalse( runningJobMapReduceJobAdvanced.waitOnCompletion( 10, TimeUnit.MINUTES, stoppable ) );
}
@Test( timeout = 500 )
public void testWaitOnCompletionFalse() throws IOException, InterruptedException {
assertFalse( runningJobMapReduceJobAdvanced.waitOnCompletion( 10, TimeUnit.MILLISECONDS, stoppable ) );
}
@Test( timeout = 500 )
public void testWaitOnCompletionCompleteBeforeSleep() throws IOException, InterruptedException {
when( runningJob.isComplete() ).thenReturn( true );
assertTrue( runningJobMapReduceJobAdvanced.waitOnCompletion( 10, TimeUnit.MILLISECONDS, stoppable ) );
}
@Test( timeout = 500 )
public void testWaitOnCompletionCompleteAfterSleep() throws IOException, InterruptedException {
when( runningJob.isComplete() ).thenReturn( false, true );
assertTrue( runningJobMapReduceJobAdvanced.waitOnCompletion( 10, TimeUnit.MILLISECONDS, stoppable ) );
}
@Test
public void testGetSetupProgress() throws IOException {
float setupProgress = 1.25f;
when( runningJob.setupProgress() ).thenReturn( setupProgress );
assertEquals( setupProgress, runningJobMapReduceJobAdvanced.getSetupProgress(), 0 );
}
@Test
public void testGetMapProgress() throws IOException {
float mapProgress = 1.25f;
when( runningJob.mapProgress() ).thenReturn( mapProgress );
assertEquals( mapProgress, runningJobMapReduceJobAdvanced.getMapProgress(), 0 );
}
@Test
public void testGetReduceProgress() throws IOException {
float reduceProgress = 1.25f;
when( runningJob.reduceProgress() ).thenReturn( reduceProgress );
assertEquals( reduceProgress, runningJobMapReduceJobAdvanced.getReduceProgress(), 0 );
}
@Test
public void testIsSuccessful() throws IOException {
when( runningJob.isSuccessful() ).thenReturn( true, false );
assertTrue( runningJobMapReduceJobAdvanced.isSuccessful() );
assertFalse( runningJobMapReduceJobAdvanced.isSuccessful() );
}
@Test
public void testIsComplete() throws IOException {
when( runningJob.isComplete() ).thenReturn( true, false );
assertTrue( runningJobMapReduceJobAdvanced.isComplete() );
assertFalse( runningJobMapReduceJobAdvanced.isComplete() );
}
@Test
public void testGetTaskCompletionEvents() throws IOException {
int id = 256;
TaskCompletionEvent taskCompletionEvent = mock( TaskCompletionEvent.class );
when( runningJob.getTaskCompletionEvents( 1 ) )
.thenReturn( new TaskCompletionEvent[] { taskCompletionEvent } );
when( taskCompletionEvent.getEventId() ).thenReturn( id );
org.pentaho.bigdata.api.mapreduce.TaskCompletionEvent[] taskCompletionEvents =
runningJobMapReduceJobAdvanced.getTaskCompletionEvents( 1 );
assertEquals( 1, taskCompletionEvents.length );
assertEquals( id, taskCompletionEvents[ 0 ].getEventId() );
}
@Test
public void testGetTaskDiagnostics() throws IOException {
Object o = new Object();
String[] value = { "diag" };
when( runningJob.getTaskDiagnostics( o ) ).thenReturn( value );
assertArrayEquals( value, runningJobMapReduceJobAdvanced.getTaskDiagnostics( o ) );
}
}
|
krattai/AEBL | blades/floreantpos-code/src/com/floreantpos/model/base/BaseCurrency.java | <gh_stars>1-10
package com.floreantpos.model.base;
import java.lang.Comparable;
import java.io.Serializable;
/**
* This is an object that contains data related to the CURRENCY table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table="CURRENCY"
*/
public abstract class BaseCurrency implements Comparable, Serializable {
public static String REF = "Currency";
public static String PROP_SALES_PRICE = "salesPrice";
public static String PROP_BUY_PRICE = "buyPrice";
public static String PROP_NAME = "name";
public static String PROP_MAIN = "main";
public static String PROP_TOLERANCE = "tolerance";
public static String PROP_EXCHANGE_RATE = "exchangeRate";
public static String PROP_SYMBOL = "symbol";
public static String PROP_ID = "id";
public static String PROP_CODE = "code";
// constructors
public BaseCurrency () {
initialize();
}
/**
* Constructor for primary key
*/
public BaseCurrency (java.lang.Integer id) {
this.setId(id);
initialize();
}
protected void initialize () {}
private int hashCode = Integer.MIN_VALUE;
// primary key
private java.lang.Integer id;
// fields
protected java.lang.String code;
protected java.lang.String name;
protected java.lang.String symbol;
protected java.lang.Double exchangeRate;
protected java.lang.Double tolerance;
protected java.lang.Double buyPrice;
protected java.lang.Double salesPrice;
protected java.lang.Boolean main;
/**
* Return the unique identifier of this class
* @hibernate.id
* generator-class="identity"
* column="ID"
*/
public java.lang.Integer getId () {
return id;
}
/**
* Set the unique identifier of this class
* @param id the new ID
*/
public void setId (java.lang.Integer id) {
this.id = id;
this.hashCode = Integer.MIN_VALUE;
}
/**
* Return the value associated with the column: CODE
*/
public java.lang.String getCode () {
return code;
}
/**
* Set the value related to the column: CODE
* @param code the CODE value
*/
public void setCode (java.lang.String code) {
this.code = code;
}
/**
* Return the value associated with the column: NAME
*/
public java.lang.String getName () {
return name;
}
/**
* Set the value related to the column: NAME
* @param name the NAME value
*/
public void setName (java.lang.String name) {
this.name = name;
}
/**
* Return the value associated with the column: SYMBOL
*/
public java.lang.String getSymbol () {
return symbol;
}
/**
* Set the value related to the column: SYMBOL
* @param symbol the SYMBOL value
*/
public void setSymbol (java.lang.String symbol) {
this.symbol = symbol;
}
/**
* Return the value associated with the column: EXCHANGE_RATE
*/
public java.lang.Double getExchangeRate () {
return exchangeRate == null ? Double.valueOf(1) : exchangeRate;
}
/**
* Set the value related to the column: EXCHANGE_RATE
* @param exchangeRate the EXCHANGE_RATE value
*/
public void setExchangeRate (java.lang.Double exchangeRate) {
this.exchangeRate = exchangeRate;
}
/**
* Custom property
*/
public static String getExchangeRateDefaultValue () {
return "1";
}
/**
* Return the value associated with the column: TOLERANCE
*/
public java.lang.Double getTolerance () {
return tolerance == null ? Double.valueOf(0) : tolerance;
}
/**
* Set the value related to the column: TOLERANCE
* @param tolerance the TOLERANCE value
*/
public void setTolerance (java.lang.Double tolerance) {
this.tolerance = tolerance;
}
/**
* Return the value associated with the column: BUY_PRICE
*/
public java.lang.Double getBuyPrice () {
return buyPrice == null ? Double.valueOf(0) : buyPrice;
}
/**
* Set the value related to the column: BUY_PRICE
* @param buyPrice the BUY_PRICE value
*/
public void setBuyPrice (java.lang.Double buyPrice) {
this.buyPrice = buyPrice;
}
/**
* Return the value associated with the column: SALES_PRICE
*/
public java.lang.Double getSalesPrice () {
return salesPrice == null ? Double.valueOf(0) : salesPrice;
}
/**
* Set the value related to the column: SALES_PRICE
* @param salesPrice the SALES_PRICE value
*/
public void setSalesPrice (java.lang.Double salesPrice) {
this.salesPrice = salesPrice;
}
/**
* Return the value associated with the column: MAIN
*/
public java.lang.Boolean isMain () {
return main == null ? Boolean.FALSE : main;
}
/**
* Set the value related to the column: MAIN
* @param main the MAIN value
*/
public void setMain (java.lang.Boolean main) {
this.main = main;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof com.floreantpos.model.Currency)) return false;
else {
com.floreantpos.model.Currency currency = (com.floreantpos.model.Currency) obj;
if (null == this.getId() || null == currency.getId()) return false;
else return (this.getId().equals(currency.getId()));
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
if (null == this.getId()) return super.hashCode();
else {
String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
public int compareTo (Object obj) {
if (obj.hashCode() > hashCode()) return 1;
else if (obj.hashCode() < hashCode()) return -1;
else return 0;
}
public String toString () {
return super.toString();
}
} |
wardat/apache-ant-1.6.2 | src/main/org/apache/tools/ant/launch/Locator.java | /*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.launch;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.File;
import java.io.FilenameFilter;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
/**
* The Locator is a utility class which is used to find certain items
* in the environment
*
* @since Ant 1.6
*/
public final class Locator {
/**
* Not instantiable
*/
private Locator() {
}
/**
* Find the directory or jar file the class has been loaded from.
*
* @param c the class whose location is required.
* @return the file or jar with the class or null if we cannot
* determine the location.
*
* @since Ant 1.6
*/
public static File getClassSource(Class c) {
String classResource = c.getName().replace('.', '/') + ".class";
return getResourceSource(c.getClassLoader(), classResource);
}
/**
* Find the directory or jar a give resource has been loaded from.
*
* @param c the classloader to be consulted for the source
* @param resource the resource whose location is required.
*
* @return the file with the resource source or null if
* we cannot determine the location.
*
* @since Ant 1.6
*/
public static File getResourceSource(ClassLoader c, String resource) {
if (c == null) {
c = Locator.class.getClassLoader();
}
URL url = null;
if (c == null) {
url = ClassLoader.getSystemResource(resource);
} else {
url = c.getResource(resource);
}
if (url != null) {
String u = url.toString();
if (u.startsWith("jar:file:")) {
int pling = u.indexOf("!");
String jarName = u.substring(4, pling);
return new File(fromURI(jarName));
} else if (u.startsWith("file:")) {
int tail = u.indexOf(resource);
String dirName = u.substring(0, tail);
return new File(fromURI(dirName));
}
}
return null;
}
/**
* Constructs a file path from a <code>file:</code> URI.
*
* <p>Will be an absolute path if the given URI is absolute.</p>
*
* <p>Swallows '%' that are not followed by two characters,
* doesn't deal with non-ASCII characters.</p>
*
* @param uri the URI designating a file in the local filesystem.
* @return the local file system path for the file.
* @since Ant 1.6
*/
public static String fromURI(String uri) {
URL url = null;
try {
url = new URL(uri);
} catch (MalformedURLException emYouEarlEx) {
}
if (url == null || !("file".equals(url.getProtocol()))) {
throw new IllegalArgumentException("Can only handle valid file: URIs");
}
StringBuffer buf = new StringBuffer(url.getHost());
if (buf.length() > 0) {
buf.insert(0, File.separatorChar).insert(0, File.separatorChar);
}
String file = url.getFile();
int queryPos = file.indexOf('?');
buf.append((queryPos < 0) ? file : file.substring(0, queryPos));
uri = buf.toString().replace('/', File.separatorChar);
if (File.pathSeparatorChar == ';' && uri.startsWith("\\") && uri.length() > 2
&& Character.isLetter(uri.charAt(1)) && uri.lastIndexOf(':') > -1) {
uri = uri.substring(1);
}
StringBuffer sb = new StringBuffer();
CharacterIterator iter = new StringCharacterIterator(uri);
for (char c = iter.first(); c != CharacterIterator.DONE;
c = iter.next()) {
if (c == '%') {
char c1 = iter.next();
if (c1 != CharacterIterator.DONE) {
int i1 = Character.digit(c1, 16);
char c2 = iter.next();
if (c2 != CharacterIterator.DONE) {
int i2 = Character.digit(c2, 16);
sb.append((char) ((i1 << 4) + i2));
}
}
} else {
sb.append(c);
}
}
String path = sb.toString();
return path;
}
/**
* Get the File necessary to load the Sun compiler tools. If the classes
* are available to this class, then no additional URL is required and
* null is returned. This may be because the classes are explicitly in the
* class path or provided by the JVM directly
*
* @return the tools jar as a File if required, null otherwise
*/
public static File getToolsJar() {
// firstly check if the tools jar is already in the classpath
boolean toolsJarAvailable = false;
try {
// just check whether this throws an exception
Class.forName("com.sun.tools.javac.Main");
toolsJarAvailable = true;
} catch (Exception e) {
try {
Class.forName("sun.tools.javac.Main");
toolsJarAvailable = true;
} catch (Exception e2) {
// ignore
}
}
if (toolsJarAvailable) {
return null;
}
// couldn't find compiler - try to find tools.jar
// based on java.home setting
String javaHome = System.getProperty("java.home");
if (javaHome.toLowerCase(Locale.US).endsWith("jre")) {
javaHome = javaHome.substring(0, javaHome.length() - 4);
}
File toolsJar = new File(javaHome + "/lib/tools.jar");
if (!toolsJar.exists()) {
System.out.println("Unable to locate tools.jar. "
+ "Expected to find it in " + toolsJar.getPath());
return null;
}
return toolsJar;
}
/**
* Get an array or URLs representing all of the jar files in the
* given location. If the location is a file, it is returned as the only
* element of the array. If the location is a directory, it is scanned for
* jar files
*
* @param location the location to scan for Jars
*
* @return an array of URLs for all jars in the given location.
*
* @exception MalformedURLException if the URLs for the jars cannot be
* formed
*/
public static URL[] getLocationURLs(File location)
throws MalformedURLException {
return getLocationURLs(location, new String[]{".jar"});
}
/**
* Get an array or URLs representing all of the files of a given set of
* extensions in the given location. If the location is a file, it is
* returned as the only element of the array. If the location is a
* directory, it is scanned for matching files
*
* @param location the location to scan for files
* @param extensions an array of extension that are to match in the
* directory search
*
* @return an array of URLs of matching files
* @exception MalformedURLException if the URLs for the files cannot be
* formed
*/
public static URL[] getLocationURLs(File location,
final String[] extensions)
throws MalformedURLException {
URL[] urls = new URL[0];
if (!location.exists()) {
return urls;
}
if (!location.isDirectory()) {
urls = new URL[1];
String path = location.getPath();
for (int i = 0; i < extensions.length; ++i) {
if (path.toLowerCase().endsWith(extensions[i])) {
urls[0] = location.toURL();
break;
}
}
return urls;
}
File[] matches = location.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String name) {
for (int i = 0; i < extensions.length; ++i) {
if (name.toLowerCase().endsWith(extensions[i])) {
return true;
}
}
return false;
}
});
urls = new URL[matches.length];
for (int i = 0; i < matches.length; ++i) {
urls[i] = matches[i].toURL();
}
return urls;
}
}
|
RTSandberg/BaryTree | src/interaction_compute/interaction_compute_downpass.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include "../utilities/array.h"
#include "../tree/struct_tree.h"
#include "../particles/struct_particles.h"
#include "../run_params/struct_run_params.h"
#include "interaction_compute.h"
static void cp_comp_pot(struct Tree *tree, int idx, double *potential, int interp_order,
double *xT, double *yT, double *zT, double *qT,
double *clusterQ, double *clusterW);
//static void cp_comp_pot_SS(struct Tree *tree, int idx, int interp_order,
// double *xT, double *yT, double *zT, double *qT,
// double *clusterQ, double *clusterW);
static void cp_comp_pot_hermite(struct Tree *tree, int idx, double *potential, int interp_order,
double *xT, double *yT, double *zT, double *qT,
double *clusterQ, double *clusterW);
//static void cp_comp_pot_hermite_SS(struct Tree *tree, int idx, int interp_order,
// int totalNumberInterpolationPoints,
// double *xT, double *yT, double *zT, double *qT,
// double *clusterQ, double *clusterW);
void InteractionCompute_Downpass(double *potential, struct Tree *tree,
struct Particles *targets, struct Clusters *clusters,
struct RunParams *run_params)
{
int num_targets = targets->num;
double *target_x = targets->x;
double *target_y = targets->y;
double *target_z = targets->z;
double *target_q = targets->q;
int total_num_interp_charges = clusters->num_charges;
int total_num_interp_weights = clusters->num_weights;
double *cluster_q = clusters->q;
double *cluster_w = clusters->w;
int tree_numnodes = tree->numnodes;
int interp_order = run_params->interp_order;
#ifdef OPENACC_ENABLED
#pragma acc data copyin(target_x[0:num_targets], target_y[0:num_targets], \
target_z[0:num_targets], target_q[0:num_targets], \
cluster_q[0:total_num_interp_charges], \
cluster_w[0:total_num_interp_weights]) \
copy(potential[0:num_targets])
{
#endif
if ((run_params->approximation == LAGRANGE) && (run_params->singularity == SKIPPING)) {
for (int i = 0; i < tree_numnodes; i++)
cp_comp_pot(tree, i, potential, interp_order,
target_x, target_y, target_z, target_q, cluster_q, cluster_w);
} else if ((run_params->approximation == LAGRANGE) && (run_params->singularity == SUBTRACTION)) {
// for (int i = 0; i < tree_numnodes; i++)
// cp_comp_pot_SS(tree, i, potential interp_order,
// target_x, target_y, target_z, target_q, cluster_q, cluster_w);
} else if ((run_params->approximation == HERMITE) && (run_params->singularity == SKIPPING)) {
for (int i = 0; i < tree_numnodes; i++)
cp_comp_pot_hermite(tree, i, potential, interp_order,
target_x, target_y, target_z, target_q, cluster_q, cluster_w);
} else if ((run_params->approximation == HERMITE) && (run_params->singularity == SUBTRACTION)) {
// for (int i = 0; i < tree_numnodes; i++)
// cp_comp_pot_hermite_SS(tree, i, potential, interp_order,
// target_x, target_y, target_z, target_q, cluster_q, cluster_w);
} else {
exit(1);
}
#ifdef OPENACC_ENABLED
#pragma acc wait
} // end ACC DATA REGION
#endif
return;
}
/************************************/
/***** LOCAL FUNCTIONS **************/
/************************************/
void cp_comp_pot(struct Tree *tree, int idx, double *potential, int interp_order,
double *target_x, double *target_y, double *target_z, double *target_q,
double *cluster_q, double *cluster_w)
{
int interp_order_lim = interp_order + 1;
int interp_pts_per_cluster = interp_order_lim * interp_order_lim * interp_order_lim;
int num_targets_in_cluster = tree->iend[idx] - tree->ibeg[idx] + 1;
int target_start = tree->ibeg[idx] - 1;
int cluster_start = idx * interp_pts_per_cluster;
double *weights, *dj, *tt, *nodeX, *nodeY, *nodeZ;
make_vector(weights, interp_order_lim);
make_vector(dj, interp_order_lim);
make_vector(tt, interp_order_lim);
make_vector(nodeX, interp_order_lim);
make_vector(nodeY, interp_order_lim);
make_vector(nodeZ, interp_order_lim);
double x0 = tree->x_min[idx];
double x1 = tree->x_max[idx];
double y0 = tree->y_min[idx];
double y1 = tree->y_max[idx];
double z0 = tree->z_min[idx];
double z1 = tree->z_max[idx];
#ifdef OPENACC_ENABLED
int streamID = rand() % 4;
#pragma acc kernels async(streamID) present(target_x, target_y, target_z, target_q, cluster_q) \
create(nodeX[0:interp_order_lim], nodeY[0:interp_order_lim], nodeZ[0:interp_order_lim], \
weights[0:interp_order_lim], dj[0:interp_order_lim], tt[0:interp_order_lim])
{
#endif
// Fill in arrays of unique x, y, and z coordinates for the interpolation points.
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int i = 0; i < interp_order_lim; i++) {
tt[i] = cos(i * M_PI / interp_order);
nodeX[i] = x0 + (tt[i] + 1.0)/2.0 * (x1 - x0);
nodeY[i] = y0 + (tt[i] + 1.0)/2.0 * (y1 - y0);
nodeZ[i] = z0 + (tt[i] + 1.0)/2.0 * (z1 - z0);
}
// Compute weights
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int j = 0; j < interp_order_lim; j++){
dj[j] = 1.0;
if (j == 0) dj[j] = 0.5;
if (j == interp_order) dj[j] = 0.5;
}
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int j = 0; j < interp_order_lim; j++) {
weights[j] = ((j % 2 == 0)? 1 : -1) * dj[j];
}
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int i = 0; i < num_targets_in_cluster; i++) { // loop through the target points
double sumX = 0.0;
double sumY = 0.0;
double sumZ = 0.0;
double tx = target_x[target_start+i];
double ty = target_y[target_start+i];
double tz = target_z[target_start+i];
int eix = -1;
int eiy = -1;
int eiz = -1;
#ifdef OPENACC_ENABLED
#pragma acc loop independent reduction(+:sumX,sumY,sumZ) reduction(max:eix,eiy,eiz)
#endif
for (int j = 0; j < interp_order_lim; j++) { // loop through the degree
double cx = tx - nodeX[j];
double cy = ty - nodeY[j];
double cz = tz - nodeZ[j];
if (fabs(cx)<DBL_MIN) eix = j;
if (fabs(cy)<DBL_MIN) eiy = j;
if (fabs(cz)<DBL_MIN) eiz = j;
// Increment the sums
double w = weights[j];
sumX += w / cx;
sumY += w / cy;
sumZ += w / cz;
}
double denominator = 1.0;
if (eix==-1) denominator /= sumX;
if (eiy==-1) denominator /= sumY;
if (eiz==-1) denominator /= sumZ;
double temp = 0.0;
#ifdef OPENACC_ENABLED
#pragma acc loop independent reduction(+:temp)
#endif
for (int j = 0; j < interp_pts_per_cluster; j++) { // loop over interpolation points, set (cx,cy,cz) for this point
int k1 = j%interp_order_lim;
int kk = (j-k1)/interp_order_lim;
int k2 = kk%interp_order_lim;
kk = kk - k2;
int k3 = kk / interp_order_lim;
double w3 = weights[k3];
double w2 = weights[k2];
double w1 = weights[k1];
double cx = nodeX[k1];
double cy = nodeY[k2];
double cz = nodeZ[k3];
double cq = cluster_q[cluster_start + j];
double numerator = 1.0;
// If exactInd[i] == -1, then no issues.
// If exactInd[i] != -1, then we want to zero out terms EXCEPT when exactInd=k1.
if (eix == -1) {
numerator *= w1 / (tx - cx);
} else {
if (eix != k1) numerator *= 0;
}
if (eiy == -1) {
numerator *= w2 / (ty - cy);
} else {
if (eiy != k2) numerator *= 0;
}
if (eiz == -1) {
numerator *= w3 / (tz - cz);
} else {
if (eiz != k3) numerator *= 0;
}
temp += numerator * denominator * cq;
}
#ifdef OPENACC_ENABLED
#pragma acc atomic
#endif
potential[i + target_start] += temp;
}
#ifdef OPENACC_ENABLED
} //end ACC kernels
#endif
free_vector(weights);
free_vector(dj);
free_vector(tt);
free_vector(nodeX);
free_vector(nodeY);
free_vector(nodeZ);
return;
}
void cp_comp_pot_hermite(struct Tree *tree, int idx, double *potential, int interp_order,
double *target_x, double *target_y, double *target_z, double *target_q, double *cluster_q, double *cluster_w)
{
int interp_order_lim = interp_order + 1;
int interp_pts_per_cluster = interp_order_lim * interp_order_lim * interp_order_lim;
int num_targets_in_cluster = tree->iend[idx] - tree->ibeg[idx] + 1;
int target_start = tree->ibeg[idx] - 1;
int cluster_start = idx * interp_pts_per_cluster;
double *dj, *tt, *ww, *wx, *wy, *wz, *nodeX, *nodeY, *nodeZ;
make_vector(dj, interp_order_lim);
make_vector(tt, interp_order_lim);
make_vector(ww, interp_order_lim);
make_vector(wx, interp_order_lim);
make_vector(wy, interp_order_lim);
make_vector(wz, interp_order_lim);
make_vector(nodeX, interp_order_lim);
make_vector(nodeY, interp_order_lim);
make_vector(nodeZ, interp_order_lim);
double *cluster_q_ = &cluster_q[8*cluster_start + 0*interp_pts_per_cluster];
double *cluster_q_dx = &cluster_q[8*cluster_start + 1*interp_pts_per_cluster];
double *cluster_q_dy = &cluster_q[8*cluster_start + 2*interp_pts_per_cluster];
double *cluster_q_dz = &cluster_q[8*cluster_start + 3*interp_pts_per_cluster];
double *cluster_q_dxy = &cluster_q[8*cluster_start + 4*interp_pts_per_cluster];
double *cluster_q_dyz = &cluster_q[8*cluster_start + 5*interp_pts_per_cluster];
double *cluster_q_dxz = &cluster_q[8*cluster_start + 6*interp_pts_per_cluster];
double *cluster_q_dxyz = &cluster_q[8*cluster_start + 7*interp_pts_per_cluster];
double x0 = tree->x_min[idx];
double x1 = tree->x_max[idx];
double y0 = tree->y_min[idx];
double y1 = tree->y_max[idx];
double z0 = tree->z_min[idx];
double z1 = tree->z_max[idx];
#ifdef OPENACC_ENABLED
int streamID = rand() % 4;
#pragma acc kernels async(streamID) present(target_x, target_y, target_z, target_q, \
cluster_q_, cluster_q_dx, cluster_q_dy, cluster_q_dz, \
cluster_q_dxy, cluster_q_dyz, cluster_q_dxz, \
cluster_q_dxyz) \
create(nodeX[0:interp_order_lim], nodeY[0:interp_order_lim], nodeZ[0:interp_order_lim], \
dj[0:interp_order_lim], tt[0:interp_order_lim], ww[0:interp_order_lim], \
wx[0:interp_order_lim], wy[0:interp_order_lim], wz[0:interp_order_lim])
{
#endif
// Fill in arrays of unique x, y, and z coordinates for the interpolation points.
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int i = 0; i < interp_order_lim; i++) {
double xx = i * M_PI / interp_order;
tt[i] = cos(xx);
ww[i] = -cos(xx) / (2 * sin(xx) * sin(xx));
nodeX[i] = x0 + (tt[i] + 1.0)/2.0 * (x1 - x0);
nodeY[i] = y0 + (tt[i] + 1.0)/2.0 * (y1 - y0);
nodeZ[i] = z0 + (tt[i] + 1.0)/2.0 * (z1 - z0);
}
ww[0] = 0.25 * (interp_order*interp_order/3.0 + 1.0/6.0);
ww[interp_order] = -ww[0];
// Compute weights
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int j = 0; j < interp_order_lim; j++){
dj[j] = 1.0;
wx[j] = -4.0 * ww[j] / (x1 - x0);
wy[j] = -4.0 * ww[j] / (y1 - y0);
wz[j] = -4.0 * ww[j] / (z1 - z0);
}
dj[0] = 0.25;
dj[interp_order] = 0.25;
#ifdef OPENACC_ENABLED
#pragma acc loop independent
#endif
for (int i = 0; i < num_targets_in_cluster; i++) { // loop through the target points
double sumX = 0.0;
double sumY = 0.0;
double sumZ = 0.0;
double tx = target_x[target_start+i];
double ty = target_y[target_start+i];
double tz = target_z[target_start+i];
int eix = -1;
int eiy = -1;
int eiz = -1;
#ifdef OPENACC_ENABLED
#pragma acc loop independent reduction(+:sumX,sumY,sumZ) reduction(max:eix,eiy,eiz)
#endif
for (int j = 0; j < interp_order_lim; j++) { // loop through the degree
double cx = tx - nodeX[j];
double cy = ty - nodeY[j];
double cz = tz - nodeZ[j];
if (fabs(cx)<DBL_MIN) eix = j;
if (fabs(cy)<DBL_MIN) eiy = j;
if (fabs(cz)<DBL_MIN) eiz = j;
// Increment the sums
sumX += dj[j] / (cx*cx) + wx[j] / cx;
sumY += dj[j] / (cy*cy) + wy[j] / cy;
sumZ += dj[j] / (cz*cz) + wz[j] / cz;
}
double denominator = 1.0;
if (eix==-1) denominator /= sumX;
if (eiy==-1) denominator /= sumY;
if (eiz==-1) denominator /= sumZ;
double temp = 0.0;
#ifdef OPENACC_ENABLED
#pragma acc loop independent reduction(+:temp)
#endif
for (int j = 0; j < interp_pts_per_cluster; j++) { // loop over interpolation points, set (cx,cy,cz) for this point
int k1 = j%interp_order_lim;
int kk = (j-k1)/interp_order_lim;
int k2 = kk%interp_order_lim;
kk = kk - k2;
int k3 = kk / interp_order_lim;
double dx = tx - nodeX[k1];
double dy = ty - nodeY[k2];
double dz = tz - nodeZ[k3];
double cq = cluster_q_[j];
double cqdx = cluster_q_dx[j];
double cqdy = cluster_q_dy[j];
double cqdz = cluster_q_dz[j];
double cqdxy = cluster_q_dxy[j];
double cqdyz = cluster_q_dyz[j];
double cqdxz = cluster_q_dxz[j];
double cqdxyz = cluster_q_dxyz[j];
double numerator0 = 1.0, numerator1 = 1.0, numerator2 = 1.0, numerator3 = 1.0;
double numerator4 = 1.0, numerator5 = 1.0, numerator6 = 1.0, numerator7 = 1.0;
double Ax = dj[k1] / (dx*dx) + wx[k1] / dx;
double Ay = dj[k2] / (dy*dy) + wy[k2] / dy;
double Az = dj[k3] / (dz*dz) + wz[k3] / dz;
double Bx = dj[k1] / dx;
double By = dj[k2] / dy;
double Bz = dj[k3] / dz;
// If exactInd[i] == -1, then no issues.
// If exactInd[i] != -1, then we want to zero out terms EXCEPT when exactInd=k1.
if (eix == -1) {
numerator0 *= Ax; // Aaa
numerator1 *= Bx; // Baa
numerator2 *= Ax; // Aba
numerator3 *= Ax; // Aab
numerator4 *= Bx; // Bba
numerator5 *= Ax; // Abb
numerator6 *= Bx; // Bab
numerator7 *= Bx; // Bbb
} else {
if (eix != k1) {
numerator0 *= 0; numerator1 *= 0; numerator2 *= 0; numerator3 *= 0;
numerator4 *= 0; numerator5 *= 0; numerator6 *= 0; numerator7 *= 0;
} else {
numerator1 *= 0; numerator4 *= 0; numerator6 *= 0; numerator7 *= 0;
}
}
if (eiy == -1) {
numerator0 *= Ay; // aAa
numerator1 *= Ay; // bAa
numerator2 *= By; // aBa
numerator3 *= Ay; // aAb
numerator4 *= By; // bBa
numerator5 *= By; // aBb
numerator6 *= Ay; // bAb
numerator7 *= By; // bBb
} else {
if (eiy != k2) {
numerator0 *= 0; numerator1 *= 0; numerator2 *= 0; numerator3 *= 0;
numerator4 *= 0; numerator5 *= 0; numerator6 *= 0; numerator7 *= 0;
} else {
numerator2 *= 0; numerator4 *= 0; numerator5 *= 0; numerator7 *= 0;
}
}
if (eiz == -1) {
numerator0 *= Az; // aaA
numerator1 *= Az; // baA
numerator2 *= Az; // abA
numerator3 *= Bz; // aaB
numerator4 *= Az; // bbA
numerator5 *= Bz; // abB
numerator6 *= Bz; // baB
numerator7 *= Bz; // bbB
} else {
if (eiz != k3) {
numerator0 *= 0; numerator1 *= 0; numerator2 *= 0; numerator3 *= 0;
numerator4 *= 0; numerator5 *= 0; numerator6 *= 0; numerator7 *= 0;
} else {
numerator3 *= 0; numerator5 *= 0; numerator6 *= 0; numerator7 *= 0;
}
}
temp += denominator * (numerator0 * cq + numerator1 * cqdx + numerator2 * cqdy
+ numerator3 * cqdz + numerator4 * cqdxy + numerator5 * cqdyz
+ numerator6 * cqdxz + numerator7 * cqdxyz);
}
#ifdef OPENACC_ENABLED
#pragma acc atomic
#endif
potential[i + target_start] += temp;
}
#ifdef OPENACC_ENABLED
} //end ACC kernels
#endif
free_vector(dj);
free_vector(tt);
free_vector(ww);
free_vector(wx);
free_vector(wy);
free_vector(wz);
free_vector(nodeX);
free_vector(nodeY);
free_vector(nodeZ);
return;
}
|
hitong/ChartRoom | src/utils/IsNull.java | package utils;
public class IsNull {
public static boolean isNull(String str) {
if (str == null || str.trim().equals("")) {
return true;
} else {
return false;
}
}
public static boolean isNull(Object obj) {
if (obj == null) {
return true;
} else {
return false;
}
}
}
|
tlunter/oboe-ruby | test/instrumentation/em_http_request_test.rb | <reponame>tlunter/oboe-ruby<gh_stars>0
# Copyright (c) 2015 AppNeta, Inc.
# All rights reserved.
require 'minitest_helper'
# Disable this test on JRuby until we can investigate
# "SOCKET: SET COMM INACTIVITY UNIMPLEMENTED 10"
# https://travis-ci.org/appneta/traceview-ruby/jobs/33745752
if RUBY_VERSION >= '1.9' and TraceView::Config[:em_http_request][:enabled] and not defined?(JRUBY_VERSION)
describe "EventMachine" do
before do
clear_all_traces
@collect_backtraces = TraceView::Config[:em_http_request][:collect_backtraces]
end
after do
TraceView::Config[:em_http_request][:collect_backtraces] = @collect_backtraces
end
it 'EventMachine::HttpConnection should be loaded, defined and ready' do
defined?(::EventMachine::HttpConnection).wont_match nil
end
it 'should have traceview methods defined' do
::EventMachine::HttpConnection.method_defined?("setup_request_with_traceview").must_equal true
end
it 'should trace request' do
TraceView::API.start_trace('em-http-request_test', '', {}) do
EventMachine.run do
http = EventMachine::HttpRequest.new('http://appneta.com/').get
http.callback do
EventMachine.stop
end
end
end
traces = get_all_traces
traces.count.must_equal 4
validate_outer_layers(traces, 'em-http-request_test')
traces[1]["Layer"].must_equal "em-http-request"
traces[1]["Label"].must_equal "entry"
traces[1]["IsService"].must_equal "1"
traces[1]["RemoteURL"].must_equal "http://appneta.com/"
traces[1].has_key?('Backtrace').must_equal TraceView::Config[:em_http_request][:collect_backtraces]
traces[2]["Layer"].must_equal "em-http-request"
traces[2]["Label"].must_equal "exit"
traces[2]["Async"].must_equal "1"
traces[2].has_key?('Backtrace').must_equal TraceView::Config[:em_http_request][:collect_backtraces]
end
it "should obey :collect_backtraces setting when true" do
TraceView::Config[:em_http_request][:collect_backtraces] = true
TraceView::API.start_trace('em-http-request_test', '', {}) do
EventMachine.run do
http = EventMachine::HttpRequest.new('http://appneta.com/').get
http.callback do
EventMachine.stop
end
end
end
traces = get_all_traces
layer_has_key(traces, 'em-http-request', 'Backtrace')
end
it "should obey :collect_backtraces setting when false" do
TraceView::Config[:em_http_request][:collect_backtraces] = false
TraceView::API.start_trace('em-http-request_test', '', {}) do
EventMachine.run do
http = EventMachine::HttpRequest.new('http://appneta.com/').get
http.callback do
EventMachine.stop
end
end
end
traces = get_all_traces
layer_doesnt_have_key(traces, 'em-http-request', 'Backtrace')
end
end
end # unless defined?(JRUBY_VERSION)
|
armroyce/Unreal | UnrealEngine-4.11.2-release/Engine/Source/Developer/Mac/MacTargetPlatform/Private/MacTargetPlatformClasses.cpp | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
MacTargetPlatformClasses.cpp: Implements the module's UClasses.
=============================================================================*/
#include "MacTargetPlatformPrivatePCH.h"
/* UMacTargetSettings structors
*****************************************************************************/
UMacTargetSettings::UMacTargetSettings( const FObjectInitializer& ObjectInitializer )
: Super(ObjectInitializer)
{ }
|
whkendny/Learning-Vuejs-2 | chapter7/shopping-list/test/unit/specs/vuex/getters.spec.js | <reponame>whkendny/Learning-Vuejs-2
import * as getters from 'src/vuex/getters'
describe('getters.js', () => {
var state, lists
beforeEach(() => {
lists = [{id: '1', title: 'groceries'}, {id: '2', title: 'clothes'}]
state = {
shoppinglists: lists
}
})
describe('getLists', () => {
it('should return lists', () => {
expect(getters.getLists(state)).to.eql(lists)
})
})
describe('getListById', () => {
it('should return the shopping list object by its id', () => {
expect(getters.getListById(state, '1')).to.eql({id: '1', title: 'groceries'})
})
it('should not return anything if the passed id is not in the list', () => {
expect(getters.getListById(state, 'notexisting')).to.be.empty
})
})
})
|
sofwerx/OSUS-R | mil.dod.th.ose.gui.webapp/test/mil/dod/th/ose/gui/webapp/utils/push/TestPushContextUtil.java | //==============================================================================
// This software is part of the Open Standard for Unattended Sensors (OSUS)
// reference implementation (OSUS-R).
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <http://creativecommons.org/publicdomain/zero/1.0/>.
//==============================================================================
package mil.dod.th.ose.gui.webapp.utils.push;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.primefaces.push.PushContext;
import org.primefaces.push.PushContextFactory;
/**
* Test class for {@link PushContextUtil}
* @author nickmarcucci
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({PushContextFactory.class, PushContext.class})
public class TestPushContextUtil
{
private PushContextUtil m_SUT;
@Before
public void init()
{
m_SUT = new PushContextUtil();
PowerMockito.mockStatic(PushContextFactory.class);
PowerMockito.mockStatic(PushContext.class);
}
/**
* Test the getPushContext method.
* Verify that the appropriate PushContext is returned.
*/
@Test
public void testGetPushContext()
{
PushContextFactory factory = mock(PushContextFactory.class);
PushContext context = mock(PushContext.class);
PowerMockito.when(PushContextFactory.getDefault()).thenReturn(factory);
PowerMockito.when(PushContextFactory.getDefault().getPushContext()).thenReturn(context);
assertThat(m_SUT.getPushContext(), is(context));
}
}
|
benety/mongo | src/mongo/db/operation_context.h | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <boost/optional.hpp>
#include <memory>
#include "mongo/base/status.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/logical_session_id_helpers.h"
#include "mongo/db/operation_id.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/db/storage/recovery_unit.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/storage/write_unit_of_work.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/mutex.h"
#include "mongo/stdx/condition_variable.h"
#include "mongo/transport/session.h"
#include "mongo/util/cancellation.h"
#include "mongo/util/concurrency/with_lock.h"
#include "mongo/util/decorable.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/interruptible.h"
#include "mongo/util/lockable_adapter.h"
#include "mongo/util/time_support.h"
#include "mongo/util/timer.h"
namespace mongo {
class CurOp;
class ProgressMeter;
class ServiceContext;
class StringData;
namespace repl {
class UnreplicatedWritesBlock;
} // namespace repl
// Enabling the maxTimeAlwaysTimeOut fail point will cause any query or command run with a
// valid non-zero max time to fail immediately. Any getmore operation on a cursor already
// created with a valid non-zero max time will also fail immediately.
//
// This fail point cannot be used with the maxTimeNeverTimeOut fail point.
extern FailPoint maxTimeAlwaysTimeOut;
// Enabling the maxTimeNeverTimeOut fail point will cause the server to never time out any
// query, command, or getmore operation, regardless of whether a max time is set.
//
// This fail point cannot be used with the maxTimeAlwaysTimeOut fail point.
extern FailPoint maxTimeNeverTimeOut;
/**
* This class encompasses the state required by an operation and lives from the time a network
* operation is dispatched until its execution is finished. Note that each "getmore" on a cursor
* is a separate operation. On construction, an OperationContext associates itself with the
* current client, and only on destruction it deassociates itself. At any time a client can be
* associated with at most one OperationContext. Each OperationContext has a RecoveryUnit
* associated with it, though the lifetime is not necesarily the same, see releaseRecoveryUnit
* and setRecoveryUnit. The operation context also keeps track of some transaction state
* (RecoveryUnitState) to reduce complexity and duplication in the storage-engine specific
* RecoveryUnit and to allow better invariant checking.
*/
class OperationContext : public Interruptible, public Decorable<OperationContext> {
OperationContext(const OperationContext&) = delete;
OperationContext& operator=(const OperationContext&) = delete;
public:
static constexpr auto kDefaultOperationContextTimeoutError = ErrorCodes::ExceededTimeLimit;
/**
* Creates an op context with no unique operation ID tracking - prefer using the OperationIdSlot
* CTOR if possible to avoid OperationId collisions.
*/
OperationContext(Client* client, OperationId opId);
OperationContext(Client* client, OperationIdSlot&& opIdSlot);
virtual ~OperationContext();
bool shouldParticipateInFlowControl() const {
return _shouldParticipateInFlowControl;
}
void setShouldParticipateInFlowControl(bool target) {
_shouldParticipateInFlowControl = target;
}
/**
* Interface for durability. Caller DOES NOT own pointer.
*/
RecoveryUnit* recoveryUnit() const {
return _recoveryUnit.get();
}
/**
* Returns the RecoveryUnit (same return value as recoveryUnit()) but the caller takes
* ownership of the returned RecoveryUnit, and the OperationContext instance relinquishes
* ownership. Sets the RecoveryUnit to NULL.
*/
std::unique_ptr<RecoveryUnit> releaseRecoveryUnit();
/*
* Similar to releaseRecoveryUnit(), but sets up a new, inactive RecoveryUnit after releasing
* the existing one.
*/
std::unique_ptr<RecoveryUnit> releaseAndReplaceRecoveryUnit();
/**
* Associates the OperatingContext with a different RecoveryUnit for getMore or
* subtransactions, see RecoveryUnitSwap. The new state is passed and the old state is
* returned separately even though the state logically belongs to the RecoveryUnit,
* as it is managed by the OperationContext.
*/
WriteUnitOfWork::RecoveryUnitState setRecoveryUnit(std::unique_ptr<RecoveryUnit> unit,
WriteUnitOfWork::RecoveryUnitState state);
/**
* Interface for locking. Caller DOES NOT own pointer.
*/
Locker* lockState() const {
return _locker.get();
}
/**
* Sets the locker for use by this OperationContext. Call during OperationContext
* initialization, only.
*/
void setLockState(std::unique_ptr<Locker> locker);
/**
* Swaps the locker, releasing the old locker to the caller. The Client lock is required to
* call this function.
*/
std::unique_ptr<Locker> swapLockState(std::unique_ptr<Locker> locker, WithLock);
/**
* Returns Status::OK() unless this operation is in a killed state.
*/
Status checkForInterruptNoAssert() noexcept override;
/**
* Returns the service context under which this operation context runs, or nullptr if there is
* no such service context.
*/
ServiceContext* getServiceContext() const {
if (!_client) {
return nullptr;
}
return _client->getServiceContext();
}
/**
* Returns the client under which this context runs.
*/
Client* getClient() const {
return _client;
}
/**
* Returns the operation ID associated with this operation.
*/
OperationId getOpID() const {
return _opId.getId();
}
/**
* Returns the operation UUID associated with this operation or boost::none.
*/
const boost::optional<OperationKey>& getOperationKey() const {
return _opKey;
}
/**
* Sets the operation UUID associated with this operation.
*
* This function may only be called once per OperationContext.
*/
void setOperationKey(OperationKey opKey);
/**
* Removes the operation UUID associated with this operation.
* DO NOT call this function outside `~OperationContext()` and `killAndDelistOperation()`.
*/
void releaseOperationKey();
/**
* Returns the session ID associated with this operation, if there is one.
*/
const boost::optional<LogicalSessionId>& getLogicalSessionId() const {
return _lsid;
}
/**
* Associates a logical session id with this operation context. May only be called once for the
* lifetime of the operation.
*/
void setLogicalSessionId(LogicalSessionId lsid);
/**
* Returns the transaction number associated with thes operation. The combination of logical
* session id + transaction number is what constitutes the operation transaction id.
*/
boost::optional<TxnNumber> getTxnNumber() const {
return _txnNumber;
}
/**
* Returns the txnRetryCounter associated with this operation.
*/
boost::optional<TxnRetryCounter> getTxnRetryCounter() const {
return _txnRetryCounter;
}
/**
* Returns a CancellationToken that will be canceled when the OperationContext is killed via
* markKilled (including for internal reasons, like the OperationContext deadline being
* reached).
*/
CancellationToken getCancellationToken() {
return _cancelSource.token();
}
/**
* Sets a transport Baton on the operation. This will trigger the Baton on markKilled.
*/
void setBaton(const BatonHandle& baton) {
_baton = baton;
}
/**
* Retrieves the baton associated with the operation.
*/
const BatonHandle& getBaton() const {
return _baton;
}
/**
* Associates a transaction number with this operation context. May only be called once for the
* lifetime of the operation and the operation must have a logical session id assigned.
*/
void setTxnNumber(TxnNumber txnNumber);
/**
* Associates a txnRetryCounter with this operation context. May only be called once for the
* lifetime of the operation and the operation must have a logical session id and a transaction
* number assigned.
*/
void setTxnRetryCounter(TxnRetryCounter txnRetryCounter);
/**
* Returns the top-level WriteUnitOfWork associated with this operation context, if any.
*/
WriteUnitOfWork* getWriteUnitOfWork() {
return _writeUnitOfWork.get();
}
/**
* Sets a top-level WriteUnitOfWork for this operation context, to be held for the duration
* of the given network operation.
*/
void setWriteUnitOfWork(std::unique_ptr<WriteUnitOfWork> writeUnitOfWork) {
invariant(writeUnitOfWork || _writeUnitOfWork);
invariant(!(writeUnitOfWork && _writeUnitOfWork));
_writeUnitOfWork = std::move(writeUnitOfWork);
}
/**
* Returns WriteConcernOptions of the current operation
*/
const WriteConcernOptions& getWriteConcern() const {
return _writeConcern;
}
void setWriteConcern(const WriteConcernOptions& writeConcern) {
_writeConcern = writeConcern;
}
/**
* Returns true if operations should generate oplog entries.
*/
bool writesAreReplicated() const {
return _writesAreReplicated;
}
/**
* Returns true if the operation is running lock-free.
*/
bool isLockFreeReadsOp() const {
return _lockFreeReadOpCount;
}
/**
* Returns true if operations' durations should be added to serverStatus latency metrics.
*/
bool shouldIncrementLatencyStats() const {
return _shouldIncrementLatencyStats;
}
/**
* Sets the shouldIncrementLatencyStats flag.
*/
void setShouldIncrementLatencyStats(bool shouldIncrementLatencyStats) {
_shouldIncrementLatencyStats = shouldIncrementLatencyStats;
}
void markKillOnClientDisconnect();
/**
* Identifies the opCtx as an operation which is executing global shutdown. This has the effect
* of masking any existing time limits, removing markKill-ability and is slightly stronger than
* code run under runWithoutInterruptionExceptAtGlobalShutdown, because it is also immune to
* global shutdown.
*
* This should only be called from the registered task of global shutdown and is not
* recoverable.
*/
void setIsExecutingShutdown();
/**
* Marks this operation as killed so that subsequent calls to checkForInterrupt and
* checkForInterruptNoAssert by the thread executing the operation will start returning the
* specified error code.
*
* If multiple threads kill the same operation with different codes, only the first code
* will be preserved.
*
* May be called by any thread that has locked the Client owning this operation context, or
* by the thread executing this on behalf of this OperationContext.
*/
void markKilled(ErrorCodes::Error killCode = ErrorCodes::Interrupted);
/**
* Returns the code passed to markKilled if this operation context has been killed previously
* or ErrorCodes::OK otherwise.
*
* May be called by any thread that has locked the Client owning this operation context, or
* without lock by the thread executing on behalf of this operation context.
*/
ErrorCodes::Error getKillStatus() const {
if (_ignoreInterrupts) {
return ErrorCodes::OK;
}
return _killCode.loadRelaxed();
}
/**
* Shortcut method, which checks whether getKillStatus returns a non-OK value. Has the same
* concurrency rules as getKillStatus.
*/
bool isKillPending() const {
return getKillStatus() != ErrorCodes::OK;
}
/**
* Returns the amount of time since the operation was constructed. Uses the system's most
* precise tick source, and may not be cheap to call in a tight loop.
*/
Microseconds getElapsedTime() const {
return _elapsedTime.elapsed();
}
/**
* Sets the deadline for this operation to the given point in time.
*
* To remove a deadline, pass in Date_t::max().
*/
void setDeadlineByDate(Date_t when, ErrorCodes::Error timeoutError);
/**
* Sets the deadline for this operation to the maxTime plus the current time reported
* by the ServiceContext's fast clock source.
*/
void setDeadlineAfterNowBy(Microseconds maxTime, ErrorCodes::Error timeoutError);
template <typename D>
void setDeadlineAfterNowBy(D maxTime, ErrorCodes::Error timeoutError) {
if (maxTime <= D::zero()) {
maxTime = D::zero();
}
if (maxTime <= Microseconds::max()) {
setDeadlineAfterNowBy(duration_cast<Microseconds>(maxTime), timeoutError);
} else {
setDeadlineByDate(Date_t::max(), timeoutError);
}
}
/**
* Returns the deadline for this operation, or Date_t::max() if there is no deadline.
*/
Date_t getDeadline() const override {
return _deadline;
}
/**
* Returns the error code used when this operation's time limit is reached.
*/
ErrorCodes::Error getTimeoutError() const;
/**
* Returns the number of milliseconds remaining for this operation's time limit or
* Milliseconds::max() if the operation has no time limit.
*/
Milliseconds getRemainingMaxTimeMillis() const;
/**
* NOTE: This is a legacy "max time" method for controlling operation deadlines and it should
* not be used in new code. Use getRemainingMaxTimeMillis instead.
*
* Returns the number of microseconds remaining for this operation's time limit, or the special
* value Microseconds::max() if the operation has no time limit.
*/
Microseconds getRemainingMaxTimeMicros() const;
bool isIgnoringInterrupts() const;
/**
* Returns whether this operation is part of a multi-document transaction. Specifically, it
* indicates whether the user asked for a multi-document transaction.
*/
bool inMultiDocumentTransaction() const {
return _inMultiDocumentTransaction;
}
bool isRetryableWrite() const {
return _txnNumber &&
(!_inMultiDocumentTransaction || isInternalSessionForRetryableWrite(*_lsid));
}
/**
* Sets that this operation is part of a multi-document transaction. Once this is set, it cannot
* be unset.
*/
void setInMultiDocumentTransaction() {
_inMultiDocumentTransaction = true;
if (!_txnRetryCounter.has_value()) {
_txnRetryCounter = 0;
}
}
/**
* Some operations coming into the system must be validated to ensure they meet constraints,
* such as collection namespace length limits or unique index key constraints. However,
* operations being performed from a source of truth such as during initial sync and oplog
* application often must ignore constraint violations.
*
* Initial sync and oplog application opt in to relaxed constraint checking by setting this
* value to false.
*/
void setEnforceConstraints(bool enforceConstraints) {
_enforceConstraints = enforceConstraints;
}
/**
* This method can be used to tell if an operation requires validation of constraints. This
* should be preferred to alternatives such as checking if a node is primary or if a client is
* from a user connection as those have nuances (e.g: primary catch up and client disassociation
* due to task executors).
*/
bool isEnforcingConstraints() {
return _enforceConstraints;
}
/**
* Sets that this operation should always get killed during stepDown and stepUp, regardless of
* whether or not it's taken a write lock.
*/
void setAlwaysInterruptAtStepDownOrUp() {
_alwaysInterruptAtStepDownOrUp.store(true);
}
/**
* Indicates that this operation should always get killed during stepDown and stepUp, regardless
* of whether or not it's taken a write lock.
*/
bool shouldAlwaysInterruptAtStepDownOrUp() {
return _alwaysInterruptAtStepDownOrUp.load();
}
/**
* Sets that this operation should ignore interruption except for replication state change. Can
* only be called by the thread executing this on behalf of this OperationContext.
*/
void setIgnoreInterruptsExceptForReplStateChange(bool target) {
_ignoreInterruptsExceptForReplStateChange = target;
}
/**
* Clears metadata associated with a multi-document transaction.
*/
void resetMultiDocumentTransactionState() {
invariant(_inMultiDocumentTransaction);
invariant(!_writeUnitOfWork);
invariant(_ruState == WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork);
_inMultiDocumentTransaction = false;
_isStartingMultiDocumentTransaction = false;
_lsid = boost::none;
_txnNumber = boost::none;
_txnRetryCounter = boost::none;
}
/**
* Returns whether this operation is starting a multi-document transaction.
*/
bool isStartingMultiDocumentTransaction() const {
return _isStartingMultiDocumentTransaction;
}
/**
* Returns whether this operation is continuing (not starting) a multi-document transaction.
*/
bool isContinuingMultiDocumentTransaction() const {
return inMultiDocumentTransaction() && !isStartingMultiDocumentTransaction();
}
/**
* Sets whether this operation is starting a multi-document transaction.
*/
void setIsStartingMultiDocumentTransaction(bool isStartingMultiDocumentTransaction) {
_isStartingMultiDocumentTransaction = isStartingMultiDocumentTransaction;
}
/**
* Sets '_comment'. The client lock must be acquired before calling this method.
*/
void setComment(const BSONObj& comment) {
_comment = comment.getOwned();
}
/**
* Gets '_comment'. The client lock must be acquired when calling from any thread that does
* not own the client associated with the operation.
*/
boost::optional<BSONElement> getComment() {
// The '_comment' object, if present, will only ever have one field.
return _comment ? boost::optional<BSONElement>(_comment->firstElement()) : boost::none;
}
/**
* Sets whether this operation is an exhaust command.
*/
void setExhaust(bool exhaust) {
_exhaust = exhaust;
}
/**
* Returns whether this operation is an exhaust command.
*/
bool isExhaust() const {
return _exhaust;
}
void storeMaxTimeMS(Microseconds maxTime) {
_storedMaxTime = maxTime;
}
/**
* Restore deadline to match the value stored in _storedMaxTime.
*/
void restoreMaxTimeMS();
/**
* Returns whether this operation must run in read-only mode.
*
* If the read-only flag is set on the ServiceContext then:
* - Internal operations are allowed to perform writes.
* - User originating operations are not allowed to perform writes.
*/
bool readOnly() const {
if (!(getClient() && getClient()->isFromUserConnection()))
return false;
return !getServiceContext()->userWritesAllowed();
}
private:
StatusWith<stdx::cv_status> waitForConditionOrInterruptNoAssertUntil(
stdx::condition_variable& cv, BasicLockableAdapter m, Date_t deadline) noexcept override;
IgnoreInterruptsState pushIgnoreInterrupts() override {
IgnoreInterruptsState iis{_ignoreInterrupts,
{_deadline, _timeoutError, _hasArtificialDeadline}};
_hasArtificialDeadline = true;
setDeadlineByDate(Date_t::max(), ErrorCodes::ExceededTimeLimit);
_ignoreInterrupts = true;
return iis;
}
void popIgnoreInterrupts(IgnoreInterruptsState iis) override {
_ignoreInterrupts = iis.ignoreInterrupts;
setDeadlineByDate(iis.deadline.deadline, iis.deadline.error);
_hasArtificialDeadline = iis.deadline.hasArtificialDeadline;
_markKilledIfDeadlineRequires();
}
DeadlineState pushArtificialDeadline(Date_t deadline, ErrorCodes::Error error) override {
DeadlineState ds{_deadline, _timeoutError, _hasArtificialDeadline};
_hasArtificialDeadline = true;
setDeadlineByDate(std::min(_deadline, deadline), error);
return ds;
}
void popArtificialDeadline(DeadlineState ds) override {
setDeadlineByDate(ds.deadline, ds.error);
_hasArtificialDeadline = ds.hasArtificialDeadline;
_markKilledIfDeadlineRequires();
}
void _markKilledIfDeadlineRequires() {
if (!_ignoreInterrupts && !_hasArtificialDeadline && hasDeadlineExpired() &&
!isKillPending()) {
markKilled(_timeoutError);
}
}
/**
* Returns true if ignoring interrupts other than repl state change and no repl state change
* has occurred.
*/
bool _noReplStateChangeWhileIgnoringOtherInterrupts() const {
return _ignoreInterruptsExceptForReplStateChange &&
getKillStatus() != ErrorCodes::InterruptedDueToReplStateChange &&
!_killRequestedForReplStateChange.loadRelaxed();
}
/**
* Returns true if this operation has a deadline and it has passed according to the fast clock
* on ServiceContext.
*/
bool hasDeadlineExpired() const;
/**
* Sets the deadline and maxTime as described. It is up to the caller to ensure that
* these correctly correspond.
*/
void setDeadlineAndMaxTime(Date_t when, Microseconds maxTime, ErrorCodes::Error timeoutError);
/**
* Compute maxTime based on the given deadline.
*/
Microseconds computeMaxTimeFromDeadline(Date_t when);
/**
* Returns the timepoint that is "waitFor" ms after now according to the
* ServiceContext's precise clock.
*/
Date_t getExpirationDateForWaitForValue(Milliseconds waitFor) override;
/**
* Set whether or not operations should generate oplog entries.
*/
void setReplicatedWrites(bool writesAreReplicated = true) {
_writesAreReplicated = writesAreReplicated;
}
/**
* Increment a count to indicate that the operation is running lock-free.
*/
void incrementLockFreeReadOpCount() {
++_lockFreeReadOpCount;
}
void decrementLockFreeReadOpCount() {
--_lockFreeReadOpCount;
}
friend class WriteUnitOfWork;
friend class repl::UnreplicatedWritesBlock;
friend class LockFreeReadsBlock;
Client* const _client;
const OperationIdSlot _opId;
boost::optional<OperationKey> _opKey;
boost::optional<LogicalSessionId> _lsid;
boost::optional<TxnNumber> _txnNumber;
boost::optional<TxnRetryCounter> _txnRetryCounter;
std::unique_ptr<Locker> _locker;
std::unique_ptr<RecoveryUnit> _recoveryUnit;
WriteUnitOfWork::RecoveryUnitState _ruState =
WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork;
// Operations run within a transaction will hold a WriteUnitOfWork for the duration in order
// to maintain two-phase locking.
std::unique_ptr<WriteUnitOfWork> _writeUnitOfWork;
// Follows the values of ErrorCodes::Error. The default value is 0 (OK), which means the
// operation is not killed. If killed, it will contain a specific code. This value changes only
// once from OK to some kill code.
AtomicWord<ErrorCodes::Error> _killCode{ErrorCodes::OK};
// Used to cancel all tokens obtained via getCancellationToken() when this OperationContext is
// killed.
CancellationSource _cancelSource;
BatonHandle _baton;
WriteConcernOptions _writeConcern;
// The timepoint at which this operation exceeds its time limit.
Date_t _deadline = Date_t::max();
ErrorCodes::Error _timeoutError = kDefaultOperationContextTimeoutError;
bool _ignoreInterrupts = false;
bool _hasArtificialDeadline = false;
bool _markKillOnClientDisconnect = false;
Date_t _lastClientCheck;
bool _isExecutingShutdown = false;
// Max operation time requested by the user or by the cursor in the case of a getMore with no
// user-specified maxTimeMS. This is tracked with microsecond granularity for the purpose of
// assigning unused execution time back to a cursor at the end of an operation, only. The
// _deadline and the service context's fast clock are the only values consulted for determining
// if the operation's timelimit has been exceeded.
Microseconds _maxTime = Microseconds::max();
// The value of the maxTimeMS requested by user in the case it was overwritten.
boost::optional<Microseconds> _storedMaxTime;
// Timer counting the elapsed time since the construction of this OperationContext.
Timer _elapsedTime;
bool _writesAreReplicated = true;
bool _shouldIncrementLatencyStats = true;
bool _shouldParticipateInFlowControl = true;
bool _inMultiDocumentTransaction = false;
bool _isStartingMultiDocumentTransaction = false;
bool _ignoreInterruptsExceptForReplStateChange = false;
// Commands from user applications must run validations and enforce constraints. Operations from
// a trusted source, such as initial sync or consuming an oplog entry generated by a primary
// typically desire to ignore constraints.
bool _enforceConstraints = true;
// Counts how many lock-free read operations are running nested.
// Necessary to use a counter rather than a boolean because there is existing code that
// destructs lock helpers out of order.
int _lockFreeReadOpCount = 0;
// If true, this OpCtx will get interrupted during replica set stepUp and stepDown, regardless
// of what locks it's taken.
AtomicWord<bool> _alwaysInterruptAtStepDownOrUp{false};
AtomicWord<bool> _killRequestedForReplStateChange{false};
// If populated, this is an owned singleton BSONObj whose only field, 'comment', is a copy of
// the 'comment' field from the input command object.
boost::optional<BSONObj> _comment;
// Whether this operation is an exhaust command.
bool _exhaust = false;
};
// Gets a TimeZoneDatabase pointer from the ServiceContext.
inline const TimeZoneDatabase* getTimeZoneDatabase(OperationContext* opCtx) {
return opCtx && opCtx->getServiceContext() ? TimeZoneDatabase::get(opCtx->getServiceContext())
: nullptr;
}
namespace repl {
/**
* RAII-style class to turn off replicated writes. Writes do not create oplog entries while the
* object is in scope.
*/
class UnreplicatedWritesBlock {
UnreplicatedWritesBlock(const UnreplicatedWritesBlock&) = delete;
UnreplicatedWritesBlock& operator=(const UnreplicatedWritesBlock&) = delete;
public:
UnreplicatedWritesBlock(OperationContext* opCtx)
: _opCtx(opCtx), _shouldReplicateWrites(opCtx->writesAreReplicated()) {
opCtx->setReplicatedWrites(false);
}
~UnreplicatedWritesBlock() {
_opCtx->setReplicatedWrites(_shouldReplicateWrites);
}
private:
OperationContext* _opCtx;
const bool _shouldReplicateWrites;
};
} // namespace repl
/**
* RAII-style class to indicate the operation is lock-free and code should behave accordingly.
*/
class LockFreeReadsBlock {
LockFreeReadsBlock(const LockFreeReadsBlock&) = delete;
LockFreeReadsBlock& operator=(const LockFreeReadsBlock&) = delete;
public:
LockFreeReadsBlock(OperationContext* opCtx) : _opCtx(opCtx) {
_opCtx->incrementLockFreeReadOpCount();
}
~LockFreeReadsBlock() {
_opCtx->decrementLockFreeReadOpCount();
}
private:
OperationContext* _opCtx;
};
} // namespace mongo
|
andymonis/my-test-blockstack01 | node_modules/blockstack/lib/auth/authVerification.js | <filename>node_modules/blockstack/lib/auth/authVerification.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.doSignaturesMatchPublicKeys = doSignaturesMatchPublicKeys;
exports.doPublicKeysMatchIssuer = doPublicKeysMatchIssuer;
exports.doPublicKeysMatchUsername = doPublicKeysMatchUsername;
exports.isIssuanceDateValid = isIssuanceDateValid;
exports.isExpirationDateValid = isExpirationDateValid;
exports.isManifestUriValid = isManifestUriValid;
exports.isRedirectUriValid = isRedirectUriValid;
exports.verifyAuthRequest = verifyAuthRequest;
exports.verifyAuthRequestAndLoadManifest = verifyAuthRequestAndLoadManifest;
exports.verifyAuthResponse = verifyAuthResponse;
var _jsontokens = require('jsontokens');
var _index = require('../index');
function doSignaturesMatchPublicKeys(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
var publicKeys = payload.public_keys;
if (publicKeys.length === 1) {
var publicKey = publicKeys[0];
try {
var tokenVerifier = new _jsontokens.TokenVerifier('ES256k', publicKey);
var signatureVerified = tokenVerifier.verify(token);
if (signatureVerified) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
} else {
throw new Error('Multiple public keys are not supported');
}
}
function doPublicKeysMatchIssuer(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
var publicKeys = payload.public_keys;
var addressFromIssuer = (0, _index.getAddressFromDID)(payload.iss);
if (publicKeys.length === 1) {
var addressFromPublicKeys = (0, _index.publicKeyToAddress)(publicKeys[0]);
if (addressFromPublicKeys === addressFromIssuer) {
return true;
}
} else {
throw new Error('Multiple public keys are not supported');
}
return false;
}
function doPublicKeysMatchUsername(token, nameLookupURL) {
return new Promise(function (resolve) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
if (!payload.username) {
resolve(true);
return;
}
if (payload.username === null) {
resolve(true);
return;
}
if (nameLookupURL === null) {
resolve(false);
return;
}
var username = payload.username;
var url = nameLookupURL.replace(/\/$/, '') + '/' + username;
try {
fetch(url).then(function (response) {
return response.text();
}).then(function (responseText) {
return JSON.parse(responseText);
}).then(function (responseJSON) {
if (responseJSON.hasOwnProperty('address')) {
var nameOwningAddress = responseJSON.address;
var addressFromIssuer = (0, _index.getAddressFromDID)(payload.iss);
if (nameOwningAddress === addressFromIssuer) {
resolve(true);
} else {
resolve(false);
}
} else {
resolve(false);
}
}).catch(function () {
resolve(false);
});
} catch (e) {
resolve(false);
}
});
}
function isIssuanceDateValid(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
if (payload.iat) {
if (typeof payload.iat !== 'number') {
return false;
}
var issuedAt = new Date(payload.iat * 1000); // JWT times are in seconds
if (new Date().getTime() < issuedAt.getTime()) {
return false;
} else {
return true;
}
} else {
return true;
}
}
function isExpirationDateValid(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
if (payload.exp) {
if (typeof payload.exp !== 'number') {
return false;
}
var expiresAt = new Date(payload.exp * 1000); // JWT times are in seconds
if (new Date().getTime() > expiresAt.getTime()) {
return false;
} else {
return true;
}
} else {
return true;
}
}
function isManifestUriValid(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
return (0, _index.isSameOriginAbsoluteUrl)(payload.domain_name, payload.manifest_uri);
}
function isRedirectUriValid(token) {
var payload = (0, _jsontokens.decodeToken)(token).payload;
return (0, _index.isSameOriginAbsoluteUrl)(payload.domain_name, payload.redirect_uri);
}
/**
* Verify authentication request is valid
* @param {String} token [description]
* @return {Promise} that resolves to true if the auth request
* is valid and false if it does not
* @private
*/
function verifyAuthRequest(token) {
return new Promise(function (resolve, reject) {
if ((0, _jsontokens.decodeToken)(token).header.alg === 'none') {
reject('Token must be signed in order to be verified');
}
Promise.all([isExpirationDateValid(token), isIssuanceDateValid(token), doSignaturesMatchPublicKeys(token), doPublicKeysMatchIssuer(token), isManifestUriValid(token), isRedirectUriValid(token)]).then(function (values) {
if (values.every(Boolean)) {
resolve(true);
} else {
resolve(false);
}
});
});
}
/**
* Verify the authentication response is valid and
* fetch the app manifest file if valid. Otherwise, reject the promise.
* @param {String} token the authentication request token
* @return {Promise} that resolves to the app manifest file in JSON format
* or rejects if the auth request or app manifest file is invalid
* @private
*/
function verifyAuthRequestAndLoadManifest(token) {
return new Promise(function (resolve, reject) {
return verifyAuthRequest(token).then(function (valid) {
if (valid) {
return (0, _index.fetchAppManifest)(token).then(function (appManifest) {
resolve(appManifest);
});
} else {
reject();
return Promise.reject();
}
});
});
}
/**
* Verify the authentication response is valid
* @param {String} token the authentication response token
* @param {String} nameLookupURL the url use to verify owner of a username
* @return {Promise} that resolves to true if auth response
* is valid and false if it does not
*/
function verifyAuthResponse(token, nameLookupURL) {
return new Promise(function (resolve) {
Promise.all([isExpirationDateValid(token), isIssuanceDateValid(token), doSignaturesMatchPublicKeys(token), doPublicKeysMatchIssuer(token), doPublicKeysMatchUsername(token, nameLookupURL)]).then(function (values) {
if (values.every(Boolean)) {
resolve(true);
} else {
resolve(false);
}
});
});
} |
kpagacz/software-engineering | programowanie-obiektowe/lab-8/lab-8.cpp | <filename>programowanie-obiektowe/lab-8/lab-8.cpp
#include "Object.h"
#include "Board.h"
#include<iostream>
int main() {
Board b(10, 10);
std::cout << b << "\n\n";
b.insert(0, 0, 'A');
b.insert(3, 2, 'B');
b.insert(9, 8, 'C');
b.insert(2, 7, 'D');
std::cout << b << "\n\n";
b.exchange(0, 0, 3, 2);
b.exchange(9, 8, 9, 0);
std::cout << b << "\n\n";
b.move(0, 0, 1, 1);
std::cout << b << "\n\n";
return 0;
} |
microvibe/vibe | microvibe-booster/booster-core/src/main/java/io/microvibe/booster/commons/redis/util/RedisMap.java | package io.microvibe.booster.commons.redis.util;
import java.util.Map;
public interface RedisMap<K, V> extends Map<K, V> {
}
|
guoxiangran/main | WebRoot/app/js/view/vue/vue.components.js | Vue.component('my-baseform', function (resolve, reject) {
$.get('ajax/form/base.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
}
},
template: d,
methods: {
validateAge: function (v) {
return !(v && v > 0 && v < 120);
},
validateTel: function (v) {
return !BASE.valideTel(v);
},
validateCard: function (v) {
return !!v && !BASE.valideCard(v);
}
}
})
});
});
Vue.component('my-profileform', function (resolve, reject) {
$.get('ajax/form/profile.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
},
edit: {
type: Boolean,
default: true
}
},
template: d
})
});
});
Vue.component('my-question', function (resolve, reject) {
$.get('ajax/form/question.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
},
edit: {
type: Boolean,
default: true
}
},
template: d
})
});
});
Vue.component('my-tab', function (resolve, reject) {
$.get('ajax/form/tab.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
}
},
template: d
})
});
});
Vue.component('my-liss', function (resolve, reject) {
$.get('ajax/form/lis.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
}
},
template: d,
methods: {
synchLis: function () {
},
synchLisWithQuery: function () {
BASE.showModel({
remote: 'ajax/modal-content/modal-lis-sync-query.html',
cls: 'modal-lg'
});
},
synchLisWithUpload: function () {
$('#lisfiles_addfiles input').trigger('click');
},
pacfileok: function(){
Page.mainForms.lisForm.form.img_list = this.$refs.lisfiles.imglist,
Page.mainForms.lisForm.form.img_list_ids = this.$refs.lisfiles.ids
},
halfData: function (data, bol) {
var half = Math.ceil(data.length / 2);
return bol ? data.slice(0, half) : data.slice(half, data.length);
},
isDeepModal: function () {
return Page.mainForms.dockingMode == '2';
},
removeItem: function (pkey, key) {
var lisForm = Page.mainForms.lisForm.form;
var pIdx = BASE.arrayFindObjIndex(pkey, 'key', lisForm.list);
var idx = BASE.arrayFindObjIndex(key, 'key', lisForm.list[pIdx].beans);
idx != -1 && lisForm.list[pIdx].beans.splice(idx, 1);
},
showReportDetail: function (e) {
var o = $(e.target).closest('.reportlist'),
op = o.closest('.beantimelist');
var Idx = o.index(),
pIdx = op.index();
function creatAndshow(oIdx, opIdx) {
var $op = $('#lis-list .beantimelist:eq(' + opIdx + ')'),
$o = $op.find('.reportlist:eq(' + oIdx + ')');
var oSize = $op.find('.reportlist').size(),
opSize = $('#lis-list .beantimelist').size();
var prev = opIdx != 0 ? '<button class="btn btn-prev" onclick="Page.creatAndshow(0,' + (opIdx - 1) + ')"><i class="fa fa-angle-left"></i></button>' : '';
var next = opIdx != (opSize - 1) ? '<button class="btn btn-next" onclick="Page.creatAndshow(0,' + (opIdx + 1) + ')"><i class="fa fa-angle-right"></i></button>' : '';
var head = oSize > 1 ? (function (ele, idx, pidx) {
var header = [];
var _header = '<div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="javascript:;">报告单</a></div>';
ele.each(function (i) {
header.push('<li class="toplist' + (idx == i ? ' active' : '')
+ '" onclick="Page.creatAndshow(' + i + ',' + pidx + ')"><a href="javascript:;">' + $('.re_title', this).attr('title')
+ '</a></li>');
});
return '<div class="navbar navbar-default report-head">' + _header + '<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2"><ul class="nav navbar-nav">' + header.join('') + '</ul></div></div>';
})($op.find('.reportlist'), oIdx, opIdx) : '';
var close = '<button type="button" class="close fixed-close" data-dismiss="modal" aria-hidden="true">×</button>';
var rpt = '<div class="report-body">' + prev + '<div class="report">' + $o.find('.report').html() + '</div>' + next + '</div>';
BASE.showModel({
text: close + head + rpt,
cls: 'modal-1024'
});
}
Page.creatAndshow = creatAndshow;
creatAndshow(Idx, pIdx);
}
}
});
});
});
Vue.component('my-pacs', function (resolve, reject) {
$.get('ajax/form/pac.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
},
edit: {
type: Boolean,
default: true
}
},
template: d,
mounted: function(){
// $(window).bind("scroll",function(){
// var st = $(window).scrollTop(), sth = st + $(window).height();
// $('.vue img[data-src]').each(function(){
// var o = $(this), post = o.offset().top, posb = post + o.height();
// if ((post > st && post < sth) || (posb > st && posb < sth)) {
// this.getAttribute('src') != this.getAttribute('data-src') && o.attr('src', o.attr('data-src'));
// }
// });
// }).trigger('scroll');
},
methods: {
synchPacWithQuery: function () {
BASE.showModel({
remote: 'ajax/modal-content/modal-pac-sync-query.html',
cls: 'modal-lg'
});
},
synchPacWithUpload: function () {
BASE.showModel({
remote: 'ajax/modal-content/modal-DCIM.html',
cls: 'modal-lg'
});
},
synchImgPacWithUpload: function(){
$('#pacfiles_addfiles input').trigger('click');
},
pacfileok: function(){
Page.mainForms.pacForm.form.img_list = this.$refs.pacfiles.imglist,
Page.mainForms.pacForm.form.img_list_ids = this.$refs.pacfiles.ids
},
isDeepModal: function () {
return Page.mainForms.dockingMode == '2';
},
removeItem: function (pkey, key) {
if(confirm("确定要要删除吗?")){
var pacForm = Page.mainForms.pacForm.form;
var pIdx = BASE.arrayFindObjIndex(pkey, 'key', pacForm.list);
var idx = BASE.arrayFindObjIndex(key, 'key', pacForm.list[pIdx].beans);
idx != -1 && pacForm.list[pIdx].beans.splice(idx, 1);
var url = this.edit ? '/doctor/editPacsInfo' : '/doctor/editPacsInfo_case'
var pacs_ids = (function(list){
var arr = [];
$.each(list,function(i,n){
$.each(n.beans,function(ii,nn){
arr.push(nn.key);
});
});
return arr.join(',')})
(pacForm.list)
var obj = this.edit ? { oid: Page.otype == 4 ? Page.oid : Page.ouid, otype: Page.otype, pacs_ids: pacs_ids} : { caseUuid: Page.ouid, pacs_ids: pacs_ids}
$.post(url, obj)
.done(function () {
$.smallBox({
title: "删除提示",
content: "影像资料删除成功",
color: $.color.success,
timeout: 3000
});
})
.fail(function () {
$.smallBox({
title: "删除提示",
content: "影像资料删除失败",
color: $.color.error,
iconSmall: "fa fa-times"
});
})
}
},
saveFileName: function (pid, id, val) {
if(!val) return false;
var oldForm = Page.mainForms.pacForm.old.list;
var pidx = BASE.arrayFindObjIndex(pid, 'key', oldForm || []);
var oidx = pidx != -1 ? BASE.arrayFindObjIndex(id, 'key', oldForm[pidx].beans || []) : -1;
var oName = oidx != -1 ? oldForm[pidx].beans[oidx].kvs.Check_Item_E : '';
if(val == oName) return false;
$.post('/doctor/compleupcheckitem', { pid: id, itemname: val, oid: Page.oid })
.done(function () {
pidx != -1 && oidx != -1 && (oldForm[pidx].beans[oidx].kvs.Check_Item_E = val);
$.smallBox({
title: "”修改为“" + val + "”,成功",
color: $.color.success,
timeout: 3000
});
})
.fail(function () {
$.smallBox({
title: "修改为“" + val + "”,失败!",
color: $.color.error,
iconSmall: "fa fa-times"
});
});
},
showPacDetail: function (key, pid, sid) {
var href = location.origin + '/dwv/viewer.html?patientID=' + pid + '&studyUID=' + sid + '&serverName=';
var close = '<button type="button" class="close fixed-close full-dialog" data-dismiss="modal" aria-hidden="true">×</button>';
var iframe = '<iframe name="dwviframe" src="' + href
+ '" id="dwviframe" frameborder="no" border="0" allowscriptaccess="always" marginwidth="0" marginheight="0" allowfullscreen="true" wmode="opaque" allowTransparency="true" type="application/x-shockwave-flash" style="width:100vw;height:100vh;"></iframe>';
BASE.showModel({
text: close + iframe,
cls: 'modal-full',
gls: 'pacmodel'
});
}
}
});
});
});
Vue.component('my-selectexp',function(resolve, reject){
$.get('ajax/form/selectexp.html')
.done(function (d) {
resolve({
props: {
oid: { type: String },
eid: { type: String },
docask: { type: String ,default: ''}
},
data: function(){
return {
tab: 'hos',
keywords: '',
hosid: '',
cityid: '',
depid: '',
bigdepid: '',
dutyid: '',
hos: [],
dep: [],
duty: [
['-1','所有职务'],
['主任医师','主任医师'],
['副主任医师','副主任医师']
],
pager: {
list: []
},
expid: '',
info: {},
filter:{
hosid:'',
depid:'',
bigdepid:'',
dutyid:''
},
isload: false
};
},
template: d,
created: function(){
var that = this;
this.expid = this.eid;
that.hos.length < 1 && $.get('/propagate/gainHospitalsByArea')
.done(function(d){
var h = {};
$.each(d.hospitals || [],function(i,n){
var dis = n.distCode.substring(0,2) || '99';
var dis4 = n.distCode.substring(0,4);
if(dis4 == '4401' || dis4 == '4403') dis = dis4;
if(dis in h){
h[dis]['child'].push({
id: n.id,
name: n.displayName
});
}else{
h[dis] = {
name: getcity(dis),
child: [{
id: n.id,
name: n.displayName
}]
};
}
});
that.hos = h;
});
that.dep.length < 1 && $.get('/propagate/gainBigDepartments')
.done(function(d){
that.dep = [].concat(JSON.parse(d));
});
that.loadExp(1);
function getcity(id){
var discodes = {
'11' : '北京',
'31' : '上海',
'36' : '江西',
'42' : '湖北',
'43' : '湖南',
'44' : '广东',
'51' : '华西',
'4401' : '广州',
'4403' : '深圳',
'99' : '未知'
};
return id in discodes ? discodes[id] : (id || '未知');
}
},
methods: {
tapdd: function(key, value, txt){
if(key == 'cityid' && value == '-1'){
this.hosid = '-1';
}else if(key == 'bigdepid' && value == '-1'){
this.depid = '-1';
}
if(value){
this[key] != value ?
(this[key] = value,this.filter[key] = txt) :
(this[key] = '',this.filter[key] = '');
}
if(key == 'cityid' || key == 'bigdepid'){
value == '-1' && this.loadExp(1);
}else{
this.loadExp(1);
}
},
select: function(info){
this.expid = info.specialId;
this.info = info;
this.$emit('select');
},
imgSrc: function(src){
return BASE.imgsrc(src);
},
loadExp: function(no){
var that = this;
that.isload = true;
no && $.get('/docadmin/loadExperts',{
hosid: that.hosid,
docask: that.docask,
//bigDepId: that.bigdepid,
depId: that.depid,
duty: that.dutyid,
keywords: that.keywords,
pageNumber: no || 1,
pageSize: 12
})
.done(function(d){
if(BASE.isLost(d)) return BASE.checkLogin(),0;
that.pager = d.pager;
})
.always(function(){
that.isload = false;
})
}
}
})
});
});
Vue.component('my-selecttime', function (resolve, reject) {
$.get('ajax/form/selectexptime.html')
.done(function (d) {
resolve({
props: {
oid: { type: String },
expid: { type: String }
},
data: function(){
return {
timeid: '',
timename: '',
sdate: '',
sdates: [],
times: [],
info: {},
isload: false
};
},
template: d,
methods: {
imgSrc: function(src){
return BASE.imgsrc(src);
},
getTimes: function(){
var that = this;
that.isload = true;
$.post('/wzjh/gainSpecialTimes',{sid: this.expid, sdate: new Date(this.sdate).Format('yyyy-MM-dd') })
.done(function(d){
that.times = d.times || [];
})
.always(function(){
that.isload = false;
});
},
fillTimes: function(s){
this.sdate = s;
this.getTimes();
},
select: function(tid, tname){
this.timeid = tid;
this.timename = tname;
this.$emit('select');
}
},
created: function(){
var that = this;
createHead();
getExpinfo();
function createHead(){
var total = 7,arr = [];
var today = new Date(),day = today.getDate(),week,cdate,ymd,md;
for(var i = 0;i < total; i++){
cdate = new Date(),cdate.setDate(day + i);
md = [cdate.getMonth() + 1, cdate.getDate()];
ymd = [cdate.getFullYear()].concat(md);
week = getWeek(cdate.getDay());
arr.push({
w: week,
ymd: ymd.join('-'),
md: md.join('/')
});
}
that.sdates = arr;
that.fillTimes(arr[0].ymd);
}
function getWeek(week){
var day;
switch (week){
case 0:day="周日";break;
case 1:day="周一";break;
case 2:day="周二";break;
case 3:day="周三";break;
case 4:day="周四";break;
case 5:day="周五";break;
case 6:day="周六";break;
}
return day;
}
function getExpinfo(){
$.post('/kangxin/gainspedetail',{docid: that.expid})
.done(function(d){
that.info = d.special || {};
});
}
}
})
});
});
Vue.component('my-pay', function (resolve, reject) {
$.get('ajax/form/pay.html')
.done(function (d) {
resolve({
props: {
oid: { type: String },
haslisten: { type: Boolean, default: true },
pay: { type: Object },
money: { type: Number }
},
data: function(){
return {
islisten: true,
timer: 400
};
},
template: d,
watch:{
pay: {
handler: function (val, oldVal) {
val.code_url && val.code_url != oldVal.code_url && this.init()
},
deep: true
}
},
mounted: function(){
this.pay.code_url && this.init()
},
methods: {
init: function(){
var that = this;
this.haslisten && this.listen();
window.setTimeout(function(){that.islisten = false},this.timer * 1000),
this.timeleave();
},
listen: function(){
var that = this;
this.paystate(that.payok,function(){
window.setTimeout(that.listen,3000);
});
},
paystate: function(ok,fail){
var that = this;
this.islisten && this.pay.out_trade_no &&
$.post('/kangxin/listenpaystatus',{tradeno:this.pay.out_trade_no})
.done(function(d){
d.status == 'success' ? ok() : fail();
debugState && console.log('正在监听支付状态');
})
.fail(function(){
debugState && console.log('支付监听失败');
});
},
timeleave: function(){
(this.timer -= 1) && window.setTimeout(this.timeleave,1000);
},
payok: function(){
this.islisten = false;
this.$emit('payok');
}
},
destroyed: function(){
this.islisten = false;
debugState && console.log('已销毁支付监听');
}
})
});
});
Vue.component('my-webupload', function (resolve, reject) {
$.get('ajax/form/webupload.html')
.done(function (d) {
resolve({
template: d,
props: {
id: { type: String, default: 'file-list' },
oid: { type: String, default: '' },
onlyimg: { type: Boolean, default: true },
btn: { type: Boolean, default: true },
list: { type: Array, default: function () { return [] } },
edit: { type: Boolean, default: true },
editname: { type: Boolean, default: false },
single: { type: Boolean, default: false }
},
data: function () {
return {
imglist: [],
old: [],
isload: false,
issave: false,
OBJ: {}
}
},
computed: {
ids: function () {
return (function (a) {
var arr = [];
$.each(a, function (i, n) {
arr.push(n.id);
});
return arr;
})(this.imglist);
},
urls: function(){
return (function (a) {
var arr = [];
$.each(a, function (i, n) {
arr.push(n.fileUrl);
});
return arr;
})(this.imglist);
}
},
created: function () {
this.imglist = [].concat(this.list || []);
},
watch: {
list: function (n, o) {
this.imglist = [].concat(this.list || []);
},
imglist: function (n, o) {
JSON.stringify(n) != JSON.stringify(o) && window.setTimeout(this.initViewer,1000);
},
edit: function(n, o){
if(n == true) this.old = this.imglist;
}
},
methods: {
imgsrc: function(src){
return BASE.imgsrc(src, 'img/avatars/64.png');
},
initViewer: function(){
var that = this;
loadCss('js/plugin/imgviewer/viewer.css', function () {
loadScript('js/plugin/imgviewer/viewer.min.js', function () {
that.OBJ.imgViewer && that.OBJ.imgViewer.viewer('destroy');
debugState && console.log('-------初始化图片查看-------');
that.OBJ.imgViewer = $('#' + that.id + '.diyUpload .fileBoxUl').viewer({
url: 'data-src',
navbar: true,
title: false,
transition: false,
built: function () {
$('#' + that.id + ' .viewer-canvas').bind('click', function (event) {
event.target.localName != 'img' && that.OBJ.imgViewer.viewer('hide');
});
}
});
//$(window).trigger('scroll');
});
});
},
success: function () {
this.$emit('success');
},
isImg: function (val) {
var filetype = (val||'').split('.').pop();
return jQuery.inArray(filetype.toLowerCase(), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'tif']) != -1;
},
removeImage: function (val) {
var list = [].concat(this.imglist);
var arridx = BASE.arrayFindObjIndex(val, 'id', list);
arridx != -1 && list.splice(arridx, 1);
this.imglist = list;
this.success();
},
saveFileName: function (id, val) {
if (!val) return false;
var oldForm = this.old.list;
var oidx = BASE.arrayFindObjIndex(id, 'id', oldForm || []);
var oName = oidx != -1 ? oldForm[oidx].fileName : '';
if (val == oName) return false;
var that = this;
$.post('/doctor/updatefname', { fid: id, filename: val })
.done(function () {
oidx != -1 && (oldForm[oidx].fileName = val);
$.smallBox({
title: "修改为“" + val + "”,成功",
color: $.color.success,
timeout: 3000
});
that.success();
})
.fail(function () {
$.smallBox({
title: "修改“" + val + "”,失败!",
color: $.color.error,
iconSmall: "fa fa-times"
});
});
},
showVideo: function (e) {
var tet = $(e.target).find('source').attr('src');
BASE.showModel({
cls: 'modalvideo',
text: '<button type="button" onclick="BASE.closeModel()" class="close fixed-close">×</button>' + '<iframe name="videojsiframe" src="' + BASE.href + 'sea-modules/videojs/examples/index.html?src=' + tet + '" frameborder="no" border="0" allowscriptaccess="always" marginwidth="0" marginheight="0" allowfullscreen="true" wmode="opaque" allowTransparency="true" type="application/x-shockwave-flash"></iframe>'
});
}
},
mounted: function () {
$('#' + this.id + '_addfiles').size() && loadWebUploader(this);
function loadWebUploader(that) {
loadScript("js/plugin/webuploader/webuploader.min.js", function () {
loadScript("js/plugin/webuploader/upload.base.js", function () {
var _type = that.onlyimg;
debugState && console.log('-------初始化图片上传控件-------');
that.OBJ.webUploader = $('#' + that.id + '_addfiles').Uploader({
server: BASE.href + 'doctor/uploadLocalFile',
formData: { orderid: that.oid },
pick: {
multiple: !that.single
},
duplicate: true,
thumb: {
width: 100,
height: 100,
quality: 70,
allowMagnify: false,
crop: true,
type: "image/jpeg"
},
accept: {
title: "Files",
extensions: (function () {
return _type ? 'gif,jpg,jpeg,bmp,png' : 'gif,jpg,jpeg,bmp,png,mp4,avi,webm,mkv,mov,rm,ogg.ogv';
})(),
mimeTypes: (function () {
return _type ? 'image/jpg,image/jpeg,image/bmp,image/png,' : "image/jpg,image/jpeg,image/bmp,image/png,video/mp4,video/avi,video/webm,video/mkv"
})()
},
success: function (liobj, val) {
var fileid = liobj.attr('id').replace('fileBox_', '');
var img = liobj.find('img');
img.size() < 1 && (img = liobj.find('source'));
var obj = {
id: val,
thumb: img.attr('src') || '',
fileType: liobj.find('img').size() ? 'jpg' : 'mp4',
fileUrl: img.attr('data-src') || img.attr('src'),
fileName: liobj.find('.diyFileName').text()
};
if(val){
if (that.single) {
that.imglist = [].concat([obj]);
} else {
that.imglist = that.imglist.concat([obj]);
}
}else{
$.smallBox({title: "文件上传",content:"文件上传失败,请重试",color: $.color.error,iconSmall: "fa fa-times",timeout: 3000});
}
that.OBJ.webUploader.removeFile(fileid);
$('#' + that.id + '.diyUpload .browser[data-id="' + val + '"]').remove();
that.success();
},
afterpost: function () {
//重置图片查看器
//that.OBJ.imgViewer.viewer('destroy').viewer();
}
});
// $(window).bind("scroll",function(){
// var st = $(window).scrollTop(), sth = st + $(window).height();
// $('.vue img[data-src]').each(function(){
// var o = $(this), post = o.offset().top, posb = post + o.height();
// if ((post > st && post < sth) || (posb > st && posb < sth)) {
// this.getAttribute('src') != this.getAttribute('data-src') && o.attr('src', o.attr('data-src'));
// }
// });
// }).trigger('scroll');
});
});
}
},
destroyed: function() {
try{
this.OBJ.imgViewer && this.OBJ.imgViewer.viewer('destroy');
}catch(e){
//debugState && console.log('imgViewer.destroy', e);
}
try{
this.OBJ.webUploader && this.OBJ.webUploader.destroy();
}catch(e){
//debugState && console.log('webUploader.destroy', e);
}
}
})
})
});
Vue.component('my-report', function (resolve, reject) {
$.get('ajax/form/report.html')
.done(function (d) {
resolve({
props: {
oid: { type: String, default: '' },
list: { type: Object, default: function () { return {} } },
edit: { type: Boolean, default: true },
otype: { type: String, default: '' },
status:{ type: Number }
},
data: function () {
return {
tab: '1'
}
},
template: d,
methods: {
sendreport: function () {
Page.tab = this.tab
BASE.showModel({
remote: 'ajax/modal-content/modal-report.html',
cls: 'modal-lg'
});
},
expreport: function () {
BASE.showModel({
remote: 'ajax/modal-content/modal-report-word.html',
cls: 'modal-lg'
});
},
maxImgShow: function(){
Page.maximg = this.list.photoReport
BASE.showModel({
remote: 'ajax/modal-content/modal-max-image.html',
backdrop: true,
cls: 'modal-lg'
});
}
},
computed: {
usertype: function(){
return Page.mainForms.usertype == 'receive'
}
}
})
})
});
Vue.component('my-room', function (resolve, reject) {
$.get('ajax/form/room.html')
.done(function (d) {
resolve({
template: d,
props: {
oid: { type: String, default: '' },
docask: { type: String, default: '' },
room: { type: Boolean, default: false },
video: { type: Boolean, default: false },
footer: { type: Boolean, default: false },
status: { type: Number }
},
data: function () {
return {
roomid: '',
expInfo: {
info: {
specialName: '未分配'
},
state: false
},
otype: Page.otype,
utype: SStorage.get('_token_utype'),
sysMsg: [],
userMsg: [],
sendtext: '',
isInit: true,
initMsg: '准备初使化',
initImg: '../img/loading/31.gif',
playId: '',
playLength: null,
frame: '_blank.html',
openStatus: false
}
},
computed: {
framesrc: function() {
return 'video.html?oid='+ this.oid +'&utype='+ this.utype +'&otype=' + this.otype + '&status=' + +this.openStatus
}
},
methods: {
showPic: function(idx){
var item = this.userMsg[idx];
Page.media = item;
BASE.showModel({
remote: 'ajax/modal-content/modal-media.html',
backdrop: true
});
},
playMedia: function(idx){
var that = this;
var item = this.userMsg[idx];
if(this.playId == item.msgContent){
this.playId = ''
return false;
}
this.playId = item.msgContent;
if(!this.playId){
return alert('播放异常,找不到文件。'), false;
}
this.playLength = Math.floor(this.playId.length / 1024) + 1;
if (that.playId && typeof RongIMLib != 'undefined' && ('RongIMVoice' in RongIMLib)) {
RongIMLib.RongIMVoice.init();
RongIMLib.RongIMVoice.preLoaded(that.playId, function(){
RongIMLib.RongIMVoice.play(that.playId, that.playLength)
RongIMLib.RongIMVoice.onprogress = function(){
that.playLength--
!that.playLength && (that.playId = '')
}
})
}
},
roomsuccess: function () {
this.$emit('roomsuccess');
},
sendMsg: function () {
var t = this.sendtext;
if(!t) return this.sendtext = '', 0;
sendmessage(t, this);
this.userMsg.push({
"sendType": Page.utype,
"msgContent": t,
"msgType": "RC:TxtMsg",
"fileUrl": null
});
this.sendtext = '';
function sendmessage(text, that) {
var msg = new RongIMLib.TextMessage({
content: text,
extra: Page.ouid + ","+ Page.otype +","+ Page.order.docName +",3" });
var conversationtype = RongIMLib.ConversationType.GROUP; // 私聊
RongIMClient.getInstance().sendMessage(conversationtype, that.roomid, msg, {
onSuccess: function (message) {
// savemessage(text);
},
onError: errorIM
});
}
},
loadroom: function(){
var that = this;
//初始化聊天对象详情
loadUID(function () {
checkRoomState(that);
});
//初始化聊天功能
this.status == 20 && initRongIM(that);
//加载聊天历史消息
loadMessage(that);
this.roomsuccess();
//初始化room可缩放功能
initResizable();
},
toemjc (text) {
if (typeof RongIMLib != 'undefined' && 'RongIMEmoji' in RongIMLib) {
return RongIMLib.RongIMEmoji.emojiToHTML(text)
} else {
return text
}
},
newWindow: function() {
this.openStatus = 'footer' in Page ? Page.footer.isBegin : false;
window.frames['videoiframe'].location.replace(this.frame);
document.getElementById('videoiframe').style.display = 'none';
Page.popup = window.open(this.framesrc, "newwin", "height=480,width=960,toolbar=no,menubar=no,alwaysRaised=yes,depended=yes,location=no");
},
backIframe: function() {
this.openStatus = 'footer' in Page ? Page.footer.isBegin : false;
window.frames['videoiframe'].location.replace(this.framesrc);
document.getElementById('videoiframe').style.display = 'block';
Page.popup = window.frames['videoiframe'];
}
},
watch:{
sendtext: function(n, o){
this.sendtext = n.replace('\n','')
},
room: function(n,o){
if(!n) return 0;
this.loadroom();
},
video: function(n,o){
if(!n) return 0;
window.setTimeout(this.backIframe);
},
userMsg: {
deep: true,
handler: function(){
this.$nextTick(scrollMsgToView);
function scrollMsgToView() {
$('.side-column .messagelist dd:last').size() && $('.side-column .messagelist dd:last')[0].scrollIntoView(true);
}
}
}
},
mounted: function(){
var that = this;
this.room && this.loadroom();
this.video && this.backIframe();
},
destroyed: function(){
try{
RongIMClient && RongIMClient.getInstance &&RongIMClient.getInstance().disconnect();
}catch(e){
//debugState && console.log('RongIMClient.getInstance().disconnect', e);
}
try {
Page.popup && Page.popup.close();
} catch (error) {}
}
})
});
function initRongIM(that){
var data = { type: Page.usertype == 'receive' ? 2 : 3, oid: Page.oid, otype: Page.otype };
$.get('/doctor/gainIMToken', data)
.done(function (d) {
debugState && console.log('-----gainIMToken------', d);
if (d.appkey && d.token) {
initIMLib(that, d.appkey, d.token), that.roomid = d.userId;
} else {
that.initMsg = '初使化失败';
that.initImg = '../img/noresult.png';
}
});
}
function checkRoomState(vue) {
$.get('/doctor/isPeerPresence', {
userId: Page._uid,
userType: Page.utype,
orderId: Page.oid
})
.done(function (d) {
sessionStorage.setItem('_remote_info',JSON.stringify(d.peer))
d.result && (vue.expInfo.state = d.result == 'true');
d.peer && (vue.expInfo.info = d.peer);
Page.footer.online = vue.expInfo.state;
});
}
function loadUID(callback) {
if (Page._uid) return callback(), 0;
$.get('/doctor/showbasicinfo')
.done(function (d) {
d.special.specialId && (
Page._uid = d.special.specialId, callback()
);
})
}
function loadMessage(a) {
$.get('/doctor/loadmessages',{
oid: Page.oid,
docask: a.docask,
vtype: Page.utype == '2' ? '3' : '2'
}).done(function(d){
a.userMsg = (a.userMsg).concat(d.messages || []);
}).always(function(){
RongIMLib.RongIMEmoji.init();
});
}
function initResizable(){
window.setTimeout(function(){
$( ".side-column-fixed" ).resizable({
handles: "w",
minWidth: 240,
resize: function( event, ui ) {
var out = ui.element.parent();
var vdo = ui.element.find('header.videos .video-eles section');
ui.element.css({'left': 'auto'});
out.css({'width': ui.size.width});
vdo.css('height', ui.size.width * 0.75);
$('#vue-footer').css('right', ui.size.width);
}
});
},1600);
}
function initIMLib(room, key, token){
RongIMClient.init(key);
RongIMClient.setConnectionStatusListener({
onChanged: function (status) {
room.isInit = true;
switch (status) {
case RongIMLib.ConnectionStatus.CONNECTED:
room.initMsg = '链接成功';
room.isInit = false;
break;
case RongIMLib.ConnectionStatus.CONNECTING:
room.initMsg = '正在链接';
break;
case RongIMLib.ConnectionStatus.DISCONNECTED:
room.initMsg = '断开连接';
room.initImg = '../img/noresult.png';
break;
case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
room.initMsg = '其他设备登录';
room.initImg = '../img/noresult.png';
break;
case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
room.initMsg = '网络不可用';
room.initImg = '../img/noresult.png';
break;
}
}
});
// 消息监听器
RongIMClient.setOnReceiveMessageListener({
// 接收到的消息
onReceived: function (message) {
if (message.targetId != room.roomid){
debugState && console.log('targetId不一置的消息');
return 0;
}
// 判断消息类型
if(message.offLineMessage){
debugState && console.log('我接收到的离线消息为:', message);
return 0;
}
var item = {
"sendType": Page.utype == 3 ? 2 : 3,
"msgContent": ''
}
switch (message.messageType) {
case RongIMClient.MessageType.TextMessage:
item.msgContent = message.content.content;
item.msgType = 'RC:TxtMsg';
break;
case RongIMClient.MessageType.ImageMessage:
var msgcontent = 'data:image/'+ (message.content.content.slice(0, 1) == '/' ? 'jpeg' : 'png') +';base64,' + message.content.content
item.msgContent = msgcontent;
item.fileUrl = message.content.imageUri;
item.msgType = 'RC:ImgMsg';
break;
case RongIMClient.MessageType.VoiceMessage:
item.msgContent = message.content.content;
item.msgType = 'RC:VcMsg';
break;
default:
item = null;
// 自定义消息
// do something...
}
item && room.userMsg.push(item);
debugState && console.log('我接收到的消息为:', message);
}
});
// 连接融云服务器。
RongIMClient.connect(token, {
onSuccess: function (userId) {
debugState && console.log("Login successfully." + userId);
},
onTokenIncorrect: function () {
debugState && console.log('token无效');
},
onError: errorIM
});
}
function errorIM(errorCode, message) {
var info = '';
switch (errorCode) {
case RongIMLib.ErrorCode.TIMEOUT:
info = '超时';
break;
case RongIMLib.ErrorCode.UNKNOWN_ERROR:
info = '未知错误';
break;
case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
info = '在黑名单中,无法向对方发送消息';
break;
case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
info = '不在讨论组中';
break;
case RongIMLib.ErrorCode.NOT_IN_GROUP:
info = '不在群组中';
break;
case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
info = '不在聊天室中';
break;
case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
info = '不可接受的协议版本';
break;
case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
info = 'appkey不正确';
break;
case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
info = '服务器不可用';
break;
default:
info = 'XX';
break;
}
debugState && console.log('发送失败:', info);
}
});
Vue.component('my-selectdep', function (resolve, reject) {
$.get('ajax/form/selectdep.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
}
},
data: function(){
return {
keywords: '',
ylt: '',
yltInd: 0,
yltId: '',
yltName: '',
hos: '',
hosInd: 0,
hosId: '',
hosName: '',
dep: '',
depInd: -1,
depId: '',
depName: '',
isload: true,
isdep: false,
ishos: true,
loadHosName: [],
loadHosNames: [],
search: ''
}
},
created: function(){
this.ylt = Page.ylt
this.gethos(0)
},
methods: {
addyltClass: function (ind){
this.yltInd = ind
this.isload = true;
this.loadHosName = []
this.gethos(ind)
},
addhosClass: function (ind, item){
this.hosInd = ind
this.isload = true
this.getdep(ind, item)
this.$emit('addhos-class', this.hosId, this.depId)
},
adddepClass: function (ind){
this.depInd = ind
this.depId = this.dep[ind].id
this.depName = this.dep[ind].displayName
this.$emit('adddep-class', this.hosId, this.depId)
},
gethos: function (ind) {
var that = this
that.hosInd = 0
that.yltId = that.ylt[ind].id
that.yltName = that.ylt[ind].yltName
that.dep = ''
that.ishos = true
$.get('/docadmin/gainhoshealthmember', { hhaId: that.yltId })
.done(function(data){
that.hos = data.members;
that.ishos = false
that.getdep(0)
that.loadHosName=[];
that.loadHosNames=[];
$.each(that.hos, function(ind, val){
var obj = {}
obj.displayName = val.displayName
obj.hosLevel = val.hosLevel
that.loadHosName.push(obj)
that.loadHosNames.push(obj)
})
})
},
getdep: function (ind, item){
var that = this;
if(item){
function findObj (obj){
if(obj.displayName == item.displayName){
that.hosId = obj.id
that.hosName = obj.displayName
}
}
var array = that.hos.find ( findObj )
}
else{
that.hosId = that.hos[ind].id
that.hosName = that.hos[ind].displayName
}
this.depInd = -1
that.depId = ''
that.depName = ''
$.get('/docadmin/gaindepsbyhos', { hosId: that.hosId })
.done(function(data){
that.isload = false;
that.dep = data.departs
that.dep.length?
that.isdep = false:
that.isdep = true
})
},
loadHos: function(){
var that = this
if( !that.search ){
that.hosInd = -1;
that.loadHosName = that.loadHosNames
}else {
that.loadHosName = []
$.each(this.loadHosNames, function(ind, val){
if(val.displayName.indexOf(that.search) != -1){
that.loadHosName = that.loadHosName.concat(val)
}
})
}
}
},
template: d
})
});
});
Vue.component('my-selectdoc',function(resolve, reject){
$.get('ajax/form/selectdoc.html')
.done(function (d) {
resolve({
props: {
oid: { type: String },
eid: { type: Number },
dtype:{ type: Number}
},
data: function(){
return {
selected: 0,
tab: 'area',
areaid: '',
list_areaid: '',
keywords: '',
discodes: '',
hosid: -1,
cityid: '',
depid: -1,
area: [],
hos: [],
dep: [],
pager: {
list: []
},
expid: '',
info: {},
filter:{
areaid: '',
hosid:'',
depid:'',
bigdepid:'',
},
isload: false,
loader: true
};
},
template: d,
created: function(){
var that = this;
this.expid = this.eid;
that.loader = true
//城市列表
$.get('/docadmin/gainopencitys',{type: 3})
.done(function(data){
that.loader = false
that.area = data.pros
})
//医院列表
that.getHos('')
//获取科室
$.get('/kangxin/gainStandDeps')
.done(function(d){
that.dep = d.sdeps
})
that.loadDoc(-1, 1)
},
methods: {
tapdd: function(key, value, txt){
switch(key){
case 'cityid':
this[key] = value;
this.selected = 1;
this.areaid='';
this.discodes= value
this.list_areaid ='';
this.hosid= -1;
this.filter.hosid= '';
this.filter.areaid = txt; break;
case 'areaid':
this[key] = value;
this.discodes= value
this.selected = 2;
this.list_areaid ='';
this.hosid= -1;
this.filter.hosid= '';
this.filter.areaid = txt; break;
case 'list_areaid':
this.discodes= value
this[key] = value;
this.selected = 3;
this.hosid= -1;
this.filter.hosid= '';
this.filter.areaid = txt; break;
case 'hosid':
case 'depid':
this[key] = value;
this.filter[key] = txt; break;
}
this.loadDoc(-1, 1)
this.discodes?
this.getHos(this.discodes):
this.getHos('')
},
hosClick: function (){
},
getHos: function(discode){
var that = this
$.get('/propagate/gainHospitalsByArea', {distcode: discode, type: -1})
.done(function(data){
that.hos = data.hospitals
})
},
select: function(info){
this.expid = info.specialId;
this.info = info;
this.$emit('select');
},
imgSrc: function(src){
return BASE.imgsrc(src);
},
loadDoc: function(page){
var that = this;
that.isload = true;
var str = '';
this.eid == 1? str +='/docadmin/loadExpertOrDoctors': str+= '/docadmin/loadDoctors'
page && $.get( str ,{
distCode: that.discodes,
hosid: that.hosid,
depId: that.depid,
keywords: that.keywords,
pageNumber: page || 1,
pageSize: 12,
dtype: that.dtype
})
.done(function(d){
if(BASE.isLost(d)) return BASE.checkLogin(),0;
that.pager = d.pager;
})
.always(function(){
that.isload = false;
})
}
}
})
});
});
Vue.component('my-requirement', function (resolve, reject) {
$.get('ajax/form/requirement.html')
.done(function (d) {
resolve({
props: {
requir: {
type: Object
}
},
template: d
})
});
});
Vue.component('my-record', function (resolve, reject) {
$.get('ajax/form/record.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Object
}
},
template: d,
methods: {
synchrecordWithUpload: function () {
$('#recordfiles_addfiles input').trigger('click');
},
recordfileok: function () {
Page.mainForms.othersForm.form.img_list = this.$refs.recordfiles.imglist,
Page.mainForms.othersForm.form.img_list_ids = this.$refs.recordfiles.ids
}
}
})
});
});
Vue.component('my-enclosure', function (resolve, reject) {
$.get('ajax/form/enclosure.html')
.done(function (d) {
resolve({
props: {
fdata: {
type: Array
},
// readonly: {
// type: Boolean,
// deafult: false
// },
caseid: [String, Number]
},
template: d,
data: function () {
return {
timer: '',
ind: 0,
attachments: [],
allType: {'1': 'CT', '2': 'DX', '3': 'MR', '4': 'DCM', '5': 'IMG', '99': '其他','6':'检查报告','7':'影像图片'},
OBJ: {},
isbtn: false,
arrN:[],
isShow: false
}
},
created: function (){
// 获取类型
$.get('/docadmin/gainSysDicList/3')
.done(function(d){
Page.encloType = d.dictionaries
})
this.attachments = this.fdata || []
this.isShow = sessionStorage.getItem('_token_utype') == 3 ? true: false
},
mounted: function (){
var that = this
$(document).bind( 'changeenclo', function (a){
that.attachments = JSON.parse(sessionStorage.getItem('_catch_attachments_'))
})
},
watch: {
fdata: function (o, n){
this.attachments = o
},
attachments: function (o, n){
o != n && window.setTimeout(this.initViewer, 1000)
var arr = []
o.forEach(function (item) {
arr.push({
id: item.id || '',
type: item.type,
reportTime: item.reportTime,
remark: item.remark,
attachmentIds: (item.attachmentIds instanceof Array) ? item.attachmentIds.join(',') : item.attachmentIds
})
})
this.$emit('attach', arr)
}
},
methods: {
initViewer: function (){
var that = this
loadCss('js/plugin/imgviewer/viewer.css', function () {
loadScript('js/plugin/imgviewer/viewer.min.js', function () {
that.OBJ.imgViewer && that.OBJ.imgViewer.viewer('destroy');
that.OBJ.imgViewer = $('#enclosure .attachments').viewer({
url: 'data-src',
navbar: true,
title: false,
transition: false,
built: function () {
$('#enclosure .viewer-canvas').bind('click', function (event) {
event.target.localName != 'img' && that.OBJ.imgViewer.viewer('hide');
});
}
});
});
});
},
// 新增或编辑
enclosureupload: function (ids){
this.timer = ids || new Date().getTime()
sessionStorage.setItem('_catch_time_name_', (this.timer || this.attachments.createTime))
sessionStorage.setItem('_catch_attachments_', JSON.stringify(this.attachments))
BASE.showModel({
remote: 'ajax/modal-content/modal-enclo.html',
cls: 'modal-lg'
});
},
imgsrc: function(src){
return BASE.imgsrc(src, 'img/avatars/64.png');
},
// 删除
del: function (ind){
if(confirm("确定要删除吗?")){
this.attachments.splice(ind, 1)
sessionStorage.setItem('_catch_attachments_', JSON.stringify(this.attachments))
$(document).trigger('changeenclo')
let arr=[]
this.attachments.forEach(function (item) {
arr.push({
id: item.id || '',
type: item.type,
reportTime: item.reportTime,
remark: item.remark,
attachmentIds: (item.attachmentIds instanceof Array) ? item.attachmentIds.join(',') : item.attachmentIds
})
})
this.arrN = arr;
this.submitEnclo();
}
},
submitEnclo: function(){
this.saveForm('editCaseInfo', {
'attachments': JSON.stringify({'attachments': this.arrN}),
}, this.encloForm, '病例附件')
},
saveForm: function(fun, data, d, title){
data.caseid = this.caseid;
data.oid = Page.oid;
data.otype = Page.otype;
$.post('/doctor/' + fun, data)
.done(function () {
$.smallBox({
title: "保存提示",
content: title + "修改成功",
color: $.color.success,
timeout: 3000
});
})
.fail(function () {
$.smallBox({
title: "保存提示",
content: title + "修改失败",
color: $.color.error,
iconSmall: "fa fa-times"
});
})
}
}
})
});
});
|
devinrsmith/deephaven-core | Base/src/test/java/io/deephaven/base/TestStringUtils.java | package io.deephaven.base;
import io.deephaven.base.testing.BaseArrayTestCase;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.TreeSet;
/**
* Unit tests for StringUtils.
*/
public class TestStringUtils extends BaseArrayTestCase {
public void testJoinStrings() {
Collection<String> strings = new LinkedHashSet<>();
strings.add("Foo");
strings.add("Bar");
strings.add("Baz");
assertEquals("Foo,Bar,Baz", StringUtils.joinStrings(strings, ","));
assertEquals("Foo/Bar/Baz", StringUtils.joinStrings(strings.stream(), "/"));
assertEquals("Foo\nBar\nBaz", StringUtils.joinStrings(strings.iterator(), "\n"));
assertEquals("", StringUtils.joinStrings(Collections.emptyList(), "\n"));
Collection<Integer> objects = new TreeSet<>();
objects.add(3);
objects.add(1);
objects.add(7);
objects.add(2);
assertEquals("1\n2\n3\n7", StringUtils.joinStrings(objects, "\n"));
assertEquals("1\\3\\7", StringUtils.joinStrings(objects.stream().filter(i -> i % 2 != 0), "\\"));
assertEquals("1,2,3,7", StringUtils.joinStrings(objects.iterator(), ","));
}
}
|
anubhavparas/ARIAC_Group_1 | rwa5_group_1/docs/html/search/all_3.js | <filename>rwa5_group_1/docs/html/search/all_3.js
var searchData=
[
['deactivategripper',['deactivateGripper',['../classGantryControl.html#a1485577d4e29baf708a4c5c028a47798',1,'GantryControl']]],
['detected_5fconveyor_5f',['detected_conveyor_',['../classSensorControl.html#afa8478ce26058f853686d6f43c9ddae4',1,'SensorControl']]],
['dyn_5fobs_5fpos_5fpub_5f',['dyn_obs_pos_pub_',['../classDynamicObs.html#a24d2b65adf814d0fb636e39ed1d13448',1,'DynamicObs']]],
['dynamic_5fobs_2ecpp',['dynamic_obs.cpp',['../dynamic__obs_8cpp.html',1,'']]],
['dynamic_5fobs_2eh',['dynamic_obs.h',['../dynamic__obs_8h.html',1,'']]],
['dynamic_5fobstacle_5f1_5fsubscriber_5f',['dynamic_obstacle_1_subscriber_',['../classGantryControl.html#a1cb6b441dc3cd08aed97cb9ff9ba5363',1,'GantryControl']]],
['dynamic_5fobstacle_5f2_5fsubscriber_5f',['dynamic_obstacle_2_subscriber_',['../classGantryControl.html#abec9e915a281322c5a97c4ffba2aecdd',1,'GantryControl']]],
['dynamic_5fobstacle_5fcallback',['dynamic_obstacle_callback',['../classGantryControl.html#a86401fc5629111c946ea683e0846aa9d',1,'GantryControl']]],
['dynamicobs',['DynamicObs',['../classDynamicObs.html',1,'DynamicObs'],['../classDynamicObs.html#af39e0dd9c3e06dbabaf338ce22e86a66',1,'DynamicObs::DynamicObs()']]]
];
|
psygate/Ivory | gen/java/com/psygate/minecraft/spigot/sovereignty/ivory/db/model/Tables.java | /**
* This class is generated by jOOQ
*/
package com.psygate.minecraft.spigot.sovereignty.ivory.db.model;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupInvites;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupMembers;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupMutes;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroups;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryPlayerMutes;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryPlayerSettings;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvorySubGroups;
import com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryTokens;
import javax.annotation.Generated;
/**
* Convenience access to all tables in nucleus
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Tables {
/**
* The table nucleus.ivory_groups
*/
public static final IvoryGroups IVORY_GROUPS = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroups.IVORY_GROUPS;
/**
* The table nucleus.ivory_group_invites
*/
public static final IvoryGroupInvites IVORY_GROUP_INVITES = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupInvites.IVORY_GROUP_INVITES;
/**
* The table nucleus.ivory_group_members
*/
public static final IvoryGroupMembers IVORY_GROUP_MEMBERS = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupMembers.IVORY_GROUP_MEMBERS;
/**
* The table nucleus.ivory_group_mutes
*/
public static final IvoryGroupMutes IVORY_GROUP_MUTES = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryGroupMutes.IVORY_GROUP_MUTES;
/**
* The table nucleus.ivory_player_mutes
*/
public static final IvoryPlayerMutes IVORY_PLAYER_MUTES = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryPlayerMutes.IVORY_PLAYER_MUTES;
/**
* The table nucleus.ivory_player_settings
*/
public static final IvoryPlayerSettings IVORY_PLAYER_SETTINGS = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryPlayerSettings.IVORY_PLAYER_SETTINGS;
/**
* The table nucleus.ivory_sub_groups
*/
public static final IvorySubGroups IVORY_SUB_GROUPS = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvorySubGroups.IVORY_SUB_GROUPS;
/**
* The table nucleus.ivory_tokens
*/
public static final IvoryTokens IVORY_TOKENS = com.psygate.minecraft.spigot.sovereignty.ivory.db.model.tables.IvoryTokens.IVORY_TOKENS;
}
|
aberke/city-science-bike-swarm | Archive/nrf5_gcc_mesh/mesh/bootloader/include/dfu_types_mesh.h | /* Copyright (c) 2010 - 2020, Nordic Semiconductor ASA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DFU_TYPES_H__
#define DFU_TYPES_H__
#include <stdint.h>
#include <stdbool.h>
#include "compiler_abstraction.h"
#include "nordic_common.h"
#include "nrf.h"
#if defined(MBR_PRESENT) || defined(SOFTDEVICE_PRESENT)
#include "nrf_mbr.h"
/**< The currently configured start address of the bootloader. If 0xFFFFFFFF, no bootloader start
* address is configured. */
#define BOOTLOADERADDR() ((*(uint32_t *)MBR_BOOTLOADER_ADDR) == 0xFFFFFFFF ? \
*MBR_UICR_BOOTLOADER_ADDR : *(uint32_t *)MBR_BOOTLOADER_ADDR)
#else
/**< Check UICR, just in case. */
#define BOOTLOADERADDR() (NRF_UICR->NRFFW[0])
#endif
#ifdef NRF51
#define PAGE_SIZE (0x400)
#ifndef FLASH_SIZE
#define FLASH_SIZE (PAGE_SIZE * 256)
#endif
#define END_OF_RAM (0x20000000 + NRF_FICR->SIZERAMBLOCKS * NRF_FICR->NUMRAMBLOCK)
#endif
#ifdef NRF52_SERIES
#define PAGE_SIZE (0x1000)
#ifndef FLASH_SIZE
#if defined NRF52840_XXAA
#define FLASH_SIZE (1024 * 1024)
#else
#define FLASH_SIZE (1024 * 512)
#endif
#endif
#define END_OF_RAM (0x20000000 + NRF_FICR->INFO.RAM * 1024)
#endif
#define WORD_SIZE (4)
#define SEGMENT_ADDR(segment_id, start_addr) ((segment_id == 1)? \
(uint32_t) start_addr : \
(((uint32_t) start_addr) & 0xFFFFFFF0) + ((segment_id) - 1) * 16)
#define ADDR_SEGMENT(addr, start_addr) (uint32_t)(((((uint32_t) addr) - ((uint32_t) start_addr & 0xFFFFFFFF0)) >> 4) + 1)
#define PAGE_ALIGN(p_pointer) (((uint32_t) p_pointer) & (~((uint32_t) (PAGE_SIZE - 1))))
#define PAGE_OFFSET(p_pointer) (((uint32_t) p_pointer) & (PAGE_SIZE - 1))
#define NRF_UICR_BOOT_START_ADDRESS (NRF_UICR_BASE + 0x14) /**< Register where the bootloader start address is stored in the UICR register. */
#define NRF_UICR_MBR_PARAM_ADDRESS (NRF_UICR_BASE + 0x18) /**< Register where the MBR Parameter address is stored in the UICR register. */
#define BOOTLOADER_INFO_ADDRESS (FLASH_SIZE - 1 * PAGE_SIZE)
#define BOOTLOADER_INFO_BANK_ADDRESS (FLASH_SIZE - 2 * PAGE_SIZE)
#define SEGMENT_LENGTH (16)
#define DFU_AUTHORITY_MAX (0x07)
#define DFU_FWID_LEN_APP (10)
#define DFU_FWID_LEN_BL (2)
#define DFU_FWID_LEN_SD (2)
#define SERIAL_PACKET_OVERHEAD (1)
#define DFU_PUBLIC_KEY_LEN (64)
#define DFU_SIGNATURE_LEN (64)
#define BL_INFO_LEN_PUBLIC_KEY (DFU_PUBLIC_KEY_LEN)
#define BL_INFO_LEN_SEGMENT (sizeof(bl_info_segment_t))
#define BL_INFO_LEN_FWID (sizeof(fwid_t))
#define BL_INFO_LEN_FLAGS (sizeof(bl_info_flags_t))
#define BL_INFO_LEN_SIGNATURE (DFU_SIGNATURE_LEN)
#define BL_INFO_LEN_BANK_SIGNED (sizeof(bl_info_bank_t))
#define BL_INFO_LEN_BANK (BL_INFO_LEN_BANK_SIGNED - DFU_SIGNATURE_LEN)
typedef uint16_t segment_t;
typedef uint16_t seq_t;
typedef enum
{
DFU_TYPE_NONE = 0,
DFU_TYPE_SD = (1 << 0),
DFU_TYPE_BOOTLOADER = (1 << 1),
DFU_TYPE_APP = (1 << 2),
DFU_TYPE_BL_INFO = (1 << 3),
} dfu_type_t;
typedef struct __attribute((packed))
{
uint32_t company_id;
uint16_t app_id;
uint32_t app_version;
} app_id_t;
typedef struct __attribute((packed))
{
uint8_t id;
uint8_t ver;
} bl_id_t;
typedef struct __attribute((packed))
{
uint16_t sd;
bl_id_t bootloader;
app_id_t app;
} fwid_t;
typedef union __attribute((packed))
{
app_id_t app;
bl_id_t bootloader;
uint16_t sd;
} fwid_union_t;
typedef enum
{
BL_INFO_TYPE_INVALID = 0x00,
BL_INFO_TYPE_ECDSA_PUBLIC_KEY = 0x01,
BL_INFO_TYPE_VERSION = 0x02,
BL_INFO_TYPE_FLAGS = 0x04,
BL_INFO_TYPE_SEGMENT_SD = 0x10,
BL_INFO_TYPE_SEGMENT_BL = 0x11,
BL_INFO_TYPE_SEGMENT_APP = 0x12,
BL_INFO_TYPE_SIGNATURE_SD = 0x1A,
BL_INFO_TYPE_SIGNATURE_BL = 0x1B,
BL_INFO_TYPE_SIGNATURE_APP = 0x1C,
BL_INFO_TYPE_SIGNATURE_BL_INFO = 0x1D,
BL_INFO_TYPE_BANK_BASE = 0x20, /**< Only for adding offset to get the correct entry. */
BL_INFO_TYPE_BANK_SD = 0x21,
BL_INFO_TYPE_BANK_BL = 0x22,
BL_INFO_TYPE_BANK_APP = 0x24,
BL_INFO_TYPE_BANK_BL_INFO = 0x28,
BL_INFO_TYPE_TEST = 0x100,
BL_INFO_TYPE_LAST = 0x7FFF,
BL_INFO_TYPE_UNUSED = 0xFFFF,
} bl_info_type_t;
typedef struct
{
uint32_t start;
uint32_t length;
} bl_info_segment_t;
typedef enum
{
DFU_END_SUCCESS, /**< The transfer ended successfully. */
DFU_END_FWID_VALID, /**< The FWID was valid, and the bootloader stopped operation. */
DFU_END_APP_ABORT, /**< The application requested to abort the transfer. */
DFU_END_ERROR_PACKET_LOSS,
DFU_END_ERROR_UNAUTHORIZED,
DFU_END_ERROR_NO_START,
DFU_END_ERROR_TIMEOUT,
DFU_END_ERROR_NO_MEM,
DFU_END_ERROR_INVALID_PERSISTENT_STORAGE,
DFU_END_ERROR_SEGMENT_VIOLATION,
DFU_END_ERROR_MBR_CALL_FAILED,
DFU_END_ERROR_INVALID_TRANSFER,
DFU_END_ERROR_BANK_IN_BOOTLOADER_AREA,
DFU_END_ERROR_BANK_AND_DESTINATION_OVERLAP /**< When copying the finished bank to its intended destination, it will have to overwrite itself. */
} dfu_end_t;
typedef enum
{
DFU_STATE_INITIALIZED, /**< The DFU module has been initialized, but not started. */
DFU_STATE_FIND_FWID, /**< There's no DFU operation in progress. */
DFU_STATE_DFU_REQ, /**< Beaconing requests for transfers. */
DFU_STATE_READY, /**< Ready to receive a transfer. */
DFU_STATE_TARGET, /**< Receiving a transfer. */
DFU_STATE_VALIDATE, /**< Validating and finishing up a transfer. */
DFU_STATE_STABILIZE, /**< Waiting for metadata about validated transfer to be written. */
DFU_STATE_RELAY_CANDIDATE, /**< Beaconing intent to relay a transfer. */
DFU_STATE_RELAY /**< Passively relaying a transfer. */
} dfu_state_t;
/** The various roles a device can play in a dfu transfer. */
typedef enum
{
DFU_ROLE_NONE, /**< No role. */
DFU_ROLE_TARGET, /**< The target role. A receiver of a transfer. */
DFU_ROLE_RELAY, /**< The relay role. A passive forwarding role. */
DFU_ROLE_SOURCE /**< The source role. The originator of a transfer. */
} dfu_role_t;
/** Current state of a transfer. */
typedef struct
{
dfu_role_t role; /**< This device's intended role in the transfer. */
dfu_type_t type; /**< The DFU type of the transfer. */
fwid_union_t fwid; /**< The FWID of the new data in the transfer. */
dfu_state_t state; /**< The current global state of the transfer. */
uint8_t data_progress; /**< The progress of the transfer in percent (0-100). */
} dfu_transfer_state_t;
/** DFU Bank info structure. */
typedef struct
{
dfu_type_t dfu_type; /**< DFU type of the bank. */
fwid_union_t fwid; /**< Firmware ID of the bank. */
bool is_signed; /**< Flag indicating whether the bank is signed with an encryption key. */
uint32_t* p_start_addr; /**< Start address of the bank. */
uint32_t length; /**< Length of the firmware in the bank. */
} dfu_bank_info_t;
typedef fwid_t bl_info_version_t;
typedef struct
{
uint32_t sd_intact : 1;
uint32_t bl_intact : 1;
uint32_t app_intact : 1;
uint32_t page_is_invalid : 1;
} bl_info_flags_t;
/**
* State of info bank. Written to allow state machine progression being stored
* in flash without needing erase.
*/
typedef enum
{
BL_INFO_BANK_STATE_IDLE = 0xFF, /**< The bank has not been touched since it got transferred. */
BL_INFO_BANK_STATE_FLASH_FW = 0xFE, /**< In the process of flashing the bank. */
BL_INFO_BANK_STATE_FLASH_META = 0xFC, /**< In the process of flashing metadata (signature and firmware) */
BL_INFO_BANK_STATE_FLASHED = 0xF8, /**< The bank has been flashed, and can be invalidated. */
} bl_info_bank_state_t;
typedef struct
{
uint32_t* p_bank_addr;
uint32_t length;
fwid_union_t fwid;
bool has_signature;
bl_info_bank_state_t state;
uint8_t signature[BL_INFO_LEN_SIGNATURE];
} bl_info_bank_t;
typedef union
{
uint8_t public_key[BL_INFO_LEN_PUBLIC_KEY];
uint8_t signature[BL_INFO_LEN_SIGNATURE];
bl_info_segment_t segment;
bl_info_version_t version;
bl_info_flags_t flags;
bl_info_bank_t bank;
} bl_info_entry_t;
#endif /* DFU_TYPES_H__ */
|
vpnvishv/hive | ql/src/test/org/apache/hadoop/hive/ql/hooks/TestHiveProtoLoggingHook.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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.hadoop.hive.ql.hooks;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.ql.QueryPlan;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.exec.mr.ExecDriver;
import org.apache.hadoop.hive.ql.exec.tez.TezTask;
import org.apache.hadoop.hive.ql.hooks.HiveProtoLoggingHook.EventLogger;
import org.apache.hadoop.hive.ql.hooks.HiveProtoLoggingHook.EventType;
import org.apache.hadoop.hive.ql.hooks.HiveProtoLoggingHook.ExecutionMode;
import org.apache.hadoop.hive.ql.hooks.HiveProtoLoggingHook.OtherInfoType;
import org.apache.hadoop.hive.ql.hooks.HookContext.HookType;
import org.apache.hadoop.hive.ql.hooks.proto.HiveHookEvents.HiveHookEventProto;
import org.apache.hadoop.hive.ql.hooks.proto.HiveHookEvents.MapFieldEntry;
import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.apache.hadoop.hive.ql.plan.HiveOperation;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.TezWork;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.yarn.util.SystemClock;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.history.logging.proto.DatePartitionedLogger;
import org.apache.tez.dag.history.logging.proto.ProtoMessageReader;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestHiveProtoLoggingHook {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private HiveConf conf;
private HookContext context;
private String tmpFolder;
@Before
public void setup() throws Exception {
conf = new HiveConf();
conf.set(HiveConf.ConfVars.LLAP_DAEMON_QUEUE_NAME.varname, "llap_queue");
conf.set(HiveConf.ConfVars.HIVE_PROTO_EVENTS_QUEUE_CAPACITY.varname, "3");
conf.set(MRJobConfig.QUEUE_NAME, "mr_queue");
conf.set(TezConfiguration.TEZ_QUEUE_NAME, "tez_queue");
tmpFolder = folder.newFolder().getAbsolutePath();
conf.setVar(HiveConf.ConfVars.HIVE_PROTO_EVENTS_BASE_PATH, tmpFolder);
QueryState state = new QueryState.Builder().withHiveConf(conf).build();
@SuppressWarnings("serial")
QueryPlan queryPlan = new QueryPlan(HiveOperation.QUERY) {};
queryPlan.setQueryId("test_queryId");
queryPlan.setQueryStartTime(1234L);
queryPlan.setQueryString("SELECT * FROM t WHERE i > 10");
queryPlan.setRootTasks(new ArrayList<>());
queryPlan.setInputs(new HashSet<>());
queryPlan.setOutputs(new HashSet<>());
PerfLogger perf = PerfLogger.getPerfLogger(conf, true);
context = new HookContext(queryPlan, state, null, "test_user", "192.168.10.10",
"hive_addr", "test_op_id", "test_session_id", "test_thread_id", true, perf, null);
}
@Test
public void testPreEventLog() throws Exception {
context.setHookType(HookType.PRE_EXEC_HOOK);
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
evtLogger.handle(context);
evtLogger.shutdown();
HiveHookEventProto event = loadEvent(conf, tmpFolder);
Assert.assertEquals(EventType.QUERY_SUBMITTED.name(), event.getEventType());
Assert.assertEquals(1234L, event.getTimestamp());
Assert.assertEquals(System.getProperty("user.name"), event.getUser());
Assert.assertEquals("test_user", event.getRequestUser());
Assert.assertEquals("test_queryId", event.getHiveQueryId());
Assert.assertEquals("test_op_id", event.getOperationId());
Assert.assertEquals(ExecutionMode.NONE.name(), event.getExecutionMode());
Assert.assertFalse(event.hasQueue());
assertOtherInfo(event, OtherInfoType.TEZ, Boolean.FALSE.toString());
assertOtherInfo(event, OtherInfoType.MAPRED, Boolean.FALSE.toString());
assertOtherInfo(event, OtherInfoType.CLIENT_IP_ADDRESS, "192.168.10.10");
assertOtherInfo(event, OtherInfoType.SESSION_ID, "test_session_id");
assertOtherInfo(event, OtherInfoType.THREAD_NAME, "test_thread_id");
assertOtherInfo(event, OtherInfoType.HIVE_INSTANCE_TYPE, "HS2");
assertOtherInfo(event, OtherInfoType.HIVE_ADDRESS, "hive_addr");
assertOtherInfo(event, OtherInfoType.CONF, null);
assertOtherInfo(event, OtherInfoType.QUERY, null);
}
@Test
public void testQueueLogs() throws Exception {
context.setHookType(HookType.PRE_EXEC_HOOK);
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
// This makes it MR task
context.getQueryPlan().getRootTasks().add(new ExecDriver());
evtLogger.handle(context);
// This makes it Tez task
MapWork mapWork = new MapWork();
TezWork tezWork = new TezWork("test_queryid");
tezWork.add(mapWork);
TezTask task = new TezTask();
task.setId("id1");
task.setWork(tezWork);
context.getQueryPlan().getRootTasks().add(task);
context.getQueryPlan().getRootTasks().add(new TezTask());
evtLogger.handle(context);
// This makes it llap task
mapWork.setLlapMode(true);
evtLogger.handle(context);
evtLogger.shutdown();
ProtoMessageReader<HiveHookEventProto> reader = getTestReader(conf, tmpFolder);
HiveHookEventProto event = reader.readEvent();
Assert.assertNotNull(event);
Assert.assertEquals(ExecutionMode.MR.name(), event.getExecutionMode());
Assert.assertEquals(event.getQueue(), "mr_queue");
event = reader.readEvent();
Assert.assertNotNull(event);
Assert.assertEquals(ExecutionMode.TEZ.name(), event.getExecutionMode());
Assert.assertEquals(event.getQueue(), "tez_queue");
event = reader.readEvent();
Assert.assertNotNull(event);
Assert.assertEquals(ExecutionMode.LLAP.name(), event.getExecutionMode());
Assert.assertEquals(event.getQueue(), "llap_queue");
}
@org.junit.Ignore("might fail intermittently")
@Test
public void testDropsEventWhenQueueIsFull() throws Exception {
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
context.setHookType(HookType.PRE_EXEC_HOOK);
evtLogger.handle(context);
evtLogger.handle(context);
evtLogger.handle(context);
evtLogger.handle(context);
evtLogger.shutdown();
ProtoMessageReader<HiveHookEventProto> reader = getTestReader(conf, tmpFolder);
reader.readEvent();
reader.readEvent();
reader.readEvent();
try {
reader.readEvent();
Assert.fail("Expected 3 events due to queue capacity limit, got 4.");
} catch (EOFException expected) {}
}
@Test
public void testPreAndPostEventBoth() throws Exception {
context.setHookType(HookType.PRE_EXEC_HOOK);
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
evtLogger.handle(context);
context.setHookType(HookType.POST_EXEC_HOOK);
evtLogger.handle(context);
evtLogger.shutdown();
ProtoMessageReader<HiveHookEventProto> reader = getTestReader(conf, tmpFolder);
HiveHookEventProto event = reader.readEvent();
Assert.assertNotNull("Pre hook event not found", event);
Assert.assertEquals(EventType.QUERY_SUBMITTED.name(), event.getEventType());
event = reader.readEvent();
Assert.assertNotNull("Post hook event not found", event);
Assert.assertEquals(EventType.QUERY_COMPLETED.name(), event.getEventType());
}
@Test
public void testPostEventLog() throws Exception {
context.setHookType(HookType.POST_EXEC_HOOK);
context.getPerfLogger().PerfLogBegin("test", "LogTest");
context.getPerfLogger().PerfLogEnd("test", "LogTest");
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
evtLogger.handle(context);
evtLogger.shutdown();
HiveHookEventProto event = loadEvent(conf, tmpFolder);
Assert.assertEquals(EventType.QUERY_COMPLETED.name(), event.getEventType());
Assert.assertEquals(System.getProperty("user.name"), event.getUser());
Assert.assertEquals("test_user", event.getRequestUser());
Assert.assertEquals("test_queryId", event.getHiveQueryId());
Assert.assertEquals("test_op_id", event.getOperationId());
assertOtherInfo(event, OtherInfoType.STATUS, Boolean.TRUE.toString());
String val = findOtherInfo(event, OtherInfoType.PERF);
Map<String, Long> map = new ObjectMapper().readValue(val,
new TypeReference<Map<String, Long>>() {});
// This should be really close to zero.
Assert.assertTrue("Expected LogTest in PERF", map.get("LogTest") < 100);
}
@Test
public void testFailureEventLog() throws Exception {
context.setHookType(HookType.ON_FAILURE_HOOK);
EventLogger evtLogger = new EventLogger(conf, SystemClock.getInstance());
evtLogger.handle(context);
evtLogger.shutdown();
HiveHookEventProto event = loadEvent(conf, tmpFolder);
Assert.assertEquals(EventType.QUERY_COMPLETED.name(), event.getEventType());
Assert.assertEquals(System.getProperty("user.name"), event.getUser());
Assert.assertEquals("test_user", event.getRequestUser());
Assert.assertEquals("test_queryId", event.getHiveQueryId());
Assert.assertEquals("test_op_id", event.getOperationId());
assertOtherInfo(event, OtherInfoType.STATUS, Boolean.FALSE.toString());
assertOtherInfo(event, OtherInfoType.PERF, null);
}
@Test
public void testRolloverFiles() throws Exception {
long waitTime = 100;
context.setHookType(HookType.PRE_EXEC_HOOK);
conf.setTimeDuration(ConfVars.HIVE_PROTO_EVENTS_ROLLOVER_CHECK_INTERVAL.varname, waitTime,
TimeUnit.MICROSECONDS);
Path path = new Path(tmpFolder);
FileSystem fs = path.getFileSystem(conf);
AtomicLong time = new AtomicLong();
EventLogger evtLogger = new EventLogger(conf, () -> time.get());
evtLogger.handle(context);
int statusLen = 0;
// Loop to ensure that we give some grace for scheduling issues.
for (int i = 0; i < 3; ++i) {
Thread.sleep(waitTime + 100);
statusLen = fs.listStatus(path).length;
if (statusLen > 0) {
break;
}
}
Assert.assertEquals(1, statusLen);
// Move to next day and ensure a new file gets created.
time.set(24 * 60 * 60 * 1000 + 1000);
for (int i = 0; i < 3; ++i) {
Thread.sleep(waitTime + 100);
statusLen = fs.listStatus(path).length;
if (statusLen > 1) {
break;
}
}
Assert.assertEquals(2, statusLen);
}
private ProtoMessageReader<HiveHookEventProto> getTestReader(HiveConf conf, String tmpFolder)
throws IOException {
Path path = new Path(tmpFolder);
FileSystem fs = path.getFileSystem(conf);
FileStatus[] status = fs.listStatus(path);
Assert.assertEquals(1, status.length);
status = fs.listStatus(status[0].getPath());
Assert.assertEquals(1, status.length);
DatePartitionedLogger<HiveHookEventProto> logger = new DatePartitionedLogger<>(
HiveHookEventProto.PARSER, path, conf, SystemClock.getInstance());
return logger.getReader(status[0].getPath());
}
private HiveHookEventProto loadEvent(HiveConf conf, String tmpFolder) throws IOException {
ProtoMessageReader<HiveHookEventProto> reader = getTestReader(conf, tmpFolder);
HiveHookEventProto event = reader.readEvent();
Assert.assertNotNull(event);
return event;
}
private String findOtherInfo(HiveHookEventProto event, OtherInfoType key) {
for (MapFieldEntry otherInfo : event.getOtherInfoList()) {
if (otherInfo.getKey().equals(key.name())) {
return otherInfo.getValue();
}
}
Assert.fail("Cannot find key " + key);
return null;
}
private void assertOtherInfo(HiveHookEventProto event, OtherInfoType key, String value) {
String val = findOtherInfo(event, key);
if (value != null) {
Assert.assertEquals(value, val);
}
}
}
|
jingcao80/Elastos | Build/Prebuilt/Linux/usr/include/alljoyn/AboutObj.h | /**
* @file
* This contains the About class
*/
/******************************************************************************
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#ifndef _ALLJOYN_ABOUT_H
#define _ALLJOYN_ABOUT_H
#include <alljoyn/AboutDataListener.h>
#include <alljoyn/AboutListener.h>
#include <alljoyn/BusAttachment.h>
#include <alljoyn/BusObject.h>
namespace ajn {
/**
* An AllJoyn BusObject that implements the org.alljoyn.About interface.
*
* This BusObject is used to announce the capabilities and other identifying details
* of the application or device.
*/
class AboutObj : public BusObject {
public:
/**
* version of the org.alljoyn.About interface
*/
static const uint16_t VERSION;
/**
* create a new About class
*
* This will also register the About BusObject on the passed in BusAttachment
*
* The AboutObj class is responsible for transmitting information about the
* interfaces that are available for other applications to use. It also
* provides application specific information that is contained in the
* AboutDataListener class
*
* It also provides means for applications to respond to certain requests
* concerning the interfaces.
*
* By default the org.alljoyn.About interface is excluded from the list of
* announced interfaces. Since simply receiving the announce signal tells
* the client that the service implements the org.alljoyn.About interface.
* There are some legacy applications that expect the org.alljoyn.About
* interface to be part of the announcement. Changing the isAnnounced flag
* from UNANNOUNCED, its default, to ANNOUNCED will cause the org.alljoyn.About
* interface to be part of the announce signal. Unless your application is
* talking with a legacy application that expects the org.alljoyn.About
* interface to be part of the announce signal it is best to leave the
* isAnnounced to use its default value.
*
* @param[in] bus the BusAttachment that will contain the about information
* @param[in] isAboutIntfAnnounced will the org.alljoyn.About interface be
* part of the announced interfaces.
*/
AboutObj(BusAttachment& bus, AnnounceFlag isAboutIntfAnnounced = UNANNOUNCED);
virtual ~AboutObj();
/**
* This is used to send the Announce signal. It announces the list of all
* interfaces available at given object paths as well as the announced
* fields from the AboutData.
*
* This method will automatically obtain the Announced ObjectDescription from the
* BusAttachment that was used to create the AboutObj. Only BusObjects that have
* marked their interfaces as announced and are registered with the
* BusAttachment will be announced.
*
* @see BusAttachment::RegisterBusObject
* @see BusObject::AddInterface
*
* @param sessionPort the session port the interfaces can be connected with
* @param aboutData the AboutDataListener that contains the AboutData for
* this announce signal.
*
* @return
* - ER_OK on success
* - ER_ABOUT_SESSIONPORT_NOT_BOUND if the SessionPort given is not bound
*/
QStatus Announce(SessionPort sessionPort, AboutDataListener& aboutData);
/**
* Cancel the last announce signal sent. If no signals have been sent this
* method call will return.
*
* @return
* - ER_OK on success
* - another status indicating failure.
*/
QStatus Unannounce();
private:
/**
* Handles GetAboutData method
* @param[in] member
* @param[in] msg reference of AllJoyn Message
*/
void GetAboutData(const InterfaceDescription::Member* member, Message& msg);
/**
* Handles GetObjectDescription method
* @param[in] member
* @param[in] msg reference of AllJoyn Message
*/
void GetObjectDescription(const InterfaceDescription::Member* member, Message& msg);
/**
* Handles the GetPropery request
* @param[in] ifcName interface name
* @param[in] propName the name of the properly
* @param[in] val reference of MsgArg out parameter.
* @return ER_OK if successful.
*/
QStatus Get(const char* ifcName, const char* propName, MsgArg& val);
/**
* check that the MsgArg returned from AboutDataListener.GetAboutData
* contains all the required fields
* Fields are:
* - AppId
* - DefaultLanguage
* - DeviceId
* - AppName
* - Manufacture
* - ModelNumber
* - SupportedLanguages
* - Description
* - SoftwareVersion
* - AJSoftwareVersion
*
* @param aboutDataArg MsgArg containing the AboutData fields.
*
* return true if it contains all the required fields
*/
bool HasAllRequiredFields(MsgArg& aboutDataArg);
/**
*
* check that the MsgArg returned from AboutDataListener.GetAnnouncedAboutData
* contains all the required fields
* Fields are:
* - AppId
* - DefaultLanguage
* - DeviceId
* - AppName
* - Manufacture
* - ModelNumber
*
* @param announcedDataArg MsgArg containging the announced AboutData fields.
*
* return true if it contains all the required fields
*/
bool HasAllAnnouncedFields(MsgArg& announcedDataArg);
/**
* Check that the values in the Announced Fields and the Requried Fields
* agree.
*
* @param aboutDataArg MsgArg containing the AboutData fields.
* @param announcedDataArg MsgArg containging the announced AboutData fields.
*
* @return true if the announced AboutData and the AboutData fields match
*/
bool AnnouncedDataAgreesWithAboutData(MsgArg& aboutDataArg, MsgArg& announcedDataArg);
/**
* Validate individual AboutData fields to make sure they meet requirements.
*
* @param aboutDataArg MsgArg containing the AboutData fields.
*
* @return
* - #ER_OK if all checked fields are good
* - Error status indicating otherwise
*/
QStatus ValidateAboutDataFields(MsgArg& aboutDataArg);
/**
* pointer to BusAttachment
*/
BusAttachment* m_busAttachment;
MsgArg m_objectDescription;
AboutDataListener* m_aboutDataListener;
uint32_t m_announceSerialNumber;
};
}
#endif
|
niallthomson/microservices-demo | src/ui/src/main/java/com/watchn/ui/util/ecs/MissingAwsECSEnvironmentCondition.java | <gh_stars>1-10
package com.watchn.ui.util.ecs;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class MissingAwsECSEnvironmentCondition extends AwsECSEnvironmentCondition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !super.matches(context, metadata);
}
} |
cosmos33/MMVideoSDK--iOS | VideoSDK/Framwork/MLMediaEditingModel/MLMediaEditingModel.framework/Headers/MLTransitionEffect.h | //
// MLTransitionEffect.h
// Pods
//
// Created by YuAo on 16/05/2017.
//
//
@import Mantle;
NS_ASSUME_NONNULL_BEGIN
typedef NSString *MLTransitionEffectType NS_EXTENSIBLE_STRING_ENUM;
FOUNDATION_EXPORT MLTransitionEffectType const MLTransitionEffectTypeNone;
@interface MLTransitionEffect : MTLModel <MTLJSONSerializing>
@property (nonatomic,readonly,copy) NSDictionary<NSString *, id> *parameters;
@property (nonatomic,readonly,copy) MLTransitionEffectType type;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithType:(MLTransitionEffectType)type parameters:(NSDictionary<NSString *, id> *)parameters NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
|
xtutran/grad-projects | monitoring/src/main/java/com/github/xtutran/ui/ReportPanel.java | package com.github.xtutran.ui;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author Orrmaster
*/
public class ReportPanel extends javax.swing.JFrame {
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea2;
/**
* Creates new form ReportPanel
*/
public ReportPanel() {
initComponents();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
// <editor-fold defaultstate="collapsed"
// desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase
* /tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ReportPanel.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ReportPanel.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ReportPanel.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ReportPanel.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ReportPanel().setVisible(true);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Report");
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout
.setHorizontalGroup(layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout
.createSequentialGroup()
.addContainerGap()
.addGroup(
layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jScrollPane2,
javax.swing.GroupLayout.DEFAULT_SIZE,
380,
Short.MAX_VALUE)
.addGroup(
layout
.createSequentialGroup()
.addComponent(
jLabel1)
.addGap(
0,
0,
Short.MAX_VALUE)))
.addContainerGap()));
layout
.setVerticalGroup(layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout
.createSequentialGroup()
.addContainerGap(
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(
jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE,
256,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap()));
pack();
}// </editor-fold>
public void setText(String report) {
jTextArea2.setText(report);
}
// End of variables declaration
}
|
harverywxu/erda | modules/dop/services/sonar_metric_rule/paging.go | // Copyright (c) 2021 Terminus, 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 sonar_metric_rule
import (
"fmt"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/dop/dao"
"github.com/erda-project/erda/pkg/http/httpserver"
"github.com/erda-project/erda/pkg/i18n"
)
func (svc *Service) Paging(req apistructs.SonarMetricRulesPagingRequest, local *i18n.LocaleResource) (httpserver.Responser, error) {
setDefaultValue(&req)
paging, err := svc.db.PagingSonarMetricRules(req)
if err != nil {
return nil, err
}
// 查询系统默认的key
rule := dao.QASonarMetricRules{
ScopeID: "-1",
ScopeType: "platform",
}
defaultDbRules, err := svc.db.ListSonarMetricRules(&rule)
if err != nil {
return nil, err
}
// 假如数据库没有就设置默认值
if paging == nil || paging.List == nil {
paging.List = defaultDbRules
return httpserver.OkResp(paging)
}
// 数据库中有用户的 key, 就在最前面设置上系统默认的 key
list := paging.List
dbRules := list.([]dao.QASonarMetricRules)
defaultDbRules = append(defaultDbRules, dbRules...)
var rules []*apistructs.SonarMetricRuleDto
for _, dbRule := range defaultDbRules {
apiRule := dbRule.ToApi()
setMetricKeyDesc(apiRule, local)
rules = append(rules, apiRule)
}
paging.List = rules
return httpserver.OkResp(paging)
}
func setDefaultValue(req *apistructs.SonarMetricRulesPagingRequest) {
if req.PageNo <= 0 {
req.PageNo = 1
}
if req.PageSize <= 0 {
req.PageSize = 1000
}
}
func setMetricKeyDesc(apiRule *apistructs.SonarMetricRuleDto, local *i18n.LocaleResource) {
if apiRule == nil {
return
}
sonarMetricKey := apistructs.SonarMetricKeys[apiRule.MetricKeyID]
if sonarMetricKey == nil {
return
}
// 国际化
localDesc := getMetricKeyLocal(apiRule.MetricKey, local)
if localDesc == "" {
apiRule.MetricKeyDesc = sonarMetricKey.MetricKeyDesc
} else {
apiRule.MetricKeyDesc = localDesc
}
apiRule.ValueType = sonarMetricKey.ValueType
apiRule.DecimalScale = sonarMetricKey.DecimalScale
}
func getMetricKeyLocal(key string, local *i18n.LocaleResource) string {
if local == nil {
return ""
}
return local.Get(fmt.Sprintf("metric.%s.description", key))
}
|
pokulo/trickytripper | app/src/main/java/de/koelle/christian/trickytripper/export/impl/StyleClass.java | <gh_stars>10-100
package de.koelle.christian.trickytripper.export.impl;
public enum StyleClass {
NUMERIC_VALUE("valueNumeric"),
HEADING("heading"),
BACKGROUND_PAYER("bgPayer"),
BACKGROUND_SPENDER("bgSpender"),
/**/;
private final String className;
StyleClass(String className) {
this.className = className;
}
public String getClassName() {
return this.className;
}
}
|
Keneral/ae1 | jacoco/org.jacoco.core.test/src/org/jacoco/core/runtime/RuntimeDataTest.java | /*******************************************************************************
* Copyright (c) 2009, 2015 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME> - initial API and implementation
*
*******************************************************************************/
package org.jacoco.core.runtime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.Callable;
import org.jacoco.core.test.TargetLoader;
import org.junit.Before;
import org.junit.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Unit tests for {@link RuntimeData}.
*
*/
public class RuntimeDataTest {
private RuntimeData data;
private TestStorage storage;
@Before
public void setup() {
data = new RuntimeData();
storage = new TestStorage();
}
@Test
public void testGetSetSessionId() {
assertNotNull(data.getSessionId());
data.setSessionId("test-id");
assertEquals("test-id", data.getSessionId());
}
@Test
public void testGetProbes() {
Object[] args = new Object[] { Long.valueOf(123), "Foo",
Integer.valueOf(3) };
data.equals(args);
assertEquals(3, ((boolean[]) args[0]).length);
data.collect(storage, storage, false);
boolean[] data = (boolean[]) args[0];
assertEquals(3, data.length, 0.0);
assertFalse(data[0]);
assertFalse(data[1]);
assertFalse(data[2]);
assertSame(storage.getData(123).getProbes(), data);
assertEquals("Foo", storage.getData(123).getName());
}
@Test
public void testCollectEmpty() {
data.collect(storage, storage, false);
storage.assertSize(0);
}
@Test
public void testCollectWithReset() {
data.setSessionId("testsession");
boolean[] probes = data.getExecutionData(Long.valueOf(123), "Foo", 1)
.getProbes();
probes[0] = true;
data.collect(storage, storage, true);
assertFalse(probes[0]);
assertEquals("testsession", storage.getSessionInfo().getId());
}
@Test
public void testCollectWithoutReset() {
data.setSessionId("testsession");
boolean[] probes = data.getExecutionData(Long.valueOf(123), "Foo", 1)
.getProbes();
probes[0] = true;
data.collect(storage, storage, false);
assertTrue(probes[0]);
assertEquals("testsession", storage.getSessionInfo().getId());
}
@Test
public void testEquals() {
assertTrue(data.equals(data));
}
@Test
public void testHashCode() {
assertEquals(System.identityHashCode(data), data.hashCode());
}
@Test
public void testGenerateArgumentArray() throws Exception {
final ClassWriter writer = new ClassWriter(0);
writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null,
"java/lang/Object",
new String[] { Type.getInternalName(Callable.class) });
// Constructor
MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
"()V", null, new String[0]);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>",
"()V", false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// call()
mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call",
"()Ljava/lang/Object;", null, new String[0]);
mv.visitCode();
RuntimeData.generateArgumentArray(1000, "Sample", 15, mv);
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(5, 1);
mv.visitEnd();
writer.visitEnd();
final TargetLoader loader = new TargetLoader();
Callable<?> callable = (Callable<?>) loader.add("Sample",
writer.toByteArray()).newInstance();
final Object[] args = (Object[]) callable.call();
assertEquals(3, args.length, 0.0);
assertEquals(Long.valueOf(1000), args[0]);
assertEquals("Sample", args[1]);
assertEquals(Integer.valueOf(15), args[2]);
}
@Test
public void testGenerateAccessCall() throws Exception {
final boolean[] probes = data.getExecutionData(Long.valueOf(1234),
"Sample", 5).getProbes();
final ClassWriter writer = new ClassWriter(0);
writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null,
"java/lang/Object",
new String[] { Type.getInternalName(Callable.class) });
// Constructor
MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
"(Ljava/lang/Object;)V", null, new String[0]);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>",
"()V", false);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitFieldInsn(Opcodes.PUTFIELD, "Sample", "access",
"Ljava/lang/Object;");
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
// call()
mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call",
"()Ljava/lang/Object;", null, new String[0]);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(Opcodes.GETFIELD, "Sample", "access",
"Ljava/lang/Object;");
RuntimeData.generateAccessCall(1234, "Sample", 5, mv);
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(6, 1);
mv.visitEnd();
writer.visitField(Opcodes.ACC_PRIVATE, "access", "Ljava/lang/Object;",
null, null);
writer.visitEnd();
final TargetLoader loader = new TargetLoader();
Callable<?> callable = (Callable<?>) loader
.add("Sample", writer.toByteArray())
.getConstructor(Object.class).newInstance(data);
assertSame(probes, callable.call());
}
}
|
macro-kernel/shield-hids | shield_library/src/main/java/org/heimdall/shield_library/utility/RSAUtil.java | package org.heimdall.shield_library.utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAUtil {
private static Logger logger = LoggerFactory.getLogger(RSAUtil.class);
public static KeyPair getKeyPair() throws Exception {
try {
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keygen.initialize(1024, random);
KeyPair keyPair = keygen.generateKeyPair();
return keyPair;
} catch (NoSuchAlgorithmException exception) {
logger.error("RSA加密算法生成密钥对出错," + exception.toString());
throw exception;
}
}
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception exception) {
logger.error("RSA加密算法加密数据出错," + exception.toString());
throw exception;
}
}
public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception exception) {
logger.error("RSA加密算法解密数据出错," + exception.toString());
throw exception;
}
}
public static byte[] encrypt(byte[] data, String base64PublicKey) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(base64PublicKey));
return cipher.doFinal(data);
} catch (Exception exception) {
logger.error("RSA加密算法加密数据出错," + exception.toString());
throw exception;
}
}
public static byte[] decrypt(byte[] data, String base64PrivateKey) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(base64PrivateKey));
return cipher.doFinal(data);
} catch (Exception exception) {
logger.error("RSA加密算法解密数据出错," + exception.toString());
throw exception;
}
}
public static PublicKey getPublicKey(String base64PublicKey) throws Exception {
try {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes("UTF-8")));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (NoSuchAlgorithmException exception) {
logger.error("RSA加密算法获取公钥出错," +exception.toString());
throw exception;
} catch (InvalidKeySpecException exception) {
logger.error("RSA加密算法获取公钥出错," +exception.toString());
throw exception;
} catch (UnsupportedEncodingException exception) {
logger.error("RSA加密算法获取公钥出错," +exception.toString());
throw exception;
}
}
public static PrivateKey getPrivateKey(String base64PrivateKey) throws Exception {
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes("UTF-8")));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (NoSuchAlgorithmException exception) {
logger.error("RSA加密算法获取私钥出错," +exception.toString());
throw exception;
} catch (InvalidKeySpecException exception) {
logger.error("RSA加密算法获取私钥出错," +exception.toString());
throw exception;
} catch (UnsupportedEncodingException exception) {
logger.error("RSA加密算法获取私钥出错," +exception.toString());
throw exception;
}
}
public static String getBase64PublicKey(RSAPublicKey publicKey) {
return Base64.getEncoder().encodeToString(publicKey.getEncoded());
}
public static String getBase64PrivateKey(RSAPrivateKey privateKey) {
return Base64.getEncoder().encodeToString(privateKey.getEncoded());
}
} |
hasys/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-client/src/main/java/org/kie/workbench/common/stunner/bpmn/client/forms/fields/assignmentsEditor/AssignmentListItemWidgetView.java | <reponame>hasys/kie-wb-common
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.bpmn.client.forms.fields.assignmentsEditor;
import java.util.Set;
import org.jboss.errai.ui.client.widget.HasModel;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.i18n.StunnerFormsClientFieldsConstants;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.AssignmentRow;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.Variable.VariableType;
import org.kie.workbench.common.stunner.bpmn.client.forms.util.ListBoxValues;
public interface AssignmentListItemWidgetView extends HasModel<AssignmentRow> {
String CUSTOM_PROMPT = StunnerFormsClientFieldsConstants.INSTANCE.Custom() + ListBoxValues.EDIT_SUFFIX;
String ENTER_TYPE_PROMPT = StunnerFormsClientFieldsConstants.INSTANCE.Enter_type() + ListBoxValues.EDIT_SUFFIX;
String CONSTANT_PROMPT = StunnerFormsClientFieldsConstants.INSTANCE.Constant() + ListBoxValues.EDIT_SUFFIX;
String ENTER_CONSTANT_PROMPT = StunnerFormsClientFieldsConstants.INSTANCE.Enter_constant() + ListBoxValues.EDIT_SUFFIX;
void init();
void setParentWidget( ActivityDataIOEditorWidget parentWidget );
void setDataTypes( ListBoxValues dataTypeListBoxValues );
void setProcessVariables( ListBoxValues processVarListBoxValues );
void setShowConstants( boolean showConstants );
void setDisallowedNames( Set<String> disallowedNames, String disallowedNameErrorMessage );
void setAllowDuplicateNames( boolean allowDuplicateNames, String duplicateNameErrorMessage );
boolean isDuplicateName( String name );
VariableType getVariableType();
String getDataType();
void setDataType( String dataType );
String getProcessVar();
void setProcessVar( String processVar );
String getCustomDataType();
void setCustomDataType( String customDataType );
String getConstant();
void setConstant( String constant );
}
|
LucianoRomero1/Sigtea | web/bundles/js/feedLoots/formularioFL6.js | function agregarFila(){
$("#filas").append(`
<tr>
<th scope="row">1</th>
<td><input type="text" class="form-control" name="Recurso[tipo][]" value=""></td>
<td><input type="text" class="form-control" name="" value=""></td>
<td class="media">
<input type="text" class="form-control" name="" value="">
<a onClick="eliminarFila(this)" class="btn text-danger mt-2"><i class="far fa-trash-alt"></i></a>
</td>
</tr> `
);
reordenar();
}
function eliminarFila(fila){
fila.closest('tr').remove();
reordenar();
}
function reordenar(){
var num=1;
$('#filas tr').each(function(){
$(this).find('th').eq(0).text(num);
num++;
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.