max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,151 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/cache_storage/cache_storage_error.h"
#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom-blink.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/exception_code.h"
#include "third_party/blink/renderer/modules/cache_storage/cache.h"
namespace blink {
DOMException* CacheStorageError::CreateException(
mojom::CacheStorageError web_error) {
switch (web_error) {
case mojom::CacheStorageError::kErrorNotImplemented:
return DOMException::Create(kNotSupportedError,
"Method is not implemented.");
case mojom::CacheStorageError::kErrorNotFound:
return DOMException::Create(kNotFoundError, "Entry was not found.");
case mojom::CacheStorageError::kErrorExists:
return DOMException::Create(kInvalidAccessError, "Entry already exists.");
case mojom::CacheStorageError::kErrorQuotaExceeded:
return DOMException::Create(kQuotaExceededError, "Quota exceeded.");
case mojom::CacheStorageError::kErrorCacheNameNotFound:
return DOMException::Create(kNotFoundError, "Cache was not found.");
case mojom::CacheStorageError::kErrorQueryTooLarge:
return DOMException::Create(kAbortError, "Operation too large.");
case mojom::CacheStorageError::kErrorStorage:
return DOMException::Create(kUnknownError, "Unexpected internal error.");
case mojom::CacheStorageError::kSuccess:
// This function should only be called with an error.
break;
}
NOTREACHED();
return nullptr;
}
} // namespace blink
| 622 |
764 | <filename>erc20/0xA6446D655a0c34bC4F05042EE88170D056CBAf45.json
{"symbol": "CSP","address": "0xA6446D655a0c34bC4F05042EE88170D056CBAf45","overview":{"en": ""},"email": "<EMAIL>","website": "https://caspian.tech/","state": "NORMAL","links": {"blog": "https://caspian.tech/blog/","twitter": "https://twitter.com/Caspian_Tech","telegram": "https://t.me/Caspian_Tech","github": ""}} | 160 |
3,428 | {"id":"02181","group":"easy-ham-1","checksum":{"type":"MD5","value":"a7e15d16987b4db753c47d2ad7ebc84e"},"text":"From <EMAIL> Wed Oct 2 11:44:00 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>ass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id ECDC816F03\n\tfor <jm@localhost>; Wed, 2 Oct 2002 11:43:59 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 02 Oct 2002 11:43:59 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g92836K31829 for\n <<EMAIL>>; Wed, 2 Oct 2002 09:03:06 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy<EMAIL>int.org\nFrom: newscientist <<EMAIL>>\nSubject: Viruses that also hack computers on the rise\nDate: Wed, 02 Oct 2002 08:03:06 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://www.newsisfree.com/click/-2,8443955,1440/\nDate: Not supplied\n\nA new internet worm marks a worrying crossover between virus writing and \nhacking, say experts\n\n\n"} | 460 |
310 | #ifndef COMMAND_SOCKET_H
#define COMMAND_SOCKET_H
// Set PASS_STDFILES_UNIX_SOCKET if passing file descriptors
// over socket from client command to server, using sendmsg/recvmsg.
// I can't get this to work on MacOS.
// Alternatively, multiplex stdout, stderr, and exit code on connection socket.
// (PASS_STDFILES_UNIX_SOCKET seems in principle preferable, but isn't
// available on all platforms, and until there is a clear advantage,
// it seems better to disable for platform consistency and simpler testing.)
#define PREFER_PASS_STDFILES_UNIX_SOCKET 0
#define USING_NAMED_PIPES_FOR_CLIENT 0 /*for now*/
#if defined(__APPLE__) || USING_NAMED_PIPES_FOR_CLIENT || !PREFER_PASS_STDFILES_UNIX_SOCKET
#define PASS_STDFILES_UNIX_SOCKET 0
// Multiplex stdout, stderr, and exit code on connection socket.
// Next byte is exit code.
#define PASS_STDFILES_EXIT_CODE '\001'
// Send following bytes to stdout.
#define PASS_STDFILES_SWITCH_TO_STDOUT '\002'
// Send following bytes to stderr.
#define PASS_STDFILES_SWITCH_TO_STDERR '\003'
//#define PASS_STDFILES_SWITCH_TO_STDERR_STRING "\003"
#else
#define PASS_STDFILES_UNIX_SOCKET 1
#endif
struct cmd_socket_client {
int socket;
int exit_code;
size_t rsize;
unsigned char *rbuffer;
};
extern int client_connect (char *socket_path);
extern int client_send_command(int socket, int argc, char *const*argv,
char *const *env);
extern int create_command_socket(const char *);
#endif
| 545 |
2,151 | <gh_stars>1000+
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/compositor/layer_animation_element.h"
#include <utility>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/strings/stringprintf.h"
#include "cc/animation/animation_id_provider.h"
#include "cc/animation/keyframe_model.h"
#include "ui/compositor/float_animation_curve_adapter.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_delegate.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/transform_animation_curve_adapter.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/interpolated_transform.h"
namespace ui {
namespace {
// The factor by which duration is scaled up or down when using
// ScopedAnimationDurationScaleMode.
const int kSlowDurationScaleMultiplier = 4;
const int kFastDurationScaleDivisor = 4;
const int kNonZeroDurationScaleDivisor = 20;
// Pause -----------------------------------------------------------------------
class Pause : public LayerAnimationElement {
public:
Pause(AnimatableProperties properties, base::TimeDelta duration)
: LayerAnimationElement(properties, duration) {
}
~Pause() override {}
private:
std::string DebugName() const override { return "Pause"; }
void OnStart(LayerAnimationDelegate* delegate) override {}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
return false;
}
void OnGetTarget(TargetValue* target) const override {}
void OnAbort(LayerAnimationDelegate* delegate) override {}
DISALLOW_COPY_AND_ASSIGN(Pause);
};
// InterpolatedTransformTransition ---------------------------------------------
class InterpolatedTransformTransition : public LayerAnimationElement {
public:
InterpolatedTransformTransition(
std::unique_ptr<InterpolatedTransform> interpolated_transform,
base::TimeDelta duration)
: LayerAnimationElement(TRANSFORM, duration),
interpolated_transform_(std::move(interpolated_transform)) {}
~InterpolatedTransformTransition() override {}
protected:
std::string DebugName() const override {
return "InterpolatedTransformTransition";
}
void OnStart(LayerAnimationDelegate* delegate) override {}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetTransformFromAnimation(
interpolated_transform_->Interpolate(static_cast<float>(t)),
PropertyChangeReason::FROM_ANIMATION);
return true;
}
void OnGetTarget(TargetValue* target) const override {
target->transform = interpolated_transform_->Interpolate(1.0f);
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
std::unique_ptr<InterpolatedTransform> interpolated_transform_;
DISALLOW_COPY_AND_ASSIGN(InterpolatedTransformTransition);
};
// BoundsTransition ------------------------------------------------------------
class BoundsTransition : public LayerAnimationElement {
public:
BoundsTransition(const gfx::Rect& target, base::TimeDelta duration)
: LayerAnimationElement(BOUNDS, duration),
target_(target) {
}
~BoundsTransition() override {}
protected:
std::string DebugName() const override { return "BoundsTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetBoundsForAnimation();
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetBoundsFromAnimation(
gfx::Tween::RectValueBetween(t, start_, target_),
PropertyChangeReason::FROM_ANIMATION);
return true;
}
void OnGetTarget(TargetValue* target) const override {
target->bounds = target_;
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
gfx::Rect start_;
const gfx::Rect target_;
DISALLOW_COPY_AND_ASSIGN(BoundsTransition);
};
// VisibilityTransition --------------------------------------------------------
class VisibilityTransition : public LayerAnimationElement {
public:
VisibilityTransition(bool target, base::TimeDelta duration)
: LayerAnimationElement(VISIBILITY, duration),
start_(false),
target_(target) {
}
~VisibilityTransition() override {}
protected:
std::string DebugName() const override { return "VisibilityTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetVisibilityForAnimation();
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetVisibilityFromAnimation(t == 1.0 ? target_ : start_,
PropertyChangeReason::FROM_ANIMATION);
return t == 1.0;
}
void OnGetTarget(TargetValue* target) const override {
target->visibility = target_;
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
bool start_;
const bool target_;
DISALLOW_COPY_AND_ASSIGN(VisibilityTransition);
};
// BrightnessTransition --------------------------------------------------------
class BrightnessTransition : public LayerAnimationElement {
public:
BrightnessTransition(float target, base::TimeDelta duration)
: LayerAnimationElement(BRIGHTNESS, duration),
start_(0.0f),
target_(target) {
}
~BrightnessTransition() override {}
protected:
std::string DebugName() const override { return "BrightnessTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetBrightnessForAnimation();
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetBrightnessFromAnimation(
gfx::Tween::FloatValueBetween(t, start_, target_),
PropertyChangeReason::FROM_ANIMATION);
return true;
}
void OnGetTarget(TargetValue* target) const override {
target->brightness = target_;
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(BrightnessTransition);
};
// GrayscaleTransition ---------------------------------------------------------
class GrayscaleTransition : public LayerAnimationElement {
public:
GrayscaleTransition(float target, base::TimeDelta duration)
: LayerAnimationElement(GRAYSCALE, duration),
start_(0.0f),
target_(target) {
}
~GrayscaleTransition() override {}
protected:
std::string DebugName() const override { return "GrayscaleTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetGrayscaleForAnimation();
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetGrayscaleFromAnimation(
gfx::Tween::FloatValueBetween(t, start_, target_),
PropertyChangeReason::FROM_ANIMATION);
return true;
}
void OnGetTarget(TargetValue* target) const override {
target->grayscale = target_;
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(GrayscaleTransition);
};
// ColorTransition -------------------------------------------------------------
class ColorTransition : public LayerAnimationElement {
public:
ColorTransition(SkColor target, base::TimeDelta duration)
: LayerAnimationElement(COLOR, duration),
start_(SK_ColorBLACK),
target_(target) {
}
~ColorTransition() override {}
protected:
std::string DebugName() const override { return "ColorTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetColorForAnimation();
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
delegate->SetColorFromAnimation(
gfx::Tween::ColorValueBetween(t, start_, target_),
PropertyChangeReason::FROM_ANIMATION);
return true;
}
void OnGetTarget(TargetValue* target) const override {
target->color = target_;
}
void OnAbort(LayerAnimationDelegate* delegate) override {}
private:
SkColor start_;
const SkColor target_;
DISALLOW_COPY_AND_ASSIGN(ColorTransition);
};
// ThreadedLayerAnimationElement -----------------------------------------------
class ThreadedLayerAnimationElement : public LayerAnimationElement {
public:
ThreadedLayerAnimationElement(AnimatableProperties properties,
base::TimeDelta duration)
: LayerAnimationElement(properties, duration) {
}
~ThreadedLayerAnimationElement() override {}
bool IsThreaded(LayerAnimationDelegate* delegate) const override {
return !duration().is_zero();
}
protected:
explicit ThreadedLayerAnimationElement(const LayerAnimationElement& element)
: LayerAnimationElement(element) {
}
std::string DebugName() const override {
return "ThreadedLayerAnimationElement";
}
bool OnProgress(double t, LayerAnimationDelegate* delegate) override {
if (t < 1.0)
return false;
if (Started() && IsThreaded(delegate)) {
LayerThreadedAnimationDelegate* threaded =
delegate->GetThreadedAnimationDelegate();
DCHECK(threaded);
threaded->RemoveThreadedAnimation(keyframe_model_id());
}
OnEnd(delegate);
return true;
}
void OnAbort(LayerAnimationDelegate* delegate) override {
if (delegate && Started() && IsThreaded(delegate)) {
LayerThreadedAnimationDelegate* threaded =
delegate->GetThreadedAnimationDelegate();
DCHECK(threaded);
threaded->RemoveThreadedAnimation(keyframe_model_id());
}
}
void RequestEffectiveStart(LayerAnimationDelegate* delegate) override {
DCHECK(animation_group_id());
if (!IsThreaded(delegate)) {
set_effective_start_time(requested_start_time());
return;
}
set_effective_start_time(base::TimeTicks());
std::unique_ptr<cc::KeyframeModel> keyframe_model = CreateCCKeyframeModel();
keyframe_model->set_needs_synchronized_start_time(true);
LayerThreadedAnimationDelegate* threaded =
delegate->GetThreadedAnimationDelegate();
DCHECK(threaded);
threaded->AddThreadedAnimation(std::move(keyframe_model));
}
virtual void OnEnd(LayerAnimationDelegate* delegate) = 0;
virtual std::unique_ptr<cc::KeyframeModel> CreateCCKeyframeModel() = 0;
private:
DISALLOW_COPY_AND_ASSIGN(ThreadedLayerAnimationElement);
};
// ThreadedOpacityTransition ---------------------------------------------------
class ThreadedOpacityTransition : public ThreadedLayerAnimationElement {
public:
ThreadedOpacityTransition(float target, base::TimeDelta duration)
: ThreadedLayerAnimationElement(OPACITY, duration),
start_(0.0f),
target_(target) {
}
~ThreadedOpacityTransition() override {}
protected:
std::string DebugName() const override { return "ThreadedOpacityTransition"; }
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetOpacityForAnimation();
delegate->SetOpacityFromAnimation(delegate->GetOpacityForAnimation(),
PropertyChangeReason::FROM_ANIMATION);
}
void OnAbort(LayerAnimationDelegate* delegate) override {
if (delegate && Started()) {
ThreadedLayerAnimationElement::OnAbort(delegate);
delegate->SetOpacityFromAnimation(
gfx::Tween::FloatValueBetween(
gfx::Tween::CalculateValue(tween_type(),
last_progressed_fraction()),
start_, target_),
PropertyChangeReason::FROM_ANIMATION);
}
}
void OnEnd(LayerAnimationDelegate* delegate) override {
delegate->SetOpacityFromAnimation(target_,
PropertyChangeReason::FROM_ANIMATION);
}
std::unique_ptr<cc::KeyframeModel> CreateCCKeyframeModel() override {
std::unique_ptr<cc::AnimationCurve> animation_curve(
new FloatAnimationCurveAdapter(tween_type(), start_, target_,
duration()));
std::unique_ptr<cc::KeyframeModel> keyframe_model(cc::KeyframeModel::Create(
std::move(animation_curve), keyframe_model_id(), animation_group_id(),
cc::TargetProperty::OPACITY));
return keyframe_model;
}
void OnGetTarget(TargetValue* target) const override {
target->opacity = target_;
}
bool IsThreaded(LayerAnimationDelegate* delegate) const override {
// If the start and target values are the same, we do not create cc
// animation so that we will not create render pass in this case.
// http://crbug.com/764575.
if (duration().is_zero())
return false;
if (Started())
return start_ != target_;
return delegate->GetOpacityForAnimation() != target_;
}
private:
float start_;
const float target_;
DISALLOW_COPY_AND_ASSIGN(ThreadedOpacityTransition);
};
// ThreadedTransformTransition -------------------------------------------------
class ThreadedTransformTransition : public ThreadedLayerAnimationElement {
public:
ThreadedTransformTransition(const gfx::Transform& target,
base::TimeDelta duration)
: ThreadedLayerAnimationElement(TRANSFORM, duration),
target_(target) {
}
~ThreadedTransformTransition() override {}
protected:
std::string DebugName() const override {
return "ThreadedTransformTransition";
}
void OnStart(LayerAnimationDelegate* delegate) override {
start_ = delegate->GetTransformForAnimation();
delegate->SetTransformFromAnimation(delegate->GetTransformForAnimation(),
PropertyChangeReason::FROM_ANIMATION);
}
void OnAbort(LayerAnimationDelegate* delegate) override {
if (delegate && Started()) {
ThreadedLayerAnimationElement::OnAbort(delegate);
delegate->SetTransformFromAnimation(
gfx::Tween::TransformValueBetween(
gfx::Tween::CalculateValue(tween_type(),
last_progressed_fraction()),
start_, target_),
PropertyChangeReason::FROM_ANIMATION);
}
}
void OnEnd(LayerAnimationDelegate* delegate) override {
delegate->SetTransformFromAnimation(target_,
PropertyChangeReason::FROM_ANIMATION);
}
std::unique_ptr<cc::KeyframeModel> CreateCCKeyframeModel() override {
std::unique_ptr<cc::AnimationCurve> animation_curve(
new TransformAnimationCurveAdapter(tween_type(), start_, target_,
duration()));
std::unique_ptr<cc::KeyframeModel> keyframe_model(cc::KeyframeModel::Create(
std::move(animation_curve), keyframe_model_id(), animation_group_id(),
cc::TargetProperty::TRANSFORM));
return keyframe_model;
}
void OnGetTarget(TargetValue* target) const override {
target->transform = target_;
}
private:
gfx::Transform start_;
const gfx::Transform target_;
DISALLOW_COPY_AND_ASSIGN(ThreadedTransformTransition);
};
} // namespace
// LayerAnimationElement::TargetValue ------------------------------------------
LayerAnimationElement::TargetValue::TargetValue()
: opacity(0.0f),
visibility(false),
brightness(0.0f),
grayscale(0.0f),
color(SK_ColorBLACK) {
}
LayerAnimationElement::TargetValue::TargetValue(
const LayerAnimationDelegate* delegate)
: bounds(delegate ? delegate->GetBoundsForAnimation() : gfx::Rect()),
transform(delegate ? delegate->GetTransformForAnimation()
: gfx::Transform()),
opacity(delegate ? delegate->GetOpacityForAnimation() : 0.0f),
visibility(delegate ? delegate->GetVisibilityForAnimation() : false),
brightness(delegate ? delegate->GetBrightnessForAnimation() : 0.0f),
grayscale(delegate ? delegate->GetGrayscaleForAnimation() : 0.0f),
color(delegate ? delegate->GetColorForAnimation() : SK_ColorTRANSPARENT) {
}
// LayerAnimationElement -------------------------------------------------------
LayerAnimationElement::LayerAnimationElement(AnimatableProperties properties,
base::TimeDelta duration)
: first_frame_(true),
properties_(properties),
duration_(GetEffectiveDuration(duration)),
tween_type_(gfx::Tween::LINEAR),
keyframe_model_id_(cc::AnimationIdProvider::NextKeyframeModelId()),
animation_group_id_(0),
last_progressed_fraction_(0.0),
animation_metrics_reporter_(nullptr),
start_frame_number_(0),
weak_ptr_factory_(this) {}
LayerAnimationElement::LayerAnimationElement(
const LayerAnimationElement& element)
: first_frame_(element.first_frame_),
properties_(element.properties_),
duration_(element.duration_),
tween_type_(element.tween_type_),
keyframe_model_id_(cc::AnimationIdProvider::NextKeyframeModelId()),
animation_group_id_(element.animation_group_id_),
last_progressed_fraction_(element.last_progressed_fraction_),
animation_metrics_reporter_(nullptr),
start_frame_number_(0),
weak_ptr_factory_(this) {}
LayerAnimationElement::~LayerAnimationElement() {
}
void LayerAnimationElement::Start(LayerAnimationDelegate* delegate,
int animation_group_id) {
DCHECK(requested_start_time_ != base::TimeTicks());
DCHECK(first_frame_);
animation_group_id_ = animation_group_id;
last_progressed_fraction_ = 0.0;
OnStart(delegate);
if (delegate)
start_frame_number_ = delegate->GetFrameNumber();
RequestEffectiveStart(delegate);
first_frame_ = false;
}
bool LayerAnimationElement::Progress(base::TimeTicks now,
LayerAnimationDelegate* delegate) {
DCHECK(requested_start_time_ != base::TimeTicks());
DCHECK(!first_frame_);
bool need_draw;
double t = 1.0;
if ((effective_start_time_ == base::TimeTicks()) ||
(now < effective_start_time_)) {
// This hasn't actually started yet.
need_draw = false;
last_progressed_fraction_ = 0.0;
return need_draw;
}
base::TimeDelta elapsed = now - effective_start_time_;
if ((duration_ > base::TimeDelta()) && (elapsed < duration_))
t = elapsed.InMillisecondsF() / duration_.InMillisecondsF();
base::WeakPtr<LayerAnimationElement> alive(weak_ptr_factory_.GetWeakPtr());
need_draw = OnProgress(gfx::Tween::CalculateValue(tween_type_, t), delegate);
if (!alive)
return need_draw;
first_frame_ = t == 1.0;
last_progressed_fraction_ = t;
return need_draw;
}
bool LayerAnimationElement::IsFinished(base::TimeTicks time,
base::TimeDelta* total_duration) {
// If an effective start has been requested but the effective start time
// hasn't yet been set, the keyframe_model is not finished, regardless of the
// value of |time|.
if (!first_frame_ && (effective_start_time_ == base::TimeTicks()))
return false;
base::TimeDelta queueing_delay;
if (!first_frame_)
queueing_delay = effective_start_time_ - requested_start_time_;
base::TimeDelta elapsed = time - requested_start_time_;
if (elapsed >= duration_ + queueing_delay) {
*total_duration = duration_ + queueing_delay;
return true;
}
return false;
}
bool LayerAnimationElement::ProgressToEnd(LayerAnimationDelegate* delegate) {
const int frame_number = delegate ? delegate->GetFrameNumber() : 0;
if (first_frame_) {
OnStart(delegate);
start_frame_number_ = frame_number;
}
base::WeakPtr<LayerAnimationElement> alive(weak_ptr_factory_.GetWeakPtr());
bool need_draw = OnProgress(1.0, delegate);
int end_frame_number = frame_number;
if (animation_metrics_reporter_ && end_frame_number > start_frame_number_ &&
!duration_.is_zero()) {
base::TimeDelta elapsed = base::TimeTicks::Now() - effective_start_time_;
if (elapsed >= duration_) {
int smoothness = 100;
const float kFrameInterval =
base::Time::kMillisecondsPerSecond / delegate->GetRefreshRate();
const float actual_duration =
(end_frame_number - start_frame_number_) * kFrameInterval;
if (duration_.InMillisecondsF() - actual_duration >= kFrameInterval)
smoothness = 100 * (actual_duration / duration_.InMillisecondsF());
animation_metrics_reporter_->Report(smoothness);
}
}
if (!alive)
return need_draw;
last_progressed_fraction_ = 1.0;
first_frame_ = true;
return need_draw;
}
void LayerAnimationElement::GetTargetValue(TargetValue* target) const {
OnGetTarget(target);
}
bool LayerAnimationElement::IsThreaded(LayerAnimationDelegate* delegate) const {
return false;
}
void LayerAnimationElement::Abort(LayerAnimationDelegate* delegate) {
OnAbort(delegate);
first_frame_ = true;
}
void LayerAnimationElement::RequestEffectiveStart(
LayerAnimationDelegate* delegate) {
DCHECK(requested_start_time_ != base::TimeTicks());
effective_start_time_ = requested_start_time_;
}
std::string LayerAnimationElement::ToString() const {
// TODO(wkorman): Add support for subclasses to tack on more info
// beyond just their name.
return base::StringPrintf(
"LayerAnimationElement{name=%s, id=%d, group=%d, "
"last_progressed_fraction=%0.2f}",
DebugName().c_str(), keyframe_model_id_, animation_group_id_,
last_progressed_fraction_);
}
std::string LayerAnimationElement::DebugName() const {
return "Default";
}
// static
LayerAnimationElement::AnimatableProperty
LayerAnimationElement::ToAnimatableProperty(cc::TargetProperty::Type property) {
switch (property) {
case cc::TargetProperty::TRANSFORM:
return TRANSFORM;
case cc::TargetProperty::OPACITY:
return OPACITY;
default:
NOTREACHED();
return AnimatableProperty();
}
}
// static
std::string LayerAnimationElement::AnimatablePropertiesToString(
AnimatableProperties properties) {
std::string str;
int property_count = 0;
for (unsigned i = FIRST_PROPERTY; i != SENTINEL; i = i << 1) {
if (i & properties) {
LayerAnimationElement::AnimatableProperty property =
static_cast<LayerAnimationElement::AnimatableProperty>(i);
if (property_count > 0)
str.append("|");
// TODO(wkorman): Consider reworking enum definition to follow
// #define pattern that includes easier string output.
switch (property) {
case UNKNOWN:
str.append("UNKNOWN");
break;
case TRANSFORM:
str.append("TRANSFORM");
break;
case BOUNDS:
str.append("BOUNDS");
break;
case OPACITY:
str.append("OPACITY");
break;
case VISIBILITY:
str.append("VISIBILITY");
break;
case BRIGHTNESS:
str.append("BRIGHTNESS");
break;
case GRAYSCALE:
str.append("GRAYSCALE");
break;
case COLOR:
str.append("COLOR");
break;
case SENTINEL:
NOTREACHED();
break;
}
property_count++;
}
}
return str;
}
// static
base::TimeDelta LayerAnimationElement::GetEffectiveDuration(
const base::TimeDelta& duration) {
switch (ScopedAnimationDurationScaleMode::duration_scale_mode()) {
case ScopedAnimationDurationScaleMode::NORMAL_DURATION:
return duration;
case ScopedAnimationDurationScaleMode::FAST_DURATION:
return duration / kFastDurationScaleDivisor;
case ScopedAnimationDurationScaleMode::SLOW_DURATION:
return duration * kSlowDurationScaleMultiplier;
case ScopedAnimationDurationScaleMode::NON_ZERO_DURATION:
return duration / kNonZeroDurationScaleDivisor;
case ScopedAnimationDurationScaleMode::ZERO_DURATION:
return base::TimeDelta();
default:
NOTREACHED();
return base::TimeDelta();
}
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateTransformElement(const gfx::Transform& transform,
base::TimeDelta duration) {
return std::make_unique<ThreadedTransformTransition>(transform, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateInterpolatedTransformElement(
std::unique_ptr<InterpolatedTransform> interpolated_transform,
base::TimeDelta duration) {
return std::make_unique<InterpolatedTransformTransition>(
std::move(interpolated_transform), duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateBoundsElement(const gfx::Rect& bounds,
base::TimeDelta duration) {
return std::make_unique<BoundsTransition>(bounds, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateOpacityElement(float opacity,
base::TimeDelta duration) {
return std::make_unique<ThreadedOpacityTransition>(opacity, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateVisibilityElement(bool visibility,
base::TimeDelta duration) {
return std::make_unique<VisibilityTransition>(visibility, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateBrightnessElement(float brightness,
base::TimeDelta duration) {
return std::make_unique<BrightnessTransition>(brightness, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateGrayscaleElement(float grayscale,
base::TimeDelta duration) {
return std::make_unique<GrayscaleTransition>(grayscale, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreatePauseElement(AnimatableProperties properties,
base::TimeDelta duration) {
return std::make_unique<Pause>(properties, duration);
}
// static
std::unique_ptr<LayerAnimationElement>
LayerAnimationElement::CreateColorElement(SkColor color,
base::TimeDelta duration) {
return std::make_unique<ColorTransition>(color, duration);
}
} // namespace ui
| 9,280 |
850 | <reponame>tianyapiaozi/tensorflow<filename>tensorflow/core/kernels/gemm_functors.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.
==============================================================================*/
// This is a set of different implementations for the basic matrix by matrix
// multiply function, commonly known as GEMM after the BLAS library's naming.
// Having a standard interface enables us to swap out implementations on
// different platforms, to make sure we're using the optimal version. They are
// implemented as C++ template functors, so they're easy to swap into all of the
// different kernels that use them.
#if !defined(EIGEN_USE_THREADS)
#error "EIGEN_USE_THREADS must be enabled by all .cc files including this."
#endif // EIGEN_USE_THREADS
#include <string.h>
#include <map>
#include <vector>
#include "tensorflow/core/common_runtime/threadpool_device.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
// Apple provides an optimized BLAS library that is better than Eigen for their
// devices, so use that if possible.
#if defined(__APPLE__) && defined(USE_GEMM_FOR_CONV)
#include <Accelerate/Accelerate.h>
#define USE_CBLAS_GEMM
#endif // __APPLE__
// Older Raspberry Pi systems don't have NEON SIMD acceleration, so Eigen falls
// back to scalar code, but OpenBLAS has much faster support so prefer that.
#if defined(RASPBERRY_PI) && defined(USE_GEMM_FOR_CONV) && defined(USE_OPENBLAS)
#include <cblas.h>
#define USE_CBLAS_GEMM
#endif
// A readable but slow implementation of matrix multiplication, useful for
// debugging and understanding the algorithm. Use instead of FastGemmFunctor in
// the Im2ColConvFunctor template definition inside the op registration to
// enable. Assumes row-major ordering of the values in memory.
template <class T1, class T2, class T3>
class ReferenceGemmFunctor {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const T1* a, size_t lda, const T2* b, size_t ldb,
T3* c, size_t ldc) {
const size_t a_i_stride = lda;
const size_t a_l_stride = 1;
const size_t b_j_stride = 1;
const size_t b_l_stride = ldb;
const size_t c_i_stride = ldc;
const size_t c_j_stride = 1;
size_t i, j, l;
for (j = 0; j < n; j++) {
for (i = 0; i < m; i++) {
T3 total(0);
for (l = 0; l < k; l++) {
const size_t a_index = ((i * a_i_stride) + (l * a_l_stride));
const T1 a_value = a[a_index];
const size_t b_index = ((j * b_j_stride) + (l * b_l_stride));
const T2 b_value = b[b_index];
total += (a_value * b_value);
}
const size_t c_index = ((i * c_i_stride) + (j * c_j_stride));
c[c_index] = total;
}
}
}
};
// Uses the optimized EigenTensor library to implement the matrix multiplication
// required by the Im2ColConvFunctor class. We supply the two input and one
// output types so that the accumulator can potentially be higher-precision than
// the inputs, even though we don't currently take advantage of this.
template <class T1, class T2, class T3>
class FastGemmFunctor {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const T1* a, size_t lda, const T2* b, size_t ldb,
T3* c, size_t ldc) {
typename tensorflow::TTypes<const T1>::Matrix a_matrix(a, m, k);
typename tensorflow::TTypes<const T2>::Matrix b_matrix(b, k, n);
typename tensorflow::TTypes<T3>::Matrix c_matrix(c, m, n);
Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1> dim_pair;
dim_pair[0].first = 1;
dim_pair[0].second = 0;
c_matrix.device(ctx->eigen_device<Eigen::ThreadPoolDevice>()) =
a_matrix.contract(b_matrix, dim_pair);
}
};
// If we have a fast CBLAS library, use its implementation through a wrapper.
#if defined(USE_CBLAS_GEMM)
template <>
class FastGemmFunctor<float, float, float> {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const float* a, size_t lda, const float* b,
size_t ldb, float* c, size_t ldc) {
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f, a,
lda, b, ldb, 0.0f, c, ldc);
}
};
#endif // USE_CBLAS_GEMM
| 1,893 |
3,227 | <filename>Orthtree/doc/Orthtree/Concepts/OrthtreeTraits.h
/*!
\ingroup PkgOrthtreeConcepts
\cgalConcept
The concept `OrthtreeTraits` defines the requirements for the
template parameter of the `CGAL::Orthtree` class.
\cgalHasModel `CGAL::Orthtree_traits_2<GeomTraits>`
\cgalHasModel `CGAL::Orthtree_traits_3<GeomTraits>`
\cgalHasModel `CGAL::Orthtree_traits_d<GeomTraits,Dimension>`
*/
class OrthtreeTraits
{
public:
/// \name Types
/// @{
typedef unspecified_type Dimension; ///< Dimension type (see `CGAL::Dimension_tag`).
typedef unspecified_type Bbox_d; ///< Bounding box type.
typedef unspecified_type FT; ///< The number type of the %Cartesian coordinates of types `Point_d`
typedef unspecified_type Point_d; ///< Point type.
typedef unspecified_type Sphere_d; ///< The sphere type for neighbor queries.
/*!
A random access iterator type to enumerate the
%Cartesian coordinates of a point.
*/
typedef unspecified_type Cartesian_const_iterator_d;
typedef std::array<FT, Dimension::value> Array; ///< Array used for easy point constructions.
typedef unspecified_type Adjacency; ///< Specify the adjacency directions
/*!
Functor with an operator to construct a `Point_d` from an `Array` object.
*/
typedef unspecified_type Construct_point_d_from_array;
/*!
Functor with an operator to construct a `Bbox_d` from two `Array` objects (coordinates of minimum and maximum points).
*/
typedef unspecified_type Construct_bbox_d;
/// @}
/// \name Operations
/// @{
/*!
Function used to construct an object of type `Construct_point_d_from_array`.
*/
Construct_point_d_from_array construct_point_d_from_array_object() const;
/*!
Function used to construct an object of type `Construct_bbox_d`.
*/
Construct_bbox_d construct_bbox_d_object() const;
/// @}
};
| 612 |
1,829 | <reponame>useaname/thinking-in-spring-boot-samples
package thinking.in.spring.boot.samples.spring3.bootstrap;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurableEnvironment;
import thinking.in.spring.boot.samples.spring3.service.CalculatingService;
/**
* {@link CalculatingService} 引导程序
*
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @version 1.0.0
* @since 1.0.0
*/
@Configuration
@ComponentScan(basePackageClasses = CalculatingService.class)
public class CalculatingServiceBootstrap {
static {
// 通过 Java 系统属性设置 Spring Profile
// 以下语句等效于 ConfigurableEnvironment.setActiveProfiles("Java8")
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "Java8");
// 以下语句等效于 ConfigurableEnvironment.setDefaultProfiles("Java7")
System.setProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "Java7");
}
public static void main(String[] args) {
// 构建 Annotation 配置驱动 Spring 上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册 当前配置Bean 到 Spring 上下文
context.register(CalculatingServiceBootstrap.class);
// 启动上下文
context.refresh();
// 获取 CalculatingService Bean
CalculatingService calculatingService = context.getBean(CalculatingService.class);
// 输出累加结果
calculatingService.sum(1, 2, 3, 4, 5);
// 关闭上下文
context.close();
}
}
| 711 |
521 | #ifndef CONFIG_TIME_H
#define CONFIG_TIME_H
/** @file
*
* Time API configuration
*
*/
FILE_LICENCE ( GPL2_OR_LATER );
#include <config/defaults.h>
#include <config/local/time.h>
#endif /* CONFIG_TIME_H */
| 86 |
632 | <reponame>alesapin/NuRaft<gh_stars>100-1000
/************************************************************************
Modifications Copyright 2017-2019 eBay Inc.
Author/Developer(s): <NAME>
Original Copyright:
See URL: https://github.com/datatechnology/cornerstone
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.
**************************************************************************/
#ifndef _SRV_ROLE_HXX_
#define _SRV_ROLE_HXX_
namespace nuraft {
#include "attr_unused.hxx"
enum srv_role {
follower = 0x1,
candidate = 0x2,
leader = 0x3
};
static std::string ATTR_UNUSED
srv_role_to_string(srv_role _role)
{
switch (_role) {
case follower: return "follower";
case candidate: return "candidate";
case leader: return "leader";
default: return "UNKNOWN";
}
return "UNKNOWN";
}
}
#endif
| 449 |
323 | {
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ApplicationDbContext": {
"ConnectionString":"User ID=Sock;Password=password;Host=localhost;Port=5432;Database=DbTenantswithSaaskit;Pooling=true;"
}
} | 131 |
18,325 | package com.zheng.pay.rpc.api;
import com.zheng.common.base.BaseService;
import com.zheng.pay.dao.model.PayOutOrderDetail;
import com.zheng.pay.dao.model.PayOutOrderDetailExample;
/**
* PayOutOrderDetailService接口
* Created by shuzheng on 2017/3/29.
*/
public interface PayOutOrderDetailService extends BaseService<PayOutOrderDetail, PayOutOrderDetailExample> {
} | 131 |
348 | <filename>docs/data/leg-t2/064/06404436.json
{"nom":"Ossès","circ":"4ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":704,"abs":373,"votants":331,"blancs":34,"nuls":11,"exp":286,"res":[{"nuance":"DVD","nom":"<NAME>","voix":148},{"nuance":"REM","nom":"<NAME>","voix":138}]} | 118 |
314 | <filename>ZJKitTool/ZJCategory/UIKit/UIGestureRecognizer+ZJHelperBlockKit.h
//
// UIGestureRecognizer+ZJHelperBlockKit.h
// ZJUIKit
//
// Created by dzj on 2018/1/18.
// Copyright © 2018年 kapokcloud. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* gesture事件Block
*
*/
typedef void(^ZJGestureBlock)(UIGestureRecognizer *gesture);
/**
* Tap点击事件Block
*
*/
typedef void(^ZJTapGestureBlock)(UITapGestureRecognizer *gesture);
/**
* Tap长按事件Block
*
*/
typedef void(^ZJLongGestureBlock)(UILongPressGestureRecognizer *gesture);
@interface UIGestureRecognizer (ZJHelperBlockKit)
/**
*
* Make all gestures support block callback.
* This will support all kinds of gestures.
*/
@property (nonatomic, copy) ZJGestureBlock zj_onGesture;
/**
*
* Make tap gesture support block callback.
*/
@property (nonatomic, copy) ZJTapGestureBlock zj_onTaped;
/**
*
* Make long press gesture support block callback.
*/
@property (nonatomic, copy) ZJLongGestureBlock zj_onLongPressed;
@end
| 406 |
346 | <reponame>ZJCRT/drishti
/*! -*-c++-*-
@file FaceModelEstimator.h
@author <NAME>
@brief Internal declaration of a class to estimate 3D models from 2D face landmarks.
\copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved.
\license{This project is released under the 3 Clause BSD License.}
NOTE: This currently provide a single depth estimate based on a
mean population interocular distance model and two eye positions.
*/
#ifndef __drishti_face_FaceModelEstimator_h__
#define __drishti_face_FaceModelEstimator_h__
#include "drishti/face/drishti_face.h"
#include "drishti/face/Face.h"
#include "drishti/sensor/Sensor.h"
#include <opencv2/core/core.hpp>
DRISHTI_FACE_NAMESPACE_BEGIN
/*
This class will convert a 2D face model to a 3D face model.
It may be beneficial to introduce a dimension specific template parameter
to both the EyeModel and FaceModel classes to facilitate this. For now
we just estimate a single depth point based on simple interocular distance
constants.
*/
class FaceModelEstimator
{
public:
FaceModelEstimator(sensor::SensorModel sensor);
cv::Point3f operator()(const face::FaceModel& face);
protected:
cv::Point3f getDepth(const DRISHTI_EYE::EyeModel& eyeR, const DRISHTI_EYE::EyeModel& eyeL);
sensor::SensorModel m_sensor;
};
DRISHTI_FACE_NAMESPACE_END
#endif /* defined(__drishti_face_FaceModelEstimator_h__) */
| 485 |
608 | <gh_stars>100-1000
// ------- Preamble -------- //
#include <avr/io.h> /* Defines pins, ports, etc */
#include <util/delay.h> /* Functions to waste time */
#include <avr/interrupt.h>
#include <avr/power.h>
#include "pinDefines.h"
#include "macros.h"
#include "fullSaw15.h"
#define BASEPITCH 220 /* in tuningWord steps, which are ~1/2 Hz */
#define PHASE_RATE 7 /* controls speed of phasing effect */
#define NUMBER_OSCILLATORS 4
/* 2 and 4 work just fine.
8 and 16 take too long to maintain our 31.25kHz sample rate
so the pitch shifts downwards and there's all sorts of aliasing.
If you're just after scary sounds, 8 and 16 are awesome, but you may want
to increase the BASEPITCH to compensate. */
#define OSCILLATOR_SHIFT 2
/* This is the number of bits to shift when volume mixing.
2**OSCILLATOR_SHIFT = NUMBER_OSCILLATORS
If you don't change this to match the number of oscillators, you'll
get clipping and digital distortion. */
static inline void initTimer0(void){
set_bit(TCCR0A, WGM00); /* Fast PWM mode */
set_bit(TCCR0A, WGM01); /* Fast PWM mode */
set_bit(TCCR0A, COM0A1); /* PWM output on OCR0A */
set_bit(SPEAKER_DDR, SPEAKER); /* enable output on pin */
set_bit(TCCR0B, CS00); /* Clock with /1 prescaler */
}
| 478 |
1,392 | package com.amazonaws.auth;
/*
* Copyright 2011-2020 Amazon Technologies, 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://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copy of the original class for testing {@link io.fabric8.maven.docker.util.aws.AwsSdkAuthConfigFactory}.
* Based on <a href="https://github.com/aws/aws-sdk-java/blob/1.11.707/aws-java-sdk-core/src/main/java/com/amazonaws/auth/AWSCredentials.java">com.amazonaws:aws-java-sdk-core:1.11.707</a> (also APL licensed).
* We can't use a direct dependency here, as we have
* to keep d-m-p agnostic of the AWS SDK and only access it via reflection.
*/
public class AWSCredentials {
private final String accessKeyId;
private final String secretKey;
public AWSCredentials(String accessKeyId, String secretKey) {
this.accessKeyId = accessKeyId;
this.secretKey = secretKey;
}
public String getAWSAccessKeyId() {
return accessKeyId;
}
public String getAWSSecretKey() {
return secretKey;
}
}
| 463 |
14,668 | <filename>ash/public/cpp/holding_space/mock_holding_space_client.h
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_PUBLIC_CPP_HOLDING_SPACE_MOCK_HOLDING_SPACE_CLIENT_H_
#define ASH_PUBLIC_CPP_HOLDING_SPACE_MOCK_HOLDING_SPACE_CLIENT_H_
#include <vector>
#include "ash/public/cpp/holding_space/holding_space_client.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace ash {
// A mock implementation of `HoldingSpaceClient` for use in testing.
class MockHoldingSpaceClient : public HoldingSpaceClient {
public:
MockHoldingSpaceClient();
MockHoldingSpaceClient(const MockHoldingSpaceClient&) = delete;
MockHoldingSpaceClient& operator=(const MockHoldingSpaceClient&) = delete;
~MockHoldingSpaceClient() override;
// HoldingSpaceClient:
MOCK_METHOD(void,
AddDiagnosticsLog,
(const base::FilePath& file_path),
(override));
MOCK_METHOD(void,
AddScreenshot,
(const base::FilePath& file_path),
(override));
MOCK_METHOD(void,
AddScreenRecording,
(const base::FilePath& file_path),
(override));
MOCK_METHOD(void,
CancelItems,
(const std::vector<const HoldingSpaceItem*>& items),
(override));
MOCK_METHOD(void,
CopyImageToClipboard,
(const HoldingSpaceItem& item, SuccessCallback callback),
(override));
MOCK_METHOD(base::FilePath,
CrackFileSystemUrl,
(const GURL& file_system_url),
(const, override));
MOCK_METHOD(void, OpenDownloads, (SuccessCallback callback), (override));
MOCK_METHOD(void, OpenMyFiles, (SuccessCallback callback), (override));
MOCK_METHOD(void,
OpenItems,
(const std::vector<const HoldingSpaceItem*>& items,
SuccessCallback callback),
(override));
MOCK_METHOD(void,
PauseItems,
(const std::vector<const HoldingSpaceItem*>& items),
(override));
MOCK_METHOD(void,
PinFiles,
(const std::vector<base::FilePath>& file_paths),
(override));
MOCK_METHOD(void,
PinItems,
(const std::vector<const HoldingSpaceItem*>& items),
(override));
MOCK_METHOD(void,
ResumeItems,
(const std::vector<const HoldingSpaceItem*>& items),
(override));
MOCK_METHOD(void,
ShowItemInFolder,
(const HoldingSpaceItem& item, SuccessCallback callback),
(override));
MOCK_METHOD(void,
UnpinItems,
(const std::vector<const HoldingSpaceItem*>& items),
(override));
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_HOLDING_SPACE_MOCK_HOLDING_SPACE_CLIENT_H_
| 1,374 |
2,338 | //===-- CommandObjectStats.h ------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_SOURCE_COMMANDS_COMMANDOBJECTSTATS_H
#define LLDB_SOURCE_COMMANDS_COMMANDOBJECTSTATS_H
#include "lldb/Interpreter/CommandObjectMultiword.h"
namespace lldb_private {
class CommandObjectStats : public CommandObjectMultiword {
public:
CommandObjectStats(CommandInterpreter &interpreter);
~CommandObjectStats() override;
};
} // namespace lldb_private
#endif // LLDB_SOURCE_COMMANDS_COMMANDOBJECTSTATS_H
| 239 |
3,372 | <filename>aws-java-sdk-outposts/src/main/java/com/amazonaws/services/outposts/model/transform/OrderJsonUnmarshaller.java
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.outposts.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.outposts.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Order JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OrderJsonUnmarshaller implements Unmarshaller<Order, JsonUnmarshallerContext> {
public Order unmarshall(JsonUnmarshallerContext context) throws Exception {
Order order = new Order();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("OutpostId", targetDepth)) {
context.nextToken();
order.setOutpostId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("OrderId", targetDepth)) {
context.nextToken();
order.setOrderId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
order.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("LineItems", targetDepth)) {
context.nextToken();
order.setLineItems(new ListUnmarshaller<LineItem>(LineItemJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("PaymentOption", targetDepth)) {
context.nextToken();
order.setPaymentOption(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("OrderSubmissionDate", targetDepth)) {
context.nextToken();
order.setOrderSubmissionDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("OrderFulfilledDate", targetDepth)) {
context.nextToken();
order.setOrderFulfilledDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return order;
}
private static OrderJsonUnmarshaller instance;
public static OrderJsonUnmarshaller getInstance() {
if (instance == null)
instance = new OrderJsonUnmarshaller();
return instance;
}
}
| 1,833 |
1,473 | <gh_stars>1000+
/*
* Copyright 2016 Naver Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.vo.chart;
import java.util.List;
public class Chart<P extends Point> {
private final List<P> points;
Chart(List<P> points) {
this.points = points;
}
public List<P> getPoints() {
return this.points;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Chart<?> chart = (Chart<?>) o;
return points != null ? points.equals(chart.points) : chart.points == null;
}
@Override
public int hashCode() {
return points != null ? points.hashCode() : 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Chart{");
sb.append("points=").append(points);
sb.append('}');
return sb.toString();
}
}
| 526 |
1,738 | <reponame>brianherrera/lumberyard<gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Asset/AssetCommon.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
#include <QComboBox>
#include <Blast/BlastMaterial.h>
namespace Blast
{
namespace Editor
{
class MaterialIdWidget
: public QObject
, public AzToolsFramework::PropertyHandler<Blast::BlastMaterialId, QComboBox>
{
Q_OBJECT
public:
AZ_CLASS_ALLOCATOR(MaterialIdWidget, AZ::SystemAllocator, 0);
MaterialIdWidget() = default;
AZ::u32 GetHandlerName() const override;
QWidget* CreateGUI(QWidget* parent) override;
bool IsDefaultHandler() const override;
void ConsumeAttribute(
widget_t* widget, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue,
const char* debugName) override;
void WriteGUIValuesIntoProperty(
size_t index, widget_t* gui, property_t& instance, AzToolsFramework::InstanceDataNode* node) override;
bool ReadValuesIntoGUI(
size_t index, widget_t* gui, const property_t& instance,
AzToolsFramework::InstanceDataNode* node) override;
private:
Blast::BlastMaterialId GetIdForIndex(size_t index);
int GetIndexForId(Blast::BlastMaterialId id);
AZ::Data::AssetId m_materialLibraryId;
AZStd::vector<Blast::BlastMaterialId> m_libraryIds;
};
} // namespace Editor
} // namespace Blast
| 835 |
2,406 | #
# pool2d paddle model generator
#
import numpy as np
import sys
from save_model import saveModel
def pdpd_scale(name : str, x, scale, bias, attrs : dict, data_type):
import paddle as pdpd
pdpd.enable_static()
with pdpd.static.program_guard(pdpd.static.Program(), pdpd.static.Program()):
node_x = pdpd.static.data(name='x', shape=x.shape, dtype=data_type)
out = pdpd.scale(x=node_x, scale=scale, bias=bias,
bias_after_scale=attrs['bias_after_scale'])
#FuzzyTest only support FP32 now, so cast result to fp32
out = pdpd.cast(out, "float32")
cpu = pdpd.static.cpu_places(1)
exe = pdpd.static.Executor(cpu[0])
# startup program will call initializer to initialize the parameters.
exe.run(pdpd.static.default_startup_program())
outs = exe.run(
feed={'x': x},
fetch_list=[out])
saveModel(name, exe, feedkeys=['x'], fetchlist=[out], inputs=[x], outputs=[outs[0]], target_dir=sys.argv[1])
return outs[0]
def pdpd_scale_tensor(name : str, x, scale, bias, attrs : dict, data_type):
import paddle as pdpd
pdpd.enable_static()
with pdpd.static.program_guard(pdpd.static.Program(), pdpd.static.Program()):
node_x = pdpd.static.data(name='x', shape=x.shape, dtype=data_type)
node_scale = pdpd.static.data(name='scale', shape=[1], dtype='float32')
out = pdpd.scale(x=node_x, scale=node_scale, bias=bias,
bias_after_scale=attrs['bias_after_scale'])
#FuzzyTest only support FP32 now, so cast result to fp32
out = pdpd.cast(out, "float32")
cpu = pdpd.static.cpu_places(1)
exe = pdpd.static.Executor(cpu[0])
# startup program will call initializer to initialize the parameters.
exe.run(pdpd.static.default_startup_program())
outs = exe.run(
feed={'x': x, 'scale': scale},
fetch_list=[out])
saveModel(name, exe, feedkeys=['x', 'scale'], fetchlist=[out], inputs=[x, np.array([scale]).astype('float32')], outputs=[outs[0]], target_dir=sys.argv[1])
return outs[0]
def main():
scale = 2.0
bias = 1.0
data = np.random.random([2, 3]).astype("float32")
test_cases = [
"float32",
"int32",
"int64"
]
pdpd_attrs = {
'bias_after_scale': True,
}
pdpd_scale_tensor("scale_tensor_bias_after", data, scale, bias, pdpd_attrs, 'float32')
pdpd_attrs = {
'bias_after_scale': False,
}
pdpd_scale_tensor("scale_tensor_bias_before", data, scale, bias, pdpd_attrs, 'float32')
for test in test_cases:
data = np.random.random([2, 3]).astype(test)
pdpd_attrs = {
'bias_after_scale': True,
}
pdpd_scale("scale_bias_after_" + test, data, scale, bias, pdpd_attrs, test)
pdpd_attrs = {
'bias_after_scale': False,
}
pdpd_scale("scale_bias_before_" + test, data, scale, bias, pdpd_attrs, test)
if __name__ == "__main__":
main() | 1,472 |
467 | package com.yoyiyi.soleil.adapter.home.section.chase;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yoyiyi.soleil.R;
import com.yoyiyi.soleil.bean.chase.RecommendBangumi;
import com.yoyiyi.soleil.widget.section.StatelessSection;
import com.yoyiyi.soleil.widget.section.ViewHolder;
/**
* @author zzq 作者 E-mail: <EMAIL>
* @date 创建时间:2017/5/26 21:59
* 描述:
*/
public class ChaseAdSection extends StatelessSection {
private RecommendBangumi.AdBean mAdBean;
public ChaseAdSection(RecommendBangumi.AdBean adBean) {
super(R.layout.layout_item_home_chase_footer, R.layout.layout_empty);
this.mAdBean = adBean;
}
@Override
public void onBindHeaderViewHolder(ViewHolder holder) {
Glide.with(mContext)
.load(mAdBean.img)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.bili_default_image_tv)
.dontAnimate()
.into((ImageView) holder.getView(R.id.iv_video_preview));
holder.setVisible(R.id.tv_title, false)
.setVisible(R.id.tv_new_tag, false)
.setVisible(R.id.tv_des, false);
}
}
| 615 |
482 | package io.cattle.platform.object.meta.impl;
public class FieldCacheKey {
Class<?> clz;
String fieldName;
public FieldCacheKey(Class<?> clz, String fieldName) {
super();
this.clz = clz;
this.fieldName = fieldName;
}
public Class<?> getClz() {
return clz;
}
public String getFieldName() {
return fieldName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clz == null) ? 0 : clz.hashCode());
result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FieldCacheKey other = (FieldCacheKey) obj;
if (clz == null) {
if (other.clz != null)
return false;
} else if (!clz.equals(other.clz))
return false;
if (fieldName == null) {
if (other.fieldName != null)
return false;
} else if (!fieldName.equals(other.fieldName))
return false;
return true;
}
}
| 620 |
2,151 | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sfntly/tools/subsetter/glyph_table_subsetter.h"
#include "sfntly/table/truetype/glyph_table.h"
#include "sfntly/table/truetype/loca_table.h"
#include "sfntly/tag.h"
#include "sfntly/tools/subsetter/subsetter.h"
#include "sfntly/port/exception_type.h"
namespace sfntly {
const int32_t kGlyphTableSubsetterTags[2] = {Tag::glyf, Tag::loca};
GlyphTableSubsetter::GlyphTableSubsetter()
: TableSubsetterImpl(kGlyphTableSubsetterTags, 2) {
}
GlyphTableSubsetter::~GlyphTableSubsetter() {}
bool GlyphTableSubsetter::Subset(Subsetter* subsetter,
Font* font,
Font::Builder* font_builder) {
assert(font);
assert(subsetter);
assert(font_builder);
std::vector<int32_t>* permutation_table = subsetter->GlyphPermutationTable();
if (!permutation_table || permutation_table->empty())
return false;
GlyphTablePtr glyph_table = down_cast<GlyphTable*>(font->GetTable(Tag::glyf));
LocaTablePtr loca_table = down_cast<LocaTable*>(font->GetTable(Tag::loca));
if (glyph_table == NULL || loca_table == NULL) {
#if !defined (SFNTLY_NO_EXCEPTION)
throw RuntimeException("Font to subset is not valid.");
#endif
return false;
}
GlyphTableBuilderPtr glyph_table_builder =
down_cast<GlyphTable::Builder*>
(font_builder->NewTableBuilder(Tag::glyf));
LocaTableBuilderPtr loca_table_builder =
down_cast<LocaTable::Builder*>
(font_builder->NewTableBuilder(Tag::loca));
if (glyph_table_builder == NULL || loca_table_builder == NULL) {
#if !defined (SFNTLY_NO_EXCEPTION)
throw RuntimeException("Builder for subset is not valid.");
#endif
return false;
}
GlyphTable::GlyphBuilderList* glyph_builders =
glyph_table_builder->GlyphBuilders();
for (std::vector<int32_t>::iterator old_glyph_id = permutation_table->begin(),
old_glyph_id_end = permutation_table->end();
old_glyph_id != old_glyph_id_end; ++old_glyph_id) {
int old_offset = loca_table->GlyphOffset(*old_glyph_id);
int old_length = loca_table->GlyphLength(*old_glyph_id);
GlyphPtr glyph;
glyph.Attach(glyph_table->GetGlyph(old_offset, old_length));
ReadableFontDataPtr data = glyph->ReadFontData();
WritableFontDataPtr copy_data;
copy_data.Attach(WritableFontData::CreateWritableFontData(data->Length()));
data->CopyTo(copy_data);
GlyphBuilderPtr glyph_builder;
glyph_builder.Attach(glyph_table_builder->GlyphBuilder(copy_data));
glyph_builders->push_back(glyph_builder);
}
std::vector<int32_t> loca_list;
glyph_table_builder->GenerateLocaList(&loca_list);
loca_table_builder->SetLocaList(&loca_list);
return true;
}
} // namespace sfntly
| 1,295 |
12,278 | <reponame>Mu-L/jemalloc
#include "test/jemalloc_test.h"
#include "jemalloc/internal/safety_check.h"
bool fake_abort_called;
void fake_abort(const char *message) {
(void)message;
fake_abort_called = true;
}
#define SMALL_SIZE1 SC_SMALL_MAXCLASS
#define SMALL_SIZE2 (SC_SMALL_MAXCLASS / 2)
#define LARGE_SIZE1 SC_LARGE_MINCLASS
#define LARGE_SIZE2 (LARGE_SIZE1 * 2)
void *
test_invalid_size_pre(size_t sz) {
safety_check_set_abort(&fake_abort);
fake_abort_called = false;
void *ptr = malloc(sz);
assert_ptr_not_null(ptr, "Unexpected failure");
return ptr;
}
void
test_invalid_size_post(void) {
expect_true(fake_abort_called, "Safety check didn't fire");
safety_check_set_abort(NULL);
}
TEST_BEGIN(test_invalid_size_sdallocx) {
test_skip_if(!config_opt_size_checks);
void *ptr = test_invalid_size_pre(SMALL_SIZE1);
sdallocx(ptr, SMALL_SIZE2, 0);
test_invalid_size_post();
ptr = test_invalid_size_pre(LARGE_SIZE1);
sdallocx(ptr, LARGE_SIZE2, 0);
test_invalid_size_post();
}
TEST_END
TEST_BEGIN(test_invalid_size_sdallocx_nonzero_flag) {
test_skip_if(!config_opt_size_checks);
void *ptr = test_invalid_size_pre(SMALL_SIZE1);
sdallocx(ptr, SMALL_SIZE2, MALLOCX_TCACHE_NONE);
test_invalid_size_post();
ptr = test_invalid_size_pre(LARGE_SIZE1);
sdallocx(ptr, LARGE_SIZE2, MALLOCX_TCACHE_NONE);
test_invalid_size_post();
}
TEST_END
TEST_BEGIN(test_invalid_size_sdallocx_noflags) {
test_skip_if(!config_opt_size_checks);
void *ptr = test_invalid_size_pre(SMALL_SIZE1);
je_sdallocx_noflags(ptr, SMALL_SIZE2);
test_invalid_size_post();
ptr = test_invalid_size_pre(LARGE_SIZE1);
je_sdallocx_noflags(ptr, LARGE_SIZE2);
test_invalid_size_post();
}
TEST_END
int
main(void) {
return test(
test_invalid_size_sdallocx,
test_invalid_size_sdallocx_nonzero_flag,
test_invalid_size_sdallocx_noflags);
}
| 824 |
545 | #include <iostream>
int main() {
int i;
int *ip = &i;
*ip = 10;
std::cout << i << " " << *ip << std::endl; // 10 10
i = 5;
std::cout << i << " " << *ip << std::endl; // 5 5
return 0;
}
| 96 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-w927-cwvw-mr5c",
"modified": "2022-05-13T01:17:01Z",
"published": "2022-05-13T01:17:01Z",
"aliases": [
"CVE-2017-10125"
],
"details": "Vulnerability in the Java SE component of Oracle Java SE (subcomponent: Deployment). Supported versions that are affected are Java SE: 7u141 and 8u131. Difficult to exploit vulnerability allows physical access to compromise Java SE. While the vulnerability is in Java SE, attacks may significantly impact additional products. Successful attacks of this vulnerability can result in takeover of Java SE. Note: Applies to deployment of Java where the Java Auto Update is enabled. CVSS 3.0 Base Score 7.1 (Confidentiality, Integrity and Availability impacts). CVSS Vector: (CVSS:3.0/AV:P/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:H).",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:P/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-10125"
},
{
"type": "WEB",
"url": "https://security.gentoo.org/glsa/201709-22"
},
{
"type": "WEB",
"url": "https://security.netapp.com/advisory/ntap-20170720-0001/"
},
{
"type": "WEB",
"url": "http://www.oracle.com/technetwork/security-advisory/cpujul2017-3236622.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/99809"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id/1038931"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 738 |
13,648 | <filename>tests/micropython/viper_binop_arith.py
# test arithmetic operators
@micropython.viper
def add(x: int, y: int):
print(x + y)
print(y + x)
add(1, 2)
add(42, 3)
add(-1, 2)
add(-42, -3)
@micropython.viper
def sub(x: int, y: int):
print(x - y)
print(y - x)
sub(1, 2)
sub(42, 3)
sub(-1, 2)
sub(-42, -3)
@micropython.viper
def mul(x: int, y: int):
print(x * y)
print(y * x)
mul(0, 1)
mul(1, -1)
mul(1, 2)
mul(8, 3)
mul(-3, 4)
mul(-9, -6)
@micropython.viper
def shl(x: int, y: int):
print(x << y)
shl(1, 0)
shl(1, 3)
shl(1, 30)
shl(42, 10)
shl(-42, 10)
@micropython.viper
def shr(x: int, y: int):
print(x >> y)
shr(1, 0)
shr(1, 3)
shr(42, 2)
shr(-42, 2)
@micropython.viper
def and_(x: int, y: int):
print(x & y, y & x)
and_(1, 0)
and_(1, 3)
and_(0xF0, 0x3F)
and_(-42, 6)
@micropython.viper
def or_(x: int, y: int):
print(x | y, y | x)
or_(1, 0)
or_(1, 2)
or_(-42, 5)
@micropython.viper
def xor(x: int, y: int):
print(x ^ y, y ^ x)
xor(1, 0)
xor(1, 2)
xor(-42, 5)
| 582 |
12,711 | {"type":"newline","loc":{"start":{"line":2,"column":1},"filename":"/cases/includes.pug","end":{"line":2,"column":1}}}
{"type":"include","loc":{"start":{"line":2,"column":1},"filename":"/cases/includes.pug","end":{"line":2,"column":8}}}
{"type":"path","loc":{"start":{"line":2,"column":9},"filename":"/cases/includes.pug","end":{"line":2,"column":29}},"val":"auxiliary/mixins.pug"}
{"type":"newline","loc":{"start":{"line":4,"column":1},"filename":"/cases/includes.pug","end":{"line":4,"column":1}}}
{"type":"call","loc":{"start":{"line":4,"column":1},"filename":"/cases/includes.pug","end":{"line":4,"column":5}},"val":"foo","args":null}
{"type":"newline","loc":{"start":{"line":6,"column":1},"filename":"/cases/includes.pug","end":{"line":6,"column":1}}}
{"type":"tag","loc":{"start":{"line":6,"column":1},"filename":"/cases/includes.pug","end":{"line":6,"column":5}},"val":"body"}
{"type":"indent","loc":{"start":{"line":7,"column":1},"filename":"/cases/includes.pug","end":{"line":7,"column":3}},"val":2}
{"type":"include","loc":{"start":{"line":7,"column":3},"filename":"/cases/includes.pug","end":{"line":7,"column":10}}}
{"type":"path","loc":{"start":{"line":7,"column":11},"filename":"/cases/includes.pug","end":{"line":7,"column":31}},"val":"auxiliary/smile.html"}
{"type":"newline","loc":{"start":{"line":8,"column":1},"filename":"/cases/includes.pug","end":{"line":8,"column":3}}}
{"type":"include","loc":{"start":{"line":8,"column":3},"filename":"/cases/includes.pug","end":{"line":8,"column":10}}}
{"type":"path","loc":{"start":{"line":8,"column":11},"filename":"/cases/includes.pug","end":{"line":8,"column":33}},"val":"auxiliary/escapes.html"}
{"type":"newline","loc":{"start":{"line":9,"column":1},"filename":"/cases/includes.pug","end":{"line":9,"column":3}}}
{"type":"tag","loc":{"start":{"line":9,"column":3},"filename":"/cases/includes.pug","end":{"line":9,"column":9}},"val":"script"}
{"type":"start-attributes","loc":{"start":{"line":9,"column":9},"filename":"/cases/includes.pug","end":{"line":9,"column":10}}}
{"type":"attribute","loc":{"start":{"line":9,"column":10},"filename":"/cases/includes.pug","end":{"line":9,"column":32}},"name":"type","mustEscape":true,"val":"\"text/javascript\""}
{"type":"end-attributes","loc":{"start":{"line":9,"column":32},"filename":"/cases/includes.pug","end":{"line":9,"column":33}}}
{"type":"indent","loc":{"start":{"line":10,"column":1},"filename":"/cases/includes.pug","end":{"line":10,"column":5}},"val":4}
{"type":"include","loc":{"start":{"line":10,"column":5},"filename":"/cases/includes.pug","end":{"line":10,"column":12}}}
{"type":"filter","loc":{"start":{"line":10,"column":12},"filename":"/cases/includes.pug","end":{"line":10,"column":21}},"val":"verbatim"}
{"type":"path","loc":{"start":{"line":10,"column":22},"filename":"/cases/includes.pug","end":{"line":10,"column":45}},"val":"auxiliary/includable.js"}
{"type":"outdent","loc":{"start":{"line":11,"column":1},"filename":"/cases/includes.pug","end":{"line":11,"column":1}}}
{"type":"outdent","loc":{"start":{"line":11,"column":1},"filename":"/cases/includes.pug","end":{"line":11,"column":1}}}
{"type":"eos","loc":{"start":{"line":11,"column":1},"filename":"/cases/includes.pug","end":{"line":11,"column":1}}} | 1,043 |
2,199 | /*******************************************************************************
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
******************************************************************************/
package the8472.bencode;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class Utils {
/*
* all byte[]/buffer/String conversions use ISO_8859_1 by default because it's round-trip compatible to unicode codepoints 0-255. i.e. it's suitable for binary data of unspecified encodings.
*
* this will garble actual UTF-8 strings, decode those manually if it's meant to be human-readable
*/
public static void str2buf(String in, ByteBuffer out) {
if(out.remaining() < in.length())
throw new BufferOverflowException();
for(int i=0;i<in.length();i++) {
char c = in.charAt(i);
if(c > 0xff)
throw new IllegalArgumentException("only strings with codepoints 0x00 - 0xff are supported. for proper unicode handling convert strings manually. attempted to encode: "+in);
out.put((byte) c);
}
}
public static ByteBuffer str2buf(String str) {
return ByteBuffer.wrap(str.getBytes(StandardCharsets.ISO_8859_1));
}
public static String buf2str(ByteBuffer buf) {
byte[] arr;
int offset;
int len;
if(buf.hasArray()) {
arr = buf.array();
offset = buf.arrayOffset() + buf.position();
len = buf.remaining();
} else {
arr = new byte[buf.remaining()];
buf.get(arr, buf.position(), arr.length);
offset = 0;
len = arr.length;
}
return new String(arr,offset,len, StandardCharsets.ISO_8859_1);
}
public static byte[] buf2ary(ByteBuffer buf) {
byte[] out = new byte[buf.remaining()];
buf.get(out);
return out;
}
public static byte[] str2ary(String str) {
return str.getBytes(StandardCharsets.ISO_8859_1);
}
public static String prettyPrint(Object o) {
StringBuilder b = new StringBuilder(1024);
new PrettyPrinter(b).prettyPrintInternal(o);
return b.toString();
}
public static String stripToAscii(byte[] arr) {
return stripToAscii(ByteBuffer.wrap(arr));
}
public static String stripToAscii(ByteBuffer buf) {
int length = buf.remaining();
char[] out = new char[buf.remaining()];
for(int i=0;i<length ;i++) {
char b = (char)(buf.get(buf.position() + i) & 0xff);
if(b < ' ' || b > '~')
b = '�';
out[i] = b;
}
return new String(out);
}
static void toHex(byte[] toHex, StringBuilder builder, int maxBytes)
{
if(toHex.length < maxBytes)
maxBytes = toHex.length;
builder.ensureCapacity(maxBytes * 2);
for (int i = 0; i < maxBytes; i++) {
int nibble = (toHex[i] & 0xF0) >> 4;
builder.append((char)(nibble < 0x0A ? '0'+nibble : 'A'+nibble-10 ));
nibble = toHex[i] & 0x0F;
builder.append((char)(nibble < 0x0A ? '0'+nibble : 'A'+nibble-10 ));
}
}
public static byte[] hex2ary(CharSequence hex) {
byte[] bytes = new byte[hex.length()/2];
for (int i = 0; i < hex.length(); i += 2)
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16));
return bytes;
}
}
| 1,266 |
752 | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.base.container;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ofbiz.base.component.ComponentConfig;
import org.apache.ofbiz.base.component.ComponentException;
import org.apache.ofbiz.base.component.ComponentLoaderConfig;
import org.apache.ofbiz.base.start.Classpath;
import org.apache.ofbiz.base.start.Start;
import org.apache.ofbiz.base.start.StartupCommand;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.FileUtil;
/**
* ComponentContainer - StartupContainer implementation for Components
*
* The purpose of this container is to load the classpath for all components
* defined in OFBiz. This container must run before any other containers to
* allow components to access any necessary resources. Furthermore, the
* ComponentContainer also builds up the <code>ComponentConfigCache</code>
* defined in <code>ComponentConfig</code> to keep track of loaded components
*
*/
public class ComponentContainer implements Container {
public static final String module = ComponentContainer.class.getName();
private String name;
private final AtomicBoolean loaded = new AtomicBoolean(false);
private final List<Classpath> componentsClassPath = new ArrayList<Classpath>();
@Override
public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException {
if (!loaded.compareAndSet(false, true)) {
throw new ContainerException("Components already loaded, cannot start");
}
this.name = name;
// load the components from framework/base/config/component-load.xml (root components)
try {
for (ComponentLoaderConfig.ComponentDef def: ComponentLoaderConfig.getRootComponents()) {
loadComponentFromConfig(Start.getInstance().getConfig().ofbizHome, def);
}
} catch (IOException | ComponentException e) {
throw new ContainerException(e);
}
loadClassPathForAllComponents(componentsClassPath);
Debug.logInfo("All components loaded", module);
}
/**
* @see org.apache.ofbiz.base.container.Container#start()
*/
public boolean start() throws ContainerException {
return loaded.get();
}
/**
* Iterate over all the components and load their classpath URLs into the classloader
* and set the classloader as the context classloader
*
* @param componentsClassPath: a list of classpaths for all components
* @throws ContainerException
*/
private void loadClassPathForAllComponents(List<Classpath> componentsClassPath) throws ContainerException {
List<URL> allComponentUrls = new ArrayList<URL>();
for(Classpath classPath : componentsClassPath) {
try {
allComponentUrls.addAll(Arrays.asList(classPath.getUrls()));
} catch (MalformedURLException e) {
Debug.logError("Unable to load component classpath" + classPath.toString(), module);
Debug.logError(e.getMessage(), module);
}
}
URL[] componentURLs = allComponentUrls.toArray(new URL[allComponentUrls.size()]);
URLClassLoader classLoader = new URLClassLoader(componentURLs, Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(classLoader);
}
/**
* Checks if <code>ComponentDef.type</code> is a directory or a single component.
* If it is a directory, load the directory, otherwise load a single component
*
* @param parentPath: the parent path of what is being loaded
* @param def: the component or directory loader definition
* @throws IOException
*/
private void loadComponentFromConfig(String parentPath, ComponentLoaderConfig.ComponentDef def) throws IOException {
String location = def.location.startsWith("/") ? def.location : parentPath + "/" + def.location;
if (def.type.equals(ComponentLoaderConfig.ComponentType.COMPONENT_DIRECTORY)) {
loadComponentDirectory(location);
} else if (def.type.equals(ComponentLoaderConfig.ComponentType.SINGLE_COMPONENT)) {
ComponentConfig config = retrieveComponentConfig(def.name, location);
if (config != null) {
loadComponent(config);
}
}
}
/**
* Checks to see if the directory contains a load file (component-load.xml) and
* then delegates loading to the appropriate method
*
* @param directoryName: the name of component directory to load
* @throws IOException
*/
private void loadComponentDirectory(String directoryName) throws IOException {
Debug.logInfo("Auto-Loading component directory : [" + directoryName + "]", module);
File directoryPath = FileUtil.getFile(directoryName);
if (directoryPath.exists() && directoryPath.isDirectory()) {
File componentLoadFile = new File(directoryPath, ComponentLoaderConfig.COMPONENT_LOAD_XML_FILENAME);
if (componentLoadFile != null && componentLoadFile.exists()) {
loadComponentsInDirectoryUsingLoadFile(directoryPath, componentLoadFile);
} else {
loadComponentsInDirectory(directoryPath);
}
} else {
Debug.logError("Auto-Load Component directory not found : " + directoryName, module);
}
}
/**
* load components residing in a directory only if they exist in the component
* load file (component-load.xml) and they are sorted in order from top to bottom
* in the load file
*
* @param directoryPath: the absolute path of the directory
* @param componentLoadFile: the name of the load file (i.e. component-load.xml)
* @throws IOException
*/
private void loadComponentsInDirectoryUsingLoadFile(File directoryPath, File componentLoadFile) throws IOException {
URL configUrl = null;
try {
configUrl = componentLoadFile.toURI().toURL();
List<ComponentLoaderConfig.ComponentDef> componentsToLoad = ComponentLoaderConfig.getComponentsFromConfig(configUrl);
if (componentsToLoad != null) {
for (ComponentLoaderConfig.ComponentDef def: componentsToLoad) {
loadComponentFromConfig(directoryPath.toString(), def);
}
}
} catch (MalformedURLException e) {
Debug.logError(e, "Unable to locate URL for component loading file: " + componentLoadFile.getAbsolutePath(), module);
} catch (ComponentException e) {
Debug.logError(e, "Unable to load components from URL: " + configUrl.toExternalForm(), module);
}
}
/**
* Load all components in a directory because it does not contain
* a load-components.xml file. The components are sorted alphabetically
* for loading purposes
*
* @param directoryPath: the absolute path of the directory
* @throws IOException
*/
private void loadComponentsInDirectory(File directoryPath) throws IOException {
String[] sortedComponentNames = directoryPath.list();
Arrays.sort(sortedComponentNames);
for (String componentName: sortedComponentNames) {
File componentPath = FileUtil.getFile(directoryPath.getCanonicalPath() + File.separator + componentName);
String componentLocation = componentPath.getCanonicalPath();
File configFile = FileUtil.getFile(componentLocation.concat(File.separator).concat(ComponentConfig.OFBIZ_COMPONENT_XML_FILENAME));
if (componentPath.isDirectory() && !componentName.startsWith(".") && configFile.exists()) {
ComponentConfig config = retrieveComponentConfig(null, componentLocation);
if (config != null) {
loadComponent(config);
}
}
}
}
/**
* Fetch the <code>ComponentConfig</code> for a certain component
*
* @param name: component name
* @param location: directory location of the component
* @return The component configuration
*/
private ComponentConfig retrieveComponentConfig(String name, String location) {
ComponentConfig config = null;
try {
config = ComponentConfig.getComponentConfig(name, location);
} catch (ComponentException e) {
Debug.logError("Cannot load component : " + name + " @ " + location + " : " + e.getMessage(), module);
}
if (config == null) {
Debug.logError("Cannot load component : " + name + " @ " + location, module);
}
return config;
}
/**
* Load a single component by adding all its classpath entries to
* the list of classpaths to be loaded
*
* @param config: the component configuration
* @throws IOException
*/
private void loadComponent(ComponentConfig config) throws IOException {
if (config.enabled()) {
Classpath classpath = buildClasspathFromComponentConfig(config);
componentsClassPath.add(classpath);
Debug.logInfo("Added class path for component : [" + config.getComponentName() + "]", module);
} else {
Debug.logInfo("Not loading component [" + config.getComponentName() + "] because it is disabled", module);
}
}
/**
* Construct a <code>Classpath</code> object for a certain component based
* on its configuration defined in <code>ComponentConfig</code>
*
* @param config: the component configuration
* @return the constructed classpath
* @throws IOException
*/
private Classpath buildClasspathFromComponentConfig(ComponentConfig config) throws IOException {
Classpath classPath = new Classpath();
String configRoot = config.getRootLocation().replace('\\', '/');
configRoot = configRoot.endsWith("/") ? configRoot : configRoot + "/";
List<ComponentConfig.ClasspathInfo> classpathInfos = config.getClasspathInfos();
for (ComponentConfig.ClasspathInfo cp: classpathInfos) {
String location = cp.location.replace('\\', '/');
if (!"jar".equals(cp.type) && !"dir".equals(cp.type)) {
Debug.logError("Classpath type '" + cp.type + "' is not supported; '" + location + "' not loaded", module);
continue;
}
location = location.startsWith("/") ? location.substring(1) : location;
String dirLoc = location.endsWith("/*") ? location.substring(0, location.length() - 2) : location;
File path = FileUtil.getFile(configRoot + dirLoc);
if (path.exists()) {
classPath.addComponent(configRoot + location);
if (path.isDirectory() && "dir".equals(cp.type)) {
classPath.addFilesFromPath(path);
}
} else {
Debug.logWarning("Location '" + configRoot + dirLoc + "' does not exist", module);
}
}
return classPath;
}
/**
* @see org.apache.ofbiz.base.container.Container#stop()
*/
public void stop() throws ContainerException {
}
public String getName() {
return name;
}
}
| 4,409 |
9,182 | #include <Autocoders/Python/test/serialize_stringbuffer/ExampleSerializableAc.hpp>
int main(int argc, char** argv) {
Example3::ExampleSerializable ex;
return 0;
}
| 63 |
951 | #include "byteArray.h"
byteArray::byteArray(size_t size)
{
if( size == 0 )
{
_length = 0;
_ptr = nullptr;
return;
}
_length = size;
_ptr = (uint8_t*)malloc(sizeof(uint8_t) * size);
}
byteArray::byteArray(const uint8_t *data,size_t size)
{
if( size == 0 )
{
_length = 0;
_ptr = nullptr;
return;
}
_length = size;
_ptr = (uint8_t*)malloc(sizeof(uint8_t) * size);
memcpy(_ptr,data,sizeof(uint8_t) * size);
}
byteArray::byteArray(const byteArray &array)
{
if(( array._length == 0 )||( array._ptr == nullptr ))
{
delete this->_ptr;
this->_length = 0;
}
this->_length = array._length;
this->_ptr = (uint8_t*)realloc(this->_ptr,sizeof(uint8_t) * array._length);
memcpy(this->_ptr,array._ptr,sizeof(uint8_t) * array._length);
}
byteArray::~byteArray()
{
if( _ptr == nullptr ) return;
delete _ptr;
}
byteArray &byteArray::append(uint8_t data)
{
_ptr = (uint8_t*)realloc(_ptr,sizeof(uint8_t) * ( _length + 1 ) );
_ptr[_length ++] = data;
return *this;
}
byteArray &byteArray::append(const char *s)
{
_ptr = (uint8_t*)realloc(_ptr,sizeof(uint8_t) * ( _length + strlen(s)));
memcpy(&_ptr[_length],s,strlen(s));
_length += strlen(s);
return *this;
}
byteArray &byteArray::append( const byteArray &array )
{
_ptr = (uint8_t*)realloc(_ptr,sizeof(uint8_t) * ( _length + array._length));
memcpy(&_ptr[_length],array._ptr,array._length);
_length += array._length;
return *this;
}
uint8_t byteArray::at(size_t i)
{
return _ptr[i];
}
int byteArray::indexof(char data,int pos)
{
if((this->_length == 0)||(this->_ptr == nullptr)||( pos > this->_length))return -1;
for( int i = pos; i<_length; i++ )
{
if(this->_ptr[ pos + i ] == data)return i;
}
return -1;
}
int byteArray::indexof(const byteArray &array,int pos)
{
bool flag = false;
if((this->_length == 0)||(this->_ptr == nullptr)||( pos > this->_length))return -1;
for( int i = pos; i<( _length - array._length); i++ )
{
flag = true;
for (int n = 0; n < array._length; n++)
{
if( this->_ptr[ pos + i + n ] != array._ptr[n]) { flag = false;break;};
}
if( flag ) return i;
}
return -1;
}
byteArray byteArray::mid(size_t pos,size_t len)
{
if(( pos > this->_length )||( pos < 0 )) return byteArray();
if(( pos == 0 )&&( len == this->_length )) return *this;
if(( pos + len ) > this->_length ) len = -1;
if( len == -1 )
{
return byteArray(&this->_ptr[pos],this->_length - pos );
}
return byteArray();
}
byteArray &byteArray::operator=(const byteArray &array)
{
if( this == &array )return *this;
if(( array._length == 0 )||( array._ptr == nullptr ))
{
delete this->_ptr;
this->_length = 0;
return *this;
}
this->_length = array._length;
this->_ptr = (uint8_t*)realloc(this->_ptr,sizeof(uint8_t) * array._length);
memcpy(this->_ptr,array._ptr,sizeof(uint8_t) * array._length);
return *this;
}
byteArray &byteArray::operator=(const char *str)
{
if( strlen(str) == 0 )
{
delete this->_ptr;
this->_length = 0;
return *this;
}
this->_ptr = (uint8_t*)realloc(this->_ptr,sizeof(uint8_t) * strlen(str));
this->_length = strlen(str);
strcpy((char*)this->_ptr,str);
return *this;
}
uint8_t & byteArray::operator[](size_t i)
{
return _ptr[i];
}
const uint8_t & byteArray::operator[](size_t i) const
{
return _ptr[i];
}
byteArray &byteArray::operator+=(char c)
{
return append(c);
}
byteArray &byteArray::operator+=(const char *s)
{
return append(s);
}
byteArray &byteArray::operator+=(const byteArray &a)
{
return append(a);
}
| 1,745 |
758 | class Account(object):
def __init__(self, first, last, id, balance):
self.first = first
self.last = last
self.id = id
self.balance = balance
def info(self):
return (self.first, self.last, self.id, self.balance)
def __eq__(self, other):
return self.info() == other.info()
def __hash__(self):
return hash((type(self), self.info()))
def __str__(self):
return "Account: %s %s, id %d, balance %d" % self.info()
__repr__ = __str__
| 227 |
593 | package org.ananas.runner.steprunner.gcs;
import static org.apache.beam.sdk.values.Row.toRow;
import com.google.api.services.bigquery.model.TableRow;
import org.ananas.runner.kernel.LoaderStepRunner;
import org.ananas.runner.kernel.StepRunner;
import org.ananas.runner.kernel.model.Step;
import org.ananas.runner.misc.StepConfigHelper;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryUtils;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.Builder;
import org.apache.beam.sdk.schemas.SchemaCoder;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BigQueryLoader extends LoaderStepRunner {
private static final Logger LOG = LoggerFactory.getLogger(BigQueryLoader.class);
public static final String PROJECT = "project";
public static final String DATASET = "dataset";
public static final String TABLE_NAME = "tablename";
public static final String OVERWRITE = "overwrite";
protected BigQueryLoader(Step step, StepRunner previous, boolean isTest) {
super(step, previous, isTest);
}
public void build() {
String projectId = (String) step.config.getOrDefault(PROJECT, "");
String dataset = (String) step.config.getOrDefault(DATASET, "");
String tablename = (String) step.config.getOrDefault(TABLE_NAME, "");
Boolean overwrite = StepConfigHelper.getConfig(step.config, OVERWRITE, Boolean.FALSE);
Schema schema = ((SchemaCoder) previous.getOutput().getCoder()).getSchema();
schema = renameSchemaFieldNameIfNecessary(schema);
this.output = previous.getOutput();
if (isTest) {
// TODO: check configuration
}
Schema finalSchema = schema;
previous
.getOutput()
.apply(
ParDo.of(
new DoFn<Row, TableRow>() {
@ProcessElement
public void processElement(
@Element Row row, OutputReceiver<TableRow> outputReceiver) {
Row renamedRow = row.getValues().stream().collect(toRow(finalSchema));
TableRow tableRow = BigQueryUtils.toTableRow(renamedRow);
outputReceiver.output(tableRow);
}
}))
.apply(
BigQueryIO.writeTableRows()
.withSchema(BigQueryUtils.toTableSchema(finalSchema))
.withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(
overwrite ? WriteDisposition.WRITE_TRUNCATE : WriteDisposition.WRITE_APPEND)
.to(projectId + ":" + dataset + "." + tablename));
}
private Schema renameSchemaFieldNameIfNecessary(Schema schema) {
// TODO: scan whole string and replace unaccepted char to _
Schema.Builder builder = new Builder();
schema
.getFields()
.forEach(
field -> {
String name = renameFieldNameIfNecessary(field.getName());
builder.addField(name, field.getType());
});
return builder.build();
}
private static String renameFieldNameIfNecessary(String oldName) {
String name = oldName;
if (name.contains(".")) {
name = name.replace('.', '_');
}
if (name.contains("-")) {
name = name.replace('-', '_');
}
return name;
}
}
| 1,486 |
2,151 | <filename>sandbox/win/sandbox_poc/pocdll/fs.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/win/sandbox_poc/pocdll/exports.h"
#include "sandbox/win/sandbox_poc/pocdll/utils.h"
// This file contains the tests used to verify the security of the file system.
// Tries to open a file and outputs the result.
// "path" can contain environment variables.
// "output" is the stream for the logging.
void TryOpenFile(const wchar_t *path, FILE *output) {
wchar_t path_expanded[MAX_PATH] = {0};
DWORD size = ::ExpandEnvironmentStrings(path, path_expanded, MAX_PATH - 1);
if (!size) {
fprintf(output, "[ERROR] Cannot expand \"%S\". Error %ld.\r\n", path,
::GetLastError());
}
HANDLE file;
file = ::CreateFile(path_expanded,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, // No security attributes
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL); // No template
if (file && INVALID_HANDLE_VALUE != file) {
fprintf(output, "[GRANTED] Opening file \"%S\". Handle 0x%p\r\n", path,
file);
::CloseHandle(file);
} else {
fprintf(output, "[BLOCKED] Opening file \"%S\". Error %ld.\r\n", path,
::GetLastError());
}
}
void POCDLL_API TestFileSystem(HANDLE log) {
HandleToFile handle2file;
FILE *output = handle2file.Translate(log, "w");
TryOpenFile(L"%SystemDrive%", output);
TryOpenFile(L"%SystemRoot%", output);
TryOpenFile(L"%ProgramFiles%", output);
TryOpenFile(L"%SystemRoot%\\System32", output);
TryOpenFile(L"%SystemRoot%\\explorer.exe", output);
TryOpenFile(L"%SystemRoot%\\Cursors\\arrow_i.cur", output);
TryOpenFile(L"%AllUsersProfile%", output);
TryOpenFile(L"%UserProfile%", output);
TryOpenFile(L"%Temp%", output);
TryOpenFile(L"%AppData%", output);
}
| 851 |
2,508 |
extern zend_class_entry *stub_namespaces_classentry_ce;
ZEPHIR_INIT_CLASS(Stub_Namespaces_ClassEntry);
PHP_METHOD(Stub_Namespaces_ClassEntry, setParam);
PHP_METHOD(Stub_Namespaces_ClassEntry, setParamImported);
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_stub_namespaces_classentry_setparam, 0, 1, Stub\\Namespaces\\A\\B\\Sub, 0)
ZEND_ARG_OBJ_INFO(0, param, Stub\\Namespaces\\A\\B\\Sub, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_stub_namespaces_classentry_setparamimported, 0, 1, Stub\\Namespaces\\A\\B\\Sub, 0)
ZEND_ARG_OBJ_INFO(0, param, Stub\\Namespaces\\A\\B\\Sub, 0)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(stub_namespaces_classentry_method_entry) {
PHP_ME(Stub_Namespaces_ClassEntry, setParam, arginfo_stub_namespaces_classentry_setparam, ZEND_ACC_PUBLIC)
PHP_ME(Stub_Namespaces_ClassEntry, setParamImported, arginfo_stub_namespaces_classentry_setparamimported, ZEND_ACC_PUBLIC)
PHP_FE_END
};
| 405 |
634 | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.mailbox.elasticsearch.v7;
import static org.apache.james.backends.es.v7.IndexCreationFactory.ANALYZER;
import static org.apache.james.backends.es.v7.IndexCreationFactory.BOOLEAN;
import static org.apache.james.backends.es.v7.IndexCreationFactory.CASE_INSENSITIVE;
import static org.apache.james.backends.es.v7.IndexCreationFactory.FIELDS;
import static org.apache.james.backends.es.v7.IndexCreationFactory.FORMAT;
import static org.apache.james.backends.es.v7.IndexCreationFactory.KEEP_MAIL_AND_URL;
import static org.apache.james.backends.es.v7.IndexCreationFactory.KEYWORD;
import static org.apache.james.backends.es.v7.IndexCreationFactory.LONG;
import static org.apache.james.backends.es.v7.IndexCreationFactory.NESTED;
import static org.apache.james.backends.es.v7.IndexCreationFactory.NORMALIZER;
import static org.apache.james.backends.es.v7.IndexCreationFactory.PROPERTIES;
import static org.apache.james.backends.es.v7.IndexCreationFactory.RAW;
import static org.apache.james.backends.es.v7.IndexCreationFactory.REQUIRED;
import static org.apache.james.backends.es.v7.IndexCreationFactory.ROUTING;
import static org.apache.james.backends.es.v7.IndexCreationFactory.SEARCH_ANALYZER;
import static org.apache.james.backends.es.v7.IndexCreationFactory.TYPE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.ATTACHMENTS;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.BCC;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.CC;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.DATE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.FROM;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.HAS_ATTACHMENT;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.HEADERS;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.HTML_BODY;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_ANSWERED;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_DELETED;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_DRAFT;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_FLAGGED;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_RECENT;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.IS_UNREAD;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.MAILBOX_ID;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.MEDIA_TYPE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.MESSAGE_ID;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.MIME_MESSAGE_ID;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.MODSEQ;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.SENT_DATE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.SIZE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.SUBJECT;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.SUBTYPE;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.TEXT;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.TEXT_BODY;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.THREAD_ID;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.TO;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.UID;
import static org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.USER_FLAGS;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import java.io.IOException;
import org.apache.james.backends.es.v7.IndexCreationFactory;
import org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.Attachment;
import org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.EMailer;
import org.apache.james.mailbox.elasticsearch.v7.json.JsonMessageConstants.HEADER;
import org.elasticsearch.common.xcontent.XContentBuilder;
public class MailboxMappingFactory {
private static final int MAXIMUM_TERM_LENGTH = 4096;
private static final String STANDARD = "standard";
private static final String STORE = "store";
public static XContentBuilder getMappingContent() {
try {
return jsonBuilder()
.startObject()
.field("dynamic", "strict")
.startObject(ROUTING)
.field(REQUIRED, true)
.endObject()
.startObject(PROPERTIES)
.startObject(MESSAGE_ID)
.field(TYPE, KEYWORD)
.field(STORE, true)
.endObject()
.startObject(THREAD_ID)
.field(TYPE, KEYWORD)
.endObject()
.startObject(UID)
.field(TYPE, LONG)
.field(STORE, true)
.endObject()
.startObject(MODSEQ)
.field(TYPE, LONG)
.endObject()
.startObject(SIZE)
.field(TYPE, LONG)
.endObject()
.startObject(IS_ANSWERED)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(IS_DELETED)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(IS_DRAFT)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(IS_FLAGGED)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(IS_RECENT)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(IS_UNREAD)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(DATE)
.field(TYPE, IndexCreationFactory.DATE)
.field(FORMAT, "uuuu-MM-dd'T'HH:mm:ssX||uuuu-MM-dd'T'HH:mm:ssXXX||uuuu-MM-dd'T'HH:mm:ssXXXXX")
.endObject()
.startObject(SENT_DATE)
.field(TYPE, IndexCreationFactory.DATE)
.field(FORMAT, "uuuu-MM-dd'T'HH:mm:ssX||uuuu-MM-dd'T'HH:mm:ssXXX||uuuu-MM-dd'T'HH:mm:ssXXXXX")
.endObject()
.startObject(USER_FLAGS)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.startObject(MEDIA_TYPE)
.field(TYPE, KEYWORD)
.endObject()
.startObject(SUBTYPE)
.field(TYPE, KEYWORD)
.endObject()
.startObject(FROM)
.startObject(PROPERTIES)
.startObject(EMailer.NAME)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.endObject()
.startObject(EMailer.ADDRESS)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.field(SEARCH_ANALYZER, KEEP_MAIL_AND_URL)
.startObject(FIELDS)
.startObject(RAW)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.startObject(HEADERS)
.field(TYPE, NESTED)
.startObject(PROPERTIES)
.startObject(HEADER.NAME)
.field(TYPE, KEYWORD)
.endObject()
.startObject(HEADER.VALUE)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.endObject()
.endObject()
.endObject()
.startObject(SUBJECT)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.startObject(FIELDS)
.startObject(RAW)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.endObject()
.endObject()
.startObject(TO)
.startObject(PROPERTIES)
.startObject(EMailer.NAME)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.endObject()
.startObject(EMailer.ADDRESS)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.field(SEARCH_ANALYZER, KEEP_MAIL_AND_URL)
.startObject(FIELDS)
.startObject(RAW)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.startObject(CC)
.startObject(PROPERTIES)
.startObject(EMailer.NAME)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.endObject()
.startObject(EMailer.ADDRESS)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.field(SEARCH_ANALYZER, KEEP_MAIL_AND_URL)
.startObject(FIELDS)
.startObject(RAW)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.startObject(BCC)
.startObject(PROPERTIES)
.startObject(EMailer.NAME)
.field(TYPE, TEXT)
.field(ANALYZER, KEEP_MAIL_AND_URL)
.endObject()
.startObject(EMailer.ADDRESS)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.field(SEARCH_ANALYZER, KEEP_MAIL_AND_URL)
.startObject(FIELDS)
.startObject(RAW)
.field(TYPE, KEYWORD)
.field(NORMALIZER, CASE_INSENSITIVE)
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.startObject(MAILBOX_ID)
.field(TYPE, KEYWORD)
.field(STORE, true)
.endObject()
.startObject(MIME_MESSAGE_ID)
.field(TYPE, KEYWORD)
.endObject()
.startObject(TEXT_BODY)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.endObject()
.startObject(HTML_BODY)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.endObject()
.startObject(HAS_ATTACHMENT)
.field(TYPE, BOOLEAN)
.endObject()
.startObject(ATTACHMENTS)
.startObject(PROPERTIES)
.startObject(Attachment.FILENAME)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.endObject()
.startObject(Attachment.TEXT_CONTENT)
.field(TYPE, TEXT)
.field(ANALYZER, STANDARD)
.endObject()
.startObject(Attachment.MEDIA_TYPE)
.field(TYPE, KEYWORD)
.endObject()
.startObject(Attachment.SUBTYPE)
.field(TYPE, KEYWORD)
.endObject()
.startObject(Attachment.FILE_EXTENSION)
.field(TYPE, KEYWORD)
.endObject()
.startObject(Attachment.CONTENT_DISPOSITION)
.field(TYPE, KEYWORD)
.endObject()
.endObject()
.endObject()
.endObject()
.endObject();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 9,924 |
852 | <gh_stars>100-1000
#include "CondFormats/Luminosity/interface/LumiSectionData.h"
#include "CondFormats/Luminosity/interface/LumiCorrections.h"
| 51 |
7,137 | <gh_stars>1000+
package io.onedev.server.plugin.imports.gitea;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.ws.rs.client.Client;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import io.onedev.commons.utils.TaskLogger;
import io.onedev.server.web.editable.annotation.ChoiceProvider;
import io.onedev.server.web.editable.annotation.Editable;
import io.onedev.server.web.util.WicketUtils;
@Editable
public class IssueImportSource implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(IssueImportSource.class);
private String repository;
@Editable(order=400, name="Gitea Repository", description="Choose Gitea repository to import issues from")
@ChoiceProvider("getRepositoryChoices")
@NotEmpty
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
@SuppressWarnings("unused")
private static List<String> getRepositoryChoices() {
List<String> choices = new ArrayList<>();
ImportServer server = WicketUtils.getPage().getMetaData(ImportServer.META_DATA_KEY);
Client client = server.newClient();
try {
String apiEndpoint = server.getApiEndpoint("/user/repos");
for (JsonNode repoNode: ImportUtils.list(client, apiEndpoint, new TaskLogger() {
@Override
public void log(String message, String sessionId) {
logger.info(message);
}
})) {
String repoName = repoNode.get("name").asText();
String ownerName = repoNode.get("owner").get("login").asText();
choices.add(ownerName + "/" + repoName);
}
} finally {
client.close();
}
Collections.sort(choices);
return choices;
}
}
| 683 |
19,438 | <reponame>r00ster91/serenity<filename>Kernel/API/POSIX/sys/wait.h
/*
* Copyright (c) 2018-2021, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <Kernel/API/POSIX/sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define WEXITSTATUS(status) (((status)&0xff00) >> 8)
#define WSTOPSIG(status) WEXITSTATUS(status)
#define WTERMSIG(status) ((status)&0x7f)
#define WIFEXITED(status) (WTERMSIG(status) == 0)
#define WIFSTOPPED(status) (((status)&0xff) == 0x7f)
#define WIFSIGNALED(status) (((char)(((status)&0x7f) + 1) >> 1) > 0)
#define WNOHANG 1
#define WUNTRACED 2
#define WSTOPPED WUNTRACED
#define WEXITED 4
#define WCONTINUED 8
#define WNOWAIT 0x1000000
typedef enum {
P_ALL = 1,
P_PID,
P_PGID
} idtype_t;
#ifdef __cplusplus
}
#endif
| 370 |
902 | package com.github.davidmoten.rtree.geometry.internal;
import com.github.davidmoten.guavamini.Objects;
import com.github.davidmoten.guavamini.Optional;
import com.github.davidmoten.rtree.geometry.Circle;
import com.github.davidmoten.rtree.geometry.Geometries;
import com.github.davidmoten.rtree.geometry.Line;
import com.github.davidmoten.rtree.geometry.Point;
import com.github.davidmoten.rtree.geometry.Rectangle;
import com.github.davidmoten.rtree.internal.Line2D;
import com.github.davidmoten.rtree.internal.RectangleUtil;
import com.github.davidmoten.rtree.internal.util.ObjectsHelper;
/**
* A line segment.
*/
public final class LineDouble implements Line {
private final double x1;
private final double y1;
private final double x2;
private final double y2;
private LineDouble(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public static LineDouble create(double x1, double y1, double x2, double y2) {
return new LineDouble(x1, y1, x2, y2);
}
@Override
public double distance(Rectangle r) {
if (r.contains(x1, y1) || r.contains(x2, y2)) {
return 0;
} else {
double d1 = distance(r.x1(), r.y1(), r.x1(), r.y2());
if (d1 == 0)
return 0;
double d2 = distance(r.x1(), r.y2(), r.x2(), r.y2());
if (d2 == 0)
return 0;
double d3 = distance(r.x2(), r.y2(), r.x2(), r.y1());
double d4 = distance(r.x2(), r.y1(), r.x1(), r.y1());
return Math.min(d1, Math.min(d2, Math.min(d3, d4)));
}
}
private double distance(double x1, double y1, double x2, double y2) {
Line2D line = new Line2D(x1, y1, x2, y2);
double d1 = line.ptSegDist(this.x1, this.y1);
double d2 = line.ptSegDist(this.x2, this.y2);
Line2D line2 = new Line2D(this.x1, this.y1, this.x2, this.y2);
double d3 = line2.ptSegDist(x1, y1);
if (d3 == 0)
return 0;
double d4 = line2.ptSegDist(x2, y2);
if (d4 == 0)
return 0;
else
return Math.min(d1, Math.min(d2, Math.min(d3, d4)));
}
@Override
public Rectangle mbr() {
return Geometries.rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2),
Math.max(y1, y2));
}
@Override
public boolean intersects(Rectangle r) {
return RectangleUtil.rectangleIntersectsLine(r.x1(), r.y1(), r.x2() - r.x1(),
r.y2() - r.y1(), x1, y1, x2, y2);
}
@Override
public double x1() {
return x1;
}
@Override
public double y1() {
return y1;
}
@Override
public double x2() {
return x2;
}
@Override
public double y2() {
return y2;
}
@Override
public boolean intersects(Line b) {
Line2D line1 = new Line2D(x1, y1, x2, y2);
Line2D line2 = new Line2D(b.x1(), b.y1(), b.x2(), b.y2());
return line2.intersectsLine(line1);
}
@Override
public boolean intersects(Point point) {
return intersects(point.mbr());
}
@Override
public boolean intersects(Circle circle) {
return GeometryUtil.lineIntersects(x1, y1, x2, y2, circle);
}
@Override
public int hashCode() {
return Objects.hashCode(x1, y1, x2, y2);
}
@Override
public boolean equals(Object obj) {
Optional<LineDouble> other = ObjectsHelper.asClass(obj, LineDouble.class);
if (other.isPresent()) {
return Objects.equal(x1, other.get().x1) && Objects.equal(x2, other.get().x2)
&& Objects.equal(y1, other.get().y1) && Objects.equal(y2, other.get().y2);
} else
return false;
}
@Override
public boolean isDoublePrecision() {
return true;
}
}
| 1,914 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/network/network_feature_pod_button.h"
#include "base/check.h"
#include "ui/base/metadata/metadata_impl_macros.h"
namespace ash {
NetworkFeaturePodButton::NetworkFeaturePodButton(
FeaturePodControllerBase* controller,
Delegate* delegate)
: FeaturePodButton(controller), delegate_(delegate) {
DCHECK(delegate);
}
NetworkFeaturePodButton::~NetworkFeaturePodButton() = default;
void NetworkFeaturePodButton::OnThemeChanged() {
FeaturePodButton::OnThemeChanged();
delegate_->OnFeaturePodButtonThemeChanged();
}
BEGIN_METADATA(NetworkFeaturePodButton, FeaturePodButton)
END_METADATA
} // namespace ash
| 241 |
370 | /**
* @file hwaccel_libav_common.c
* @author <NAME> <<EMAIL>>
*
* @brief This file contains functions related to hw acceleration
*/
/*
* Copyright (c) 2018-2021 CESNET z.s.p.o.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by CESNET z.s.p.o.
*
* 4. Neither the name of the CESNET 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 AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#include "config_unix.h"
#include "config_win32.h"
#endif
#include "hwaccel_libav_common.h"
#include "libavcodec_common.h"
void hwaccel_state_init(struct hw_accel_state *hwaccel){
hwaccel->type = HWACCEL_NONE;
hwaccel->copy = false;
hwaccel->uninit = NULL;
hwaccel->tmp_frame = NULL;
hwaccel->uninit = NULL;
hwaccel->ctx = NULL;
}
void hwaccel_state_reset(struct hw_accel_state *hwaccel){
if(hwaccel->ctx){
hwaccel->uninit(hwaccel);
}
if(hwaccel->tmp_frame){
av_frame_free(&hwaccel->tmp_frame);
}
hwaccel_state_init(hwaccel);
}
#ifdef HWACC_COMMON_IMPL
int create_hw_device_ctx(enum AVHWDeviceType type, AVBufferRef **device_ref){
const char *device_paths[] = { NULL, "/dev/dri/renderD128" };
int ret;
for(size_t i = 0; i < sizeof(device_paths) / sizeof(*device_paths); i++){
ret = av_hwdevice_ctx_create(device_ref, type, device_paths[i], NULL, 0);
if(ret == 0)
return 0;
}
log_msg(LOG_LEVEL_ERROR, "[hw accel] Unable to create hwdevice!!\n");
return ret;
}
int create_hw_frame_ctx(AVBufferRef *device_ref,
int width,
int height,
enum AVPixelFormat format,
enum AVPixelFormat sw_format,
int decode_surfaces,
AVBufferRef **ctx)
{
*ctx = av_hwframe_ctx_alloc(device_ref);
if(!*ctx){
log_msg(LOG_LEVEL_ERROR, "[hw accel] Failed to allocate hwframe_ctx!!\n");
return -1;
}
AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(void *) (*ctx)->data;
frames_ctx->format = format;
frames_ctx->width = width;
frames_ctx->height = height;
frames_ctx->sw_format = sw_format;
frames_ctx->initial_pool_size = decode_surfaces;
int ret = av_hwframe_ctx_init(*ctx);
if (ret < 0) {
av_buffer_unref(ctx);
*ctx = NULL;
log_msg(LOG_LEVEL_ERROR, "[hw accel] Unable to init hwframe_ctx: %s\n\n",
av_err2str(ret));
return ret;
}
return 0;
}
void transfer_frame(struct hw_accel_state *s, AVFrame *frame){
av_hwframe_transfer_data(s->tmp_frame, frame, 0);
av_frame_copy_props(s->tmp_frame, frame);
av_frame_unref(frame);
av_frame_move_ref(frame, s->tmp_frame);
}
#endif
| 1,886 |
851 | from xviz_avs.builder.declarative_ui.base_ui_builder import XVIZBaseUiBuilder
from xviz_avs.builder.declarative_ui.constants import UI_TYPES
class XVIZVideoBuilder(XVIZBaseUiBuilder):
def __init__(self, cameras, **kwargs):
super().__init__(UI_TYPES.VIDEO, **kwargs)
self._cameras = cameras
self._validate()
def _validate(self):
if self._cameras is None:
self._validateError('A Video must have a stream associated')
def get_ui(self):
obj = super().get_ui()
obj["cameras"] = self._cameras
return obj
| 252 |
740 | <gh_stars>100-1000
#ifndef VG_MEMOIZING_GRAPH_HPP_INCLUDED
#define VG_MEMOIZING_GRAPH_HPP_INCLUDED
/** \file
* memoizing_graph.hpp: defines a handle graph implementation memoizes the results
* of certain handle operations
*/
#include "handle.hpp"
#include <unordered_map>
namespace vg {
using namespace std;
/**
* A PathPositionHandleGraph implementation that memoizes the results of get_handle
* and steps_of_handle.
*/
class MemoizingGraph : public PathPositionHandleGraph {
public:
/// Initialize with a pointer to graph we want to memoize operations for
MemoizingGraph(const PathPositionHandleGraph* graph);
/// Default constructor -- not actually functional
MemoizingGraph() = default;
/// Default destructor
~MemoizingGraph() = default;
//////////////////////////
/// HandleGraph interface
//////////////////////////
/// Method to check if a node exists by ID
virtual bool has_node(id_t node_id) const;
/// Look up the handle for the node with the given ID in the given orientation
virtual handle_t get_handle(const id_t& node_id, bool is_reverse = false) const;
/// Get the ID from a handle
virtual id_t get_id(const handle_t& handle) const;
/// Get the orientation of a handle
virtual bool get_is_reverse(const handle_t& handle) const;
/// Invert the orientation of a handle (potentially without getting its ID)
virtual handle_t flip(const handle_t& handle) const;
/// Get the length of a node
virtual size_t get_length(const handle_t& handle) const;
/// Get the sequence of a node, presented in the handle's local forward
/// orientation.
virtual string get_sequence(const handle_t& handle) const;
/// Loop over all the handles to next/previous (right/left) nodes. Passes
/// them to a callback which returns false to stop iterating and true to
/// continue. Returns true if we finished and false if we stopped early.
virtual bool follow_edges_impl(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const;
/// Loop over all the nodes in the graph in their local forward
/// orientations, in their internal stored order. Stop if the iteratee
/// returns false. Can be told to run in parallel, in which case stopping
/// after a false return value is on a best-effort basis and iteration
/// order is not defined.
virtual bool for_each_handle_impl(const function<bool(const handle_t&)>& iteratee, bool parallel = false) const;
/// Return the number of nodes in the graph.
virtual size_t get_node_count() const;
/// Return the smallest ID in the graph, or some smaller number if the
/// smallest ID is unavailable. Return value is unspecified if the graph is empty.
virtual id_t min_node_id() const;
/// Return the largest ID in the graph, or some larger number if the
/// largest ID is unavailable. Return value is unspecified if the graph is empty.
virtual id_t max_node_id() const;
////////////////////////////////////////////
// Path handle graph interface
////////////////////////////////////////////
/// Returns the number of paths stored in the graph
virtual size_t get_path_count() const;
/// Determine if a path name exists and is legal to get a path handle for.
virtual bool has_path(const std::string& path_name) const;
/// Look up the path handle for the given path name.
/// The path with that name must exist.
virtual path_handle_t get_path_handle(const std::string& path_name) const;
/// Look up the name of a path from a handle to it
virtual std::string get_path_name(const path_handle_t& path_handle) const;
/// Look up whether a path is circular
virtual bool get_is_circular(const path_handle_t& path_handle) const;
/// Returns the number of node steps in the path
virtual size_t get_step_count(const path_handle_t& path_handle) const;
/// Get a node handle (node ID and orientation) from a handle to an step on a path
virtual handle_t get_handle_of_step(const step_handle_t& step_handle) const;
/// Returns a handle to the path that an step is on
virtual path_handle_t get_path_handle_of_step(const step_handle_t& step_handle) const;
/// Get a handle to the first step, which will be an arbitrary step in a circular path
/// that we consider "first" based on our construction of the path. If the path is empty,
/// then the implementation must return the same value as path_end().
virtual step_handle_t path_begin(const path_handle_t& path_handle) const;
/// Get a handle to a fictitious position past the end of a path. This position is
/// returned by get_next_step for the final step in a path in a non-circular path.
/// Note: get_next_step will *NEVER* return this value for a circular path.
virtual step_handle_t path_end(const path_handle_t& path_handle) const;
/// Get a handle to the last step, which will be an arbitrary step in a circular path that
/// we consider "last" based on our construction of the path. If the path is empty
/// then the implementation must return the same value as path_front_end().
virtual step_handle_t path_back(const path_handle_t& path_handle) const;
/// Get a handle to a fictitious position before the beginning of a path. This position is
/// return by get_previous_step for the first step in a path in a non-circular path.
/// Note: get_previous_step will *NEVER* return this value for a circular path.
virtual step_handle_t path_front_end(const path_handle_t& path_handle) const;
/// Returns true if the step is not the last step in a non-circular path.
virtual bool has_next_step(const step_handle_t& step_handle) const;
/// Returns true if the step is not the first step in a non-circular path.
virtual bool has_previous_step(const step_handle_t& step_handle) const;
/// Returns a handle to the next step on the path. If the given step is the final step
/// of a non-circular path, this method has undefined behavior. In a circular path,
/// the "last" step will loop around to the "first" step.
virtual step_handle_t get_next_step(const step_handle_t& step_handle) const;
/// Returns a handle to the previous step on the path. If the given step is the first
/// step of a non-circular path, this method has undefined behavior. In a circular path,
/// it will loop around from the "first" step (i.e. the one returned by path_begin) to
/// the "last" step.
virtual step_handle_t get_previous_step(const step_handle_t& step_handle) const;
protected:
/// Execute a function on each path in the graph. If it returns false, stop
/// iteration. Returns true if we finished and false if we stopped early.
virtual bool for_each_path_handle_impl(const std::function<bool(const path_handle_t&)>& iteratee) const;
/// Execute a function on each step of a handle in any path. If it
/// returns false, stop iteration. Returns true if we finished and false if
/// we stopped early.
virtual bool for_each_step_on_handle_impl(const handle_t& handle,
const std::function<bool(const step_handle_t&)>& iteratee) const;
public:
/// Returns a vector of all steps of a node on paths. Optionally restricts to
/// steps that match the handle in orientation.
virtual std::vector<step_handle_t> steps_of_handle(const handle_t& handle,
bool match_orientation = false) const;
/// Returns true if the given path is empty, and false otherwise
virtual bool is_empty(const path_handle_t& path_handle) const;
////////////////////////////////////////////////////////////////////////////
// Path position handle graph interface
////////////////////////////////////////////////////////////////////////////
/// Returns the length of a path measured in bases of sequence.
virtual size_t get_path_length(const path_handle_t& path_handle) const;
/// Returns the position along the path of the beginning of this step measured in
/// bases of sequence. In a circular path, positions start at the step returned by
/// path_begin().
virtual size_t get_position_of_step(const step_handle_t& step) const;
/// Returns the step at this position, measured in bases of sequence starting at
/// the step returned by path_begin(). If the position is past the end of the
/// path, returns path_end().
virtual step_handle_t get_step_at_position(const path_handle_t& path,
const size_t& position) const;
protected:
/// Execute an itteratee on each step and its path relative position and orientation
/// on a handle in any path. Iteration will stop early if the iteratee returns false.
/// This method returns false if iteration was stopped early, else true.
virtual bool for_each_step_position_on_handle(const handle_t& handle,
const std::function<bool(const step_handle_t&, const bool&, const size_t&)>& iteratee) const;
public:
/// The largest number of calls to get_handle we will memoize
size_t max_handle_memo_size = 500;
/// The largest number of calls to steps_of_handle we will memoize
size_t max_steps_of_handle_memo_size = 500;
private:
/// The graph we're memoizing operations for
const PathPositionHandleGraph* graph = nullptr;
/// Memo for get_handle
unordered_map<id_t, handle_t> get_handle_memo;
/// Memo for steps_of_handle
unordered_map<handle_t, vector<step_handle_t>> steps_of_handle_memo;
};
}
#endif
| 4,079 |
2,219 | #!/usr/bin/env python
#
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Creates an AndroidManifest.xml for an incremental APK.
Given the manifest file for the real APK, generates an AndroidManifest.xml with
the application class changed to IncrementalApplication.
"""
import argparse
import os
import subprocess
import sys
import tempfile
import zipfile
from xml.etree import ElementTree
sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir, 'gyp'))
from util import build_utils
from util import manifest_utils
from util import resource_utils
_INCREMENTAL_APP_NAME = 'org.chromium.incrementalinstall.BootstrapApplication'
_META_DATA_APP_NAME = 'incremental-install-real-app'
_DEFAULT_APPLICATION_CLASS = 'android.app.Application'
_META_DATA_INSTRUMENTATION_NAMES = [
'incremental-install-real-instrumentation-0',
'incremental-install-real-instrumentation-1',
]
_INCREMENTAL_INSTRUMENTATION_CLASSES = [
'android.app.Instrumentation',
'org.chromium.incrementalinstall.SecondInstrumentation',
]
def _AddNamespace(name):
"""Adds the android namespace prefix to the given identifier."""
return '{%s}%s' % (manifest_utils.ANDROID_NAMESPACE, name)
def _ParseArgs(args):
parser = argparse.ArgumentParser()
parser.add_argument(
'--src-manifest', required=True, help='The main manifest of the app')
parser.add_argument('--disable-isolated-processes',
help='Changes all android:isolatedProcess to false. '
'This is required on Android M+',
action='store_true')
parser.add_argument(
'--out-apk', required=True, help='Path to output .ap_ file')
parser.add_argument(
'--in-apk', required=True, help='Path to non-incremental .ap_ file')
parser.add_argument(
'--aapt2-path', required=True, help='Path to the Android aapt tool')
parser.add_argument(
'--android-sdk-jars', help='GN List of resource apks to include.')
ret = parser.parse_args(build_utils.ExpandFileArgs(args))
ret.android_sdk_jars = build_utils.ParseGnList(ret.android_sdk_jars)
return ret
def _CreateMetaData(parent, name, value):
meta_data_node = ElementTree.SubElement(parent, 'meta-data')
meta_data_node.set(_AddNamespace('name'), name)
meta_data_node.set(_AddNamespace('value'), value)
def _ProcessManifest(path, arsc_package_name, disable_isolated_processes):
doc, manifest_node, app_node = manifest_utils.ParseManifest(path)
# Ensure the manifest package matches that of the apk's arsc package
# So that resource references resolve correctly. The actual manifest
# package name is set via --rename-manifest-package.
manifest_node.set('package', arsc_package_name)
# Pylint for some reason things app_node is an int.
# pylint: disable=no-member
real_app_class = app_node.get(_AddNamespace('name'),
_DEFAULT_APPLICATION_CLASS)
app_node.set(_AddNamespace('name'), _INCREMENTAL_APP_NAME)
# pylint: enable=no-member
_CreateMetaData(app_node, _META_DATA_APP_NAME, real_app_class)
# Seems to be a bug in ElementTree, as doc.find() doesn't work here.
instrumentation_nodes = doc.findall('instrumentation')
assert len(instrumentation_nodes) <= 2, (
'Need to update incremental install to support >2 <instrumentation> tags')
for i, instrumentation_node in enumerate(instrumentation_nodes):
real_instrumentation_class = instrumentation_node.get(_AddNamespace('name'))
instrumentation_node.set(_AddNamespace('name'),
_INCREMENTAL_INSTRUMENTATION_CLASSES[i])
_CreateMetaData(app_node, _META_DATA_INSTRUMENTATION_NAMES[i],
real_instrumentation_class)
ret = ElementTree.tostring(doc.getroot(), encoding='UTF-8')
# Disable check for page-aligned native libraries.
ret = ret.replace(b'extractNativeLibs="false"', b'extractNativeLibs="true"')
if disable_isolated_processes:
ret = ret.replace(b'isolatedProcess="true"', b'isolatedProcess="false"')
return ret
def main(raw_args):
options = _ParseArgs(raw_args)
arsc_package, _ = resource_utils.ExtractArscPackage(options.aapt2_path,
options.in_apk)
# Extract version from the compiled manifest since it might have been set
# via aapt, and not exist in the manifest's text form.
version_code, version_name, manifest_package = (
resource_utils.ExtractBinaryManifestValues(options.aapt2_path,
options.in_apk))
new_manifest_data = _ProcessManifest(options.src_manifest, arsc_package,
options.disable_isolated_processes)
with tempfile.NamedTemporaryFile() as tmp_manifest, \
tempfile.NamedTemporaryFile() as tmp_apk:
tmp_manifest.write(new_manifest_data)
tmp_manifest.flush()
cmd = [
options.aapt2_path, 'link', '-o', tmp_apk.name, '--manifest',
tmp_manifest.name, '-I', options.in_apk, '--replace-version',
'--version-code', version_code, '--version-name', version_name,
'--rename-manifest-package', manifest_package, '--debug-mode'
]
for j in options.android_sdk_jars:
cmd += ['-I', j]
subprocess.check_call(cmd)
with zipfile.ZipFile(options.out_apk, 'w') as z:
path_transform = lambda p: None if p != 'AndroidManifest.xml' else p
build_utils.MergeZips(z, [tmp_apk.name], path_transform=path_transform)
path_transform = lambda p: None if p == 'AndroidManifest.xml' else p
build_utils.MergeZips(z, [options.in_apk], path_transform=path_transform)
if __name__ == '__main__':
main(sys.argv[1:])
| 2,204 |
4,009 | {
"CurrVersion": "1.4",
"MinCompatibleVersion": "1.0",
"Description": "schema update for cluster metadata cleanup",
"SchemaUpdateCqlFiles": [
"cluster_metadata.sql"
]
}
| 69 |
1,564 | package org.modelmapper.convention;
import org.testng.annotations.Test;
/**
* Tests the {@link StandardMatchingStrategy} against various source and destination hierarchy
* scenarios.
*
* @author <NAME>
*/
@Test
public class StandardMatchingStrategyTest extends InexactMatchingStrategyTest {
public StandardMatchingStrategyTest() {
super(new StandardMatchingStrategy());
}
/**
* <pre>
* a/b/d <> a/b/c/d
* </pre>
*/
public void shouldNotMatchMissingSourceToken() {
match("a", "b", "d").to("a", "b", "c", "d").assertNoMatch();
}
/**
* <pre>
* a/b/c <> aC
* a/b/c <> a/C
* </pre>
*/
public void shouldNotMatchMissingDestinationToken() {
match("a", "b", "c").to("aC").assertNoMatch();
match("a", "b", "c").to("a", "c").assertNoMatch();
}
/**
* <pre>
* a/bc/d -> a/c/bd
* order/cust/addr/value -> order/addr/cust/value
* </pre>
*/
public void shouldMatchUnorderedSourceTokens() {
match("a", "bC", "d").to("a", "c", "bD").assertMatch();
match("order", "cust", "addr", "value").to("order", "addr", "cust", "value").assertMatch();
}
}
| 496 |
5,169 | {
"name": "Astro",
"version": "2.0.0",
"summary": "A RoboPod containing a small collection of utilities for project reuse",
"homepage": "https://RobotsAndPencils.com",
"license": {
"type": "MIT",
"text": "Copyright (c) 2015 Robots and Pencils, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\nNeither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. \nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
},
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/RobotsAndPencils/Astro.git",
"tag": "2.0.0"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"subspecs": [
{
"name": "Logging",
"source_files": "Astro/Logging/**/*.swift"
},
{
"name": "Networking",
"source_files": "Astro/Networking/**/*.swift",
"dependencies": {
"Astro/Logging": [
],
"Alamofire": [
"~> 3.3"
],
"Freddy": [
"~> 2.0"
],
"SwiftTask": [
"5.0"
]
}
},
{
"name": "Security",
"source_files": "Astro/Security/**/*.swift",
"dependencies": {
"Astro/Logging": [
]
}
},
{
"name": "UI",
"source_files": "Astro/UI/**/*.swift",
"frameworks": "UIKit"
},
{
"name": "Utils",
"source_files": "Astro/Utils/**/*.swift"
}
]
}
| 985 |
313 | <reponame>740326093/-<gh_stars>100-1000
//
// YBLMillionMessageTableView.h
// 手机云采
//
// Created by 乔同新 on 2017/7/27.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger,MillionType) {
/**
* 公海客户
*/
MillionTypePublic,
/**
* 已关注客户
*/
MillionTypeMine,
/**
* 选择客户
*/
MillionTypeSelect
};
@interface YBLMillionMessageTableView : UITableView
@property (nonatomic, weak) NSMutableArray *milionDataArray;
- (instancetype)initWithFrame:(CGRect)frame
style:(UITableViewStyle)style
millionType:(MillionType)millionType;
@end
| 347 |
1,025 | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file afAppStringConstants.h
///
//==================================================================================
// Infra:
#include <AMDTBaseTools/Include/AMDTDefinitions.h>
// Application title:
#define AF_STR_AMDAppDataDirectory L"AMD"
#define AF_STR_NoteTitle "Note"
#define AF_STR_WelcomePage "Welcome Page"
#define AF_STR_TitleRunningMode L" (%ls)"
#define AF_STR_TitleSeparator L" -"
#define AF_STR_TitleModeFormat L"| %ls"
#define AF_STR_TitleModeFormatA "| %1"
#define AF_STR_TitleModeSessionFormat L"| %ls (%ls)"
#define AF_STR_TitleModeSessionFormatA "| %1 (%2)"
#define AF_STR_TitleRunModeRunning L"Running"
#define AF_STR_TitleRunModeSuspended L"Suspended"
#define AF_STR_TitleRunModePaused L"Paused"
#define AF_STR_TitleRunModeDataTranslating L"Translating Data"
#define AF_STR_TitleNoProjectLoaded L"No Project Loaded"
// Tree root:
#define AF_STR_ApplicationTreeViewCaption L"%ls Explorer"
#define AF_STR_ApplicationTreeViewCommandName L"&%ls Explorer"
#define AF_STR_ApplicationTreeBackTooltip "Back"
#define AF_STR_ApplicationTreeBackToTooltip "Back to "
#define AF_STR_ApplicationTreeForwardTooltip "Forward"
#define AF_STR_ApplicationTreeForwardToTooltip "Forward to "
#define AF_STR_ApplicationTreeRootRunning "(Running)"
#define AF_STR_ApplicationTreeRootStopped "No project loaded"
#define AF_STR_ApplicationTreeNotRunning "Not running"
#define AF_STR_ApplicationTreeSeparator " - "
#define AF_STR_Underscore "_"
// General strings:
#define AF_STR_Empty L""
#define AF_STR_NotAvailable L"N/A"
#define AF_STR_NotAvailableA "N/A"
#define AF_STR_OutOfScope "Out Of Scope"
#define AF_STR_More L"More..."
#define AF_STR_MoreA "More..."
#define AF_STR_NoItems L"No Items"
#define AF_STR_Yes L"Yes"
#define AF_STR_No L"No"
#define AF_STR_OK_Button "OK"
#define AF_STR_Open_Button "&Open"
#define AF_STR_Cancel_Button "Cancel"
#define AF_STR_Close_Button L"&Close"
#define AF_STR_Attach_Button "&Attach"
#define AF_STR_Refresh_Button "&Refresh"
#define AF_STR_EmptyStr L"Empty"
#define AF_STR_Comma L","
#define AF_STR_CommaA ","
#define AF_STR_Semicolon L";"
#define AF_STR_Colon ":"
#define AF_STR_ColonW L":"
#define AF_STR_Shtrudel '@'
#define AF_STR_None L"None"
#define AF_STR_Unknown L"Unknown"
#define AF_STR_Total L"Total"
#define AF_STR_TotalA "Total"
#define AF_Str_MenuSeparator L"/"
#define AF_STR_pngFileExt L"png"
#define AF_STR_HyphenA "-"
#define AF_STR_Hyphen L'-'
#define AF_STR_StandaloneProduct L"Standalone"
#define AF_STR_ConfirmDeletion L"Are you sure you want to delete "
#define AF_STR_ConfirmRemove "Are you sure you want to remove %1 from project?"
#define AF_STR_ConfirmRemoveMultiple "Are you sure you want to remove the selected files from the project?"
#define AF_STR_NDAVersion L"NDA version"
#define AF_STR_InternalVersion L"AMD internal only"
#define AF_STR_Debug L"Debug binaries"
#define AF_STR_DoneLine L"----------------- Done -----------------"
#define AF_STR_Space L" "
#define AF_STR_SpaceA " "
#define AF_STR_Empty L""
#define AF_STR_EmptyA ""
#define AF_STR_Enabled L"Enabled"
#define AF_STR_Disabled L"Disabled"
#define AF_STR_Deleted L"Deleted"
#define AF_STR_PropertiesHandle L"Handle"
#define AF_STR_KilobytesShort L"KB"
#define AF_STR_nullptrContext L"No Context"
#define AF_STR_NewLine L"\n"
#define AF_STR_NewLineA "\n"
#define AF_STR_Tab L"\t"
#define AF_STR_Error L"Error"
#define AF_STR_ErrorA "Error"
#define AF_STR_Warning L"Warning"
#define AF_STR_WarningA "Warning"
#define AF_STR_Information L"Information"
#define AF_STR_InformationA "Information"
#define AF_STR_Question L"Question"
#define AF_STR_QuestionA "Question"
#define AF_STR_Message L"Message"
#define AF_STR_MessageA "Message"
#define AF_STR_Ready L"Ready"
#define AF_STR_AddButton "&Add >>"
#define AF_STR_RemoveButton "<< &Remove"
#define AF_STR_RemoveAllButton "Remove A&ll"
#define AF_STR_ApplyButton "Apply"
#define AF_STR_QStringAppend "%1 %2"
// Welcome page:
#define AF_STR_WelcomeDirectory L"HTML"
#define AF_STR_WelcomeFileName "Welcome.html"
#define AF_STR_WelcomeFileNameAnalyzeModeNA "WelcomeAnalyzeNA.html"
#define AF_STR_WelcomeFileExtension L"html"
#define AF_STR_WelcomeFileCSSExtension L"css"
#define AF_STR_Id L"ID"
#define AF_STR_Platform L"Platform"
#define AF_STR_Device L"Device"
#define AF_STR_Value L"Value"
#define AF_STR_ValueA "Value"
#define AF_STR_User L"User"
#define AF_STR_Item L"Item"
#define AF_STR_Size L"Size"
#define AF_STR_Type L"Type"
#define AF_STR_TypeA "Type"
#define AF_STR_FilePath L"File Path"
#define AF_STR_ProcessName L"Process Name"
#define AF_STR_FileName L"File Name"
#define AF_STR_Arguments L"Arguments"
#define AF_STR_Title L"Title"
#define AF_STR_Partial L"Partial"
#define AF_STR_Full L"Full"
#define AF_STR_RGBA L"RGBA"
#define AF_STR_Description L"Description"
#define AF_STR_FunctionName L"Function Name"
#define AF_STR_OpenGL L"OpenGL"
#if AMDT_BUILD_TARGET == AMDT_LINUX_OS
#define AF_STR_DLLName L"Module Name"
#else
#define AF_STR_DLLName L"DLL Name"
#endif
#define AF_STR_CLKernelDeclaration L"__kernel"
#define AF_STR_CLKernelDeclarationAlternative L"kernel"
#define AF_STR_CLKernelReturnType L"void"
#define AF_STR_IntFormat L"%d"
#define AF_STR_UIntFormat L"%u"
#define AF_STR_UInt64Format L"%llu"
#define AF_STR_LeftParenthesis L"("
#define AF_STR_RightParenthesis L")"
// General strings:
#define AF_STR_Name L"Name"
#define AF_STR_NameA "Name"
#define AF_STR_NumberShort L"no."
#define AF_STR_FileChangedMarker L" *"
// Layout strings
#define AF_STR_WindowRestoreGroup "WindowRestore"
#define AF_STR_WindowRestoreSectionPosition "WindowPosition"
#define AF_STR_WindowRestoreSectionSize "WindowSize"
#define AF_STR_WindowRestoreSectionMaximized "WindowMaximized"
#define AF_STR_WindowRestoreWindowState "windowState"
#define AF_STR_WindowRestoreWindowStateOriginal "windowStateOriginal"
#define AF_STR_LayoutNoProjectLoaded L"NoProject"
#define AF_STR_LayoutNoProjectOutputLoaded L"NoProjectOutput"
#define AF_STR_LayoutDebug L"Debug"
#define AF_STR_LayoutDebugKernel L"DebugKernel"
#define AF_STR_LayoutProfileGPU L"ProfileGPU"
#define AF_STR_LayoutKernelAnalyze L"KernelAnalyze"
#define AF_STR_SettingsOrganization "AMD"
#define AF_STR_SettingsApplication "AMDTApplication"
#define AF_STR_LayoutFileName L"Layout"
#define AF_STR_LayoutTempFile L"tempSetting"
#define AF_STR_LayoutGroupStrFormat L"[%ls]\n"
#define AF_STR_LayoutSettingStrFormatHead L"windowState=\""
#define AF_STR_LayoutSettingConvertedHead "@ByteArray"
// Extension names:
#define AF_STR_projectSettingsDebugExtensionName L"GPU Debug"
// Initialize application Command:
#define AF_STR_LogMsg_AppInitBegin L"Application initialization started"
#define AF_STR_LogMsg_AppInitEnded L"Application initialization ended"
#define AF_STR_LogMsg_InitImageHandlers L"Initializing image file handlers"
#define AF_STR_LogMsg_FinishedInitImageHandlers L"Finished initializing image file handlers"
#define AF_STR_LogMsg_AppInitCmdSucceeded L"Application Initialization command succeeded"
#define AF_STR_LogMsg_AppInitCmdFinalize L"Finalizing application initialization command"
#define AF_STR_LogMsg_VerifyWinVersion L"Verifying Windows version compatibility"
#define AF_STR_LogMsg_VerifyMacVersion L"Verifying Mac OS X version compatibility"
#define AF_STR_LogMsg_LoadingOptionsFile L"Loading options file"
#define AF_STR_LogMsg_FinishedLoadingOptionsFile L"Finished loading options file"
#define AF_STR_ErrorMessageFailedToLoadTheSettings "CodeXL failed to load the Settings file."
#define AF_STR_ErrorMessageFailedToLoadTheSettingsUnicode L"CodeXL failed to load the Settings file."
#define AF_STR_LogMsg_EULANotAcceptedExiting L"EULA was not accepted. Exiting."
#define AF_STR_OperatingSystemNotSupported L"CodeXL does not support this Operating System Version (%d.%d.%d).\nPlease go to https://github.com/GPUOpen-Tools/CodeXL/issues for more information."
#define AF_STR_LogMsg_EventHandlerOverflow L"Event handler overflow was prevented."
#define AF_STR_LogMsg_FailedToLoadAComponent L"Failed to load a basic component."
#define AF_STR_ErrorMessageLowResolution L"Insufficient display resolution. CodeXL requires a display resolution of %dx%d or higher. CodeXL will now exit."
// Remote session errors.
#define AF_STR_REMOTE_GENERAL_ERROR_MSG L"Unable to connect to CodeXL Remote Agent.\nPlease verify that:\n1. CodeXL and CodeXL Remote Agent are not blocked by a firewall.\n2. The given IP address and ports are valid, and the remote machine is accessible from the local machine.\n3. CodeXL Remote Agent is running on the remote machine."
#define AF_STR_REMOTE_PLATFORM_INFO_UNAVAILABLE_TITLE "OpenCL Platform information is unavailable."
#define AF_STR_REMOTE_PLATFORM_INFO_UNAVAILABLE_BODY "OpenCL platform information is currently unavailable for remote GPU debugging sessions."
// CodeXL application flow:
#define AF_STR_PropertiesViewStartRunningComment L"To run an application, select a run mode and run the application"
#define AF_STR_PropertiesViewLoadProjectComment L"To open a CodeXL project go to File -> Open Project menu"
#define AF_STR_PropertiesProcessNotRunning L"Process Not Running"
#define AF_STR_PropertiesProjectNotLoaded L"Project Not Loaded"
#define AF_STR_PropertiesProcessRunning L"Process Running"
#define AF_STR_PropertiesExecutionMode L"Current Execution Mode:"
#define AF_STR_NoExeIsSelected "No executable selected.\nPlease select an executable in the Project Settings dialog."
#define AF_STR_NoProjectIsLoaded "No project loaded.\nClick OK to create a new project."
/// Remote host:
#define AF_STR_modeToolbarHostLocal "Local"
#define AF_STR_modeToolbarHostConfigureSettings "Configure Remote Host Settings..."
#define AF_STR_modeToolbarHostSelectionProjectChangeQuestion "Do you want to switch to project %1?"
#define AF_STR_modeToolbarHostsButtonObjectName "HostsButton"
// Global settings XML file:
#define AF_STR_globalSettingsFileName L"CodeXLSettings"
#define AF_STR_globalSettingsFileExtension L"xml"
#define AF_globalSettingsGeneralHeader "General"
#define AF_globalSettingsGeneralHeaderUnicode L"General"
#define AF_globalSettingsGeneralLogFilesNode "LogFileDirectory"
#define AF_globalSettingsGeneralLogLevelNode "LogSeverity"
#define AF_globalSettingsProxyEnabledNode "IsUsingHttpProxy"
#define AF_globalSettingsProxyAddressNode "HttpProxyAddress"
#define AF_globalSettingsRdsApiPortNode "RdsApiPort"
#define AF_globalSettingsRdsEventsPortNode "RdsEventsPort"
#define AF_globalSettingsSpyApiPortNode "SpyApiPort"
#define AF_globalSettingsSpyEventsPortNode "SpyEventsPort"
#define AF_globalSettingsHistoryList "HistoryList"
#define AF_globalSettingsWidgetHistoryList "WidgetHistoryList"
#define AF_globalSettingsWidgetHistoryListItem "WidgetHistoryListItem"
#define AF_globalSettingsWidgetNameAttribute L"widgetName"
#define AF_globalSettingsEulaVersionAcceptedNode "EulaVersionAccepted"
#define AF_globalSettingsFloatingPointPrecisionNode "FloatingPointPrecision"
#define AF_globalSettingsAlertMissingSourceNode "AlertMissingSource"
#define AF_globalSettingsDialogsNotToShow "DialogsNotToShow"
#define AF_globalSettingsDialogsName "DialogName"
#define AF_STR_globalSettingsMinBoundErrorMsg "Invalid value.\nSet to minimum valid value %1"
#define AF_STR_globalSettingsMaxBoundErrorMsg "Invalid value.\nSet to maximum valid value %1"
#define AF_STR_globalSettingsInaccessiblePathErrorMsg "Log path %1 is inaccessible. Check access permissions. Reverting to original path."
#define AF_STR_globalSettingsEmptyPathErrorMsg "Log path cannot be empty. Reverting to original path."
// Commands
#define AF_STR_FileSaveAs "Save File As"
// CodeXL files:
#define AF_STR_projectFileExtension L"cxl"
#define AF_STR_exeFileExtension L"exe"
#define AF_STR_profileFileExtension1 L"cxlcpdb"
#define AF_STR_profileFileExtension2 L"prd"
#define AF_STR_profileFileExtension3 L"caperf"
#define AF_STR_profileFileExtension4 L"csv"
#define AF_STR_profileFileExtension5 L"atp"
#define AF_STR_pngFileExtension L"png"
#define AF_STR_htmlFileExtension L"html"
#define AF_STR_projectFileDetails "CodeXL Project files (*.cxl)"
#define AF_STR_visualStudioProjectFileExtension L"cxlvs"
#define AF_STR_noProjectLoaded L"No project loaded"
#define AF_STR_ImageBuffersViewsCreatorID L"ImagesAndBuffers"
#define AF_STR_GenericMDIViewsCreatorID L"GenericInfra"
#define AF_STR_KernelAnalyzerViewsCreatorID L"KernelAnalyzer"
#define AF_STR_GPUProfileViewsCreatorID L"GPUProfile"
#define AF_STR_CodeXMLImageBuffersFilesExtension L"gdcxl"
#define AF_STR_clSourceFileExtension L"cl"
#define AF_STR_hsailSourceFileExtension L"hsail"
#define AF_STR_glslSourceFileExtension L"glsl"
#define AF_STR_AnalyzedSourceFileExtension "cl,vs,hs,ds,gs,ps,cs,hlsl,frag,vert,comp,geom,tese,tesc,glsl"
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
#define AF_STR_FILE_PATHEXTENSIONS_QREGEXP "[a-z]:([\\\\/][^\\\\/\"]+)+\\.(cl|hlsl|glsl|fs|frag|vs|vert|cs|comp|gs|geom|ps|hs|ds|tese|tesc)"
#define AF_STR_FILE_EXTENSIONS_QREGEXP "\\.cl|hlsl|glsl|fs|frag|vs|vert|cs|comp|gs|geom|ps|hs|ds|tese|tesc"
#else
#define AF_STR_FILE_PATHEXTENSIONS_QREGEXP "(/[^/\"]+)+\\.(cl|glsl|fs|frag|vs|vert|cs|comp|gs|geom|tese|tesc)"
#define AF_STR_FILE_EXTENSIONS_QREGEXP "\\.cl|hlsl|glsl|fs|frag|vs|vert|cs|comp|gs|geom|tese|tesc"
#endif
#define AF_STR_BUILDING_STAGE_QREGEXP "vertex|tessellation evaluation|tessellation control|geometry|fragment|compute"
#define AF_STR_CL_LINENUM_QREGEXP "[lL]ine [0-9]+:"
#define AF_STR_HLSL_LINENUM_QREGEXP "(\\([\\d]+,)"
#define AF_STR_GLSL_LINENUM_QREGEXP ":[\\d]+:"
#define AF_STR_BUILD_STARTED "build started"
#define AF_STR_OpenGL_ERROR "ERROR:"
#define AF_STR_OpenGL_WARNING "WARNING:"
#define AF_STR_OpenGL_Shader_Failed "shader failed to compile"
#define AF_STR_BUILDING_STAGE "building stage: "
#define AF_STR_FILENAME_SEPARATOR ", filename: "
#define AF_STR_SHADER "shader"
#define AF_STR_STAGE "stage:"
#define AF_STR_COMPILING "Compiling"
#define AF_STR_GpuProfileSessionFileExtension L"gpsession"
#define AF_STR_GpuPerformanceCountersSessionFileExtension L"csv"
#define AF_STR_GpuProfileTraceFileExtension L"atp"
#define AF_STR_TeapotSampleProjectName L"CodeXL Teapot"
#define AF_STR_TeapotSampleVSProjectName L"CXLTeaPot"
#define AF_STR_ProfileDirExtension L"_ProfilerOutput"
#define AF_STR_KernelOutputExtension L"_KernelOutput"
// Toolbars:
#define AF_STR_ImagesAndBuffersToolbar L"Images and Buffers"
#define AF_STR_toolbarPostfix " Toolbar"
#define AF_STR_viewsToolbarPostfix " Views Toolbar"
#define AF_STR_modeToolbar "Active Mode"
#define AF_STR_actionsToolbar "Execution Toolbar"
#define AF_STR_actionsToolbarUnicode L"Execution Toolbar"
#define AF_STR_modeToobarButtonBaseName "ModeButton"
#define AF_STR_modeSwitchToTooltipPart1 "Switch to "
#define AF_STR_modeSwitchToTooltipPart2 " Mode"
#define AF_STR_playButtonContinue L"Continue"
#define AF_STR_playButtonExeNameOnly L" (%ls)"
#define AF_STR_playButtonStartPrefix L"Start CodeXL "
#define AF_STR_playButtonStartGeneric L"Start CodeXL"
// Menu items:
#define AF_STR_CloseAllDocuments "C&lose All Documents"
// Startup page:
#define AF_STR_StartupPageHTMLFileName L"CodeXL_startup.htm"
// Select Windows Store app dialog:
#define AF_STR_winStoreAppWindowTitle "Select Windows Store app"
#define AF_STR_winStoreAppUserModelIDLabel "User Model ID:"
// Attach to Process dialog:
#define AF_STR_winAttachToProcessTitle "Attach to Process"
// New project dialog:
#define AF_STR_newProjectWindowEditTitle "CodeXL Project Settings"
#define AF_STR_newProjectWindowNewTitle "Create a new CodeXL Project"
#define AF_STR_newProjectGeneralTabName "General"
#define AF_STR_newProjecProjectName "CodeXL Project Name:"
#define AF_STR_newProjectProjectExePath "Executable Path:"
#define AF_STR_newProjectProjectBrowseForExePathTooltipApp "Click to browse for an executable path"
#define AF_STR_newProjectProjectEXEEditLineTooltipApp "Type the full path of the selected Desktop Application, or click the browse button"
#define AF_STR_newProjectWindowsStoreApp "Windows Store App"
#define AF_STR_newProjectWindowsStoreAppTooltip "Click for a selection of a Windows Store App"
#define AF_STR_newProjectDesktopApplication "Desktop Application"
#define AF_STR_newProjectDesktopApplicationTooltip "Click for a selection of a Desktop Application"
#define AF_STR_newProjectWindowsStoreAppUserModelID "User Model ID:"
#define AF_STR_newProject_remoteHost "Remote Host"
#define AF_STR_newProject_remoteHostTooltip "Click to run the selected application on a Remote Host"
#define AF_STR_newProject_localHost "Local Host"
#define AF_STR_newProject_localHostTooltip "Click to run the selected application on the Local Host"
#define AF_STR_newProject_targetHost "Target Host:"
#define AF_STR_newProject_remoteHostAddress "Remote Host Address:"
#define AF_STR_newProject_remoteHostPort "Port:"
#define AF_STR_newProject_remoteHostDefaultPort "27015"
#define AF_STR_newProject_remoteHostTestConnection "Test Connection"
#define AF_STR_newProject_remoteHostTestConnectionTooltip "Click to test the connection to the remote host with the specified port and address"
#define AF_STR_newProject_remoteHostTestConnectionFailedMessage "Failed to connect to remote host %1 with port number %2.\n Please make sure that:\n1. CodeXL Remote Agent is running on the target machine.\n2. There is network access from the client machine to the remote machine.\n3. CodeXL is not blocked by a firewall on the client machine.\n4. CodeXL Remote Agent is not blocked by a firewall on the remote machine."
#define AF_STR_newProject_remoteHostTestConnectionSucceededMessage "Connection was established successfuly."
#define AF_STR_newProject_remoteHostInvalidAddress L"Invalid remote host address"
#define AF_STR_newProject_remoteHostInvalidPort L"Invalid port number for remote host"
#define AF_STR_newProjectWorkingFolder "Working Directory:"
#define AF_STR_newProjectWorkingFolderTooltip "Click to select the working folder for the executed application"
#define AF_STR_newProjectProgramArguments "Command Line Arguments:"
#define AF_STR_newProjectProgramArgumentsTooltip "Add the application command line arguments, separated by a ';'"
#define AF_STR_newProjectEnvironmentVariables "Environment Variables:"
#define AF_STR_newProjectBrowse "Browse"
#define AF_STR_newProjectEditEnvVars L"..."
#define AF_STR_newProjectWorkingFolderSelectionTitle "Select the project working folder"
#define AF_STR_newProjecExecutableFileSelectionTitle "Select an executable for the project"
#define AF_STR_newProjecWindowsStoreAppSelectionTitle L"Select Windows Store app"
#define AF_STR_newProjectRestoreDefaultSettings "&Restore Default Settings"
#define AF_STR_newProjectEnterName "Enter Project Name..."
#define AF_STR_newProjectDefaultProjectName "Project%1"
#define AF_STR_newProjectInvalidName L"CodeXL project name cannot be empty. Please enter a valid project name."
#define AF_STR_newProjectProjectNameChanged "The project contains saved data of type: %1.\nChanging the project name will create a new project that will not contain the data stored in this project.\nDo you want to change the project name?"
#define AF_STR_newProjectInvalidNameInvalidChars L"The project name contains invalid characters."
#define AF_STR_newProjectExeDoesNotExistOrInvalid L"Executable path does not exist or executable is invalid"
#define AF_STR_newProjectWindowsStoreAppInvalid L"Invalid Windows Store app User Model ID"
#define AF_STR_newProjectWorkingFolderDoesNotExist L"Working directory path does not exist"
#define AF_STR_loadProjectError "Could not load project file"
#define AF_STR_openFileDialogCaption "Open a file"
#define AF_STR_projectSettingsSourceFiles "Source Files"
#define AF_STR_projectSettingsTargetApplication "Target Application"
#define AF_STR_projectSettingsTargetApplicationVS "Target Application (Set by the Debugging section of the Visual Studio Project Properties)"
#define AF_STR_projectSettingsSourceFilesDirectory "Source Files Directories:"
#define AF_STR_projectSettingsSourceFilesResolutionDirectory "Source Files Resolution<br> Root Directory:"
#define AF_STR_projectSettingsSelectKernelSourceFilesFolderTitle "Select source code root resolution directory:"
#define AF_Str_ProjectSettingsSoureFilesDirectoriesLabel "CodeXL will use these paths to look for source code files of the debugged/profiled application (C, C++, OpenCL kernel files, etc.)"
#define AF_STR_newProjectEmptyProfileName L"The profile name cannot be empty."
#define AF_STR_newProjectInvalidProfileName L"The profile name must not contain any of the following characters: "
#define AF_STR_newProjectExistingQuestion "A project named '%1' already exists. \nDo you want to overwrite the existing project?"
#define AF_STR_newProjectEnvironmentVariablesDelimiter L"\n"
#define AF_STR_newProjectEnvironmentVariablesDelimitersVS L"\n;"
#define AF_STR_newProjectEditEnvVarsTooltip "Click to define the executed application environment variables"
#define AF_STR_projectSettingsSourceFilesDirectoryTooltip "Click to select a list of source files directories for the executed application.\nThe source files directories will be used to detect the sources and calls stacks when debugging / profiling the application."
// Global settings dialog:
#define AF_STR_globalSettingsWindowTitle "CodeXL Options"
#define AF_STR_globalSettingsGeneralTabName "&General"
#define AF_STR_globalSettingsRestoreDefaultSettings "&Restore Default Settings"
#define AF_STR_globalRemoteSettingsPortsHeadline "Remote Debugging Ports:"
// Global settings page:
#define AF_STR_globalSettingsLoggingGroupTitle "Logging"
#define AF_STR_globalSettingsDebugLogLevelLabel "Debug log level: "
#define AF_STR_globalSettingsLogFilesFolderLabel "Log Files and Images Directory"
#define AF_STR_globalSettingsSelectLogFilesFolderTitle "Select the log files and images directory"
#define AF_STR_globalSettingsConnectionGroupTitle "Connection"
#define AF_STR_globalSettingsUsingProxyCheckBox "I am using an HTTP proxy"
#define AF_STR_globalSettingsProxyAddressLabel "Server: "
#define AF_STR_globalSettingsProxyPortLabel "Port: "
#define AF_STR_globalSettingsFloatingPointPrecision "Floating-point precision (maximum number of significant digits):"
#define AF_STR_globalSettingsAdvancedGroupTitle "Advanced"
#define AF_STR_globalSettingsAlertMissingSourceFiles "Alert when a source file is missing"
#define AF_STR_sourceCodeQuestionInclude "Would you like to include\n%1\nin the list of source search directories?\n"
// "File" menu:
#define AF_STR_FileMenuString L"&File"
#define AF_STR_newProject L"&New Project...\t" AF_STR_keyboardShortcutNewMenu
#define AF_STR_openProject L"&Open Project...\t" AF_STR_keyboardShortcutOpenProjectMenu
#define AF_STR_closeProject L"Close &Project"
#define AF_STR_openFile L"Open &File...\t" AF_STR_keyboardShortcutOpenFileMenu
#define AF_STR_welcomePage L"&Welcome Page"
#define AF_STR_welcomePageStatusbarString L"Open CodeXL welcome page"
#define AF_STR_RecentProject L"&Recent Projects"
#define AF_STR_saveProject L"&Save Project\t" AF_STR_keyboardShortcutSaveProjectMenu
#define AF_STR_saveProjectAs L"Save Project &As..."
#define AF_STR_saveFile L"Save Fi&le\t" AF_STR_keyboardShortcutSaveMenu
#define AF_STR_saveFileAs L"Save F&ile As..."
#define AF_STR_DebugSettings L"&Debug Settings...\t" AF_STR_keyboardShortcutDebugMenu
#define AF_STR_exit L"E&xit"
#define AF_STR_DebugMenuString L"&Debug"
#define AF_STR_ProjectSettings L"Project Se&ttings...\t" AF_STR_ProjectSettingsKeyBoardShortcut
#define AF_STR_ProjectSettingsKeyBoardShortcut L"Ctrl+P"
// Status strings:
#define AF_STR_RecentlyUsedProjectStatusbarString L"Recent projects list"
#define AF_STR_newProjectStatusbarString L"Create a new project"
#define AF_STR_openProjectStatusbarString L"Open an existing project file"
#define AF_STR_closeProjectStatusbarString L"Close the current project"
#define AF_STR_openFileStatusbarString L"Open a source code file"
#define AF_STR_saveFileStatusbarString L"Save the current file"
#define AF_STR_saveFileAsStatusbarString L"Save the current file to a new location"
#define AF_STR_saveProjectStatusbarString L"Save the current project"
#define AF_STR_saveProjectAsStatusbarString L"Save the current project to another file"
#define AF_STR_exitStatusbarString L"Exit the CodeXL application"
#define AF_STR_ProgressSettingsStatusbarString L"Specify the settings for the current project"
// "Edit" menu:
#define AF_STR_EditMenuString L"&Edit"
#define AF_STR_Copy L"&Copy\t" AF_STR_keyboardShortcutCopyMenu
#define AF_STR_CopyA "&Copy\t" AF_STR_keyboardShortcutCopyMenuA
#define AF_STR_Cut L"Cu&t\t" AF_STR_keyboardShortcutCutMenu
#define AF_STR_Paste L"&Paste\t" AF_STR_keyboardShortcutPasteMenu
#define AF_STR_Find L"&Find\t" AF_STR_keyboardShortcutFindMenu
#define AF_STR_FindA "&Find\t" AF_STR_keyboardShortcutFindMenuA
#define AF_STR_FindNext L"Find &Next\t" AF_STR_keyboardShortcutFindNextMenu
#define AF_STR_FindPrev L"Find Pre&vious\t" AF_STR_keyboardShortcutFindPrevMenu
#define AF_STR_FindNextA "Find &Next\t" AF_STR_keyboardShortcutFindNextMenuA
#define AF_STR_GoTo L"&Go to...\t" AF_STR_keyboardShortcutGoToMenu
#define AF_STR_GoToA "&Go to...\t" AF_STR_keyboardShortcutGoToMenuA
#define AF_STR_MarkerNext L"Go to Next Marker\t" AF_STR_keyboardShortcutNextMarkerMenu
#define AF_STR_MarkerPrevious L"Go to Previous Marker\t" AF_STR_keyboardShortcutPrevMarkerMenu
#define AF_STR_CopyStatusbarString L"Copies the selection to the Clipboard"
#define AF_STR_PasteStatusbarString L"Pastes from Clipboard"
#define AF_STR_CutStatusbarString L"Cuts the selection to the Clipboard"
#define AF_STR_FindStatusbarString L"Finds the specified text"
#define AF_STR_FindNextStatusbarString L"Finds next instance of specified text"
#define AF_STR_FindPrevStatusbarString L"Finds previous instance of specified text"
#define AF_STR_MarkerNextStatusbarString L"Next: Scroll the Calls History View to the next string marker function call"
#define AF_STR_MarkerPreviousStatusbarString L"Previous: Scroll the Calls History View to the previous string marker function call"
#define AF_STR_SelectAllStatusbarString L"Select all items in the view"
#define AF_STR_ShowLineNumbersStatusbarString L"Show line numbers in source code view"
#define AF_STR_GoToStatusbarString L"Go to line"
// Main menu:
#define AF_STR_ProfileMenuString L"&Profile"
#define AF_STR_AnalyzeMenuString L"&Analyze"
#define AF_STR_BreakPointsMenuString L"&Breakpoints"
// "View" menu:
#define AF_STR_ViewMenuString L"&View"
#define AF_STR_ViewMenuStringA "&View"
#define AF_STR_ResetGUILayouts L"Reset &GUI Layouts"
#define AF_STR_ResetGUILayoutsStatusbarString L"Reset the GUI Layouts back to factory settings"
#define AF_STR_ToolbarMenuStringA "&Toolbars"
#define AF_STR_ViewsToolbar "Views"
#define AF_STR_WindowsMenuString L"&Window"
// "Help" menu:
#define AF_STR_HelpMenuString L"&Help"
#define AF_STR_HelpUserGuide L"View &Help"
#define AF_STR_HelpQuickStart L"View &Quick Start Guide"
#define AF_STR_HelpDevToolsSupportForum L"&CodeXL Support and Issues Page"
#define AF_STR_HelpUpdates L"Check for &Updates"
#define AF_STR_LoadTeapotSample L"Load the Teapot &Sample"
#define AF_STR_HelpAbout L"&About CodeXL"
#define AF_STR_HelpUserGuideStatusbarString L"Display CodeXL User Guide"
#define AF_STR_HelpQuickStartStatusbarString L"Display the CodeXL Quick Start Guide"
#define AF_STR_HelpDevToolsSupportForumStatusbarString L"Go to the CodeXL Support and Issues Page"
#define AF_STR_HelpUpdatesStatusbarString L"Check for new CodeXL versions"
#define AF_STR_LoadTeapotSampleStatusbarString L"Load the Teapot sample"
#define AF_STR_HelpAboutStatusbarString L"Display the program information and copyright"
#define AF_STR_HelpDevToolsSupportForumURL L"https://github.com/GPUOpen-Tools/CodeXL/issues"
#define AF_STR_HelpCodeXLWebPage L"http://gpuopen.com/compute-product/codexl/"
#define AF_STR_HelpShortcut L"F1"
// "Tools" menu:
#define AF_STR_ToolsMenuString L"&Tools"
#define AF_STR_ToolsSystemInfo L"&System Information"
#define AF_STR_ToolsOptions L"&Options..."
#define AF_STR_ToolsSystemInfoStatusbarString L"Collects computer configuration data, OpenCL and OpenGL implementation details"
#define AF_STR_ToolsOptionsStatusbarString L"Enables you to change the settings"
#define AF_STR_DebugLogLevelWarning L"CodeXL debug log level is set to '%ls' level.\nPlease set it back to 'Info' level in the Tools Options dialog\nafter finishing your current task.\n\n Do you wish to continue?"
#define AF_STR_DebugLogLevelDebugWarningTitle "Warning - Log level"
// Keyboard shortcuts:
#define AF_STR_keyboardShortcutNewMenu L"Ctrl+N"
#define AF_STR_keyboardShortcutOpenFileMenu L"Ctrl+O"
#define AF_STR_keyboardShortcutOpenProjectMenu L"Ctrl+Shift+O"
#define AF_STR_keyboardShortcutStartupDialogMenu L"Ctrl+Alt+O"
#define AF_STR_keyboardShortcutStartupDialogString L"Ctrl+Alt+O"
#define AF_STR_keyboardShortcutSaveProjectMenu L"Ctrl+Shift+S"
#define AF_STR_keyboardShortcutSaveMenu L"Ctrl+S"
#define AF_STR_keyboardShortcutExitMenu L"Alt+F4"
#define AF_STR_keyboardShortcutDebugMenu L"Ctrl+D"
#define AF_STR_keyboardShortcutCopyMenu L"Ctrl+C"
#define AF_STR_keyboardShortcutCopyMenuA "Ctrl+C"
#define AF_STR_keyboardShortcutCutMenu L"Ctrl+X"
#define AF_STR_keyboardShortcutPasteMenu L"Ctrl+V"
#define AF_STR_keyboardShortcutCopyString L"Ctrl + C"
#define AF_STR_keyboardShortcutFindMenu L"Ctrl+F"
#define AF_STR_keyboardShortcutFindMenuA "Ctrl+F"
#define AF_STR_keyboardShortcutFindString L"Ctrl + F"
#define AF_STR_keyboardShortcutFindNextMenu L"F3"
#define AF_STR_keyboardShortcutFindNextMenuA "F3"
#define AF_STR_keyboardShortcutFindNextString L"F3"
#define AF_STR_keyboardShortcutFindPrevMenu L"Shift+F3"
#define AF_STR_keyboardShortcutNextMarkerMenu L"Ctrl+Shift+N"
#define AF_STR_keyboardShortcutNextMarkerString L"Command + Shift + N"
#define AF_STR_keyboardShortcutPrevMarkerMenu L"Ctrl+Shift+P"
#define AF_STR_keyboardShortcutPrevMarkerString L"Command + Shift + P"
#define AF_STR_keyboardShortcutSelectAllMenu L"Ctrl+A"
#define AF_STR_keyboardShortcutSelectAllMenuA "Ctrl+A"
#define AF_STR_keyboardShortcutSelectAllString L"Ctrl+A"
#define AF_STR_keyboardShortcutDeleteMenuA "Del"
#define AF_STR_keyboardShortcutDeleteMenu L"Del"
#define AF_STR_keyboardShortcutDeleteString L"Del"
#define AF_STR_keyboardShortcutGoToMenu L"Ctrl+G"
#define AF_STR_keyboardShortcutGoToMenuA "Ctrl+G"
#define AF_STR_keyboardShortcutGoToString L"Ctrl + G"
// Edit environment variables:
#define AF_STR_EditVariablesDialogTitle "Edit Environment Variables"
#define AF_STR_EditVariablesDialogDescription "Please add operating system environment variables for the debugged session"
#define AF_STR_EditVariablesDialogVariableNameColumnTitle "Environment Variable Name"
#define AF_STR_EditVariablesDialogAddEnvironmentVariable "Add Environment Variable..."
#define AF_STR_EditVariablesDialogErrorMsgTitle "Incorrect Variable Name"
#define AF_STR_EditVariablesDialogErrorMsg "Variable name in row number %d is not valid"
// Project xml file
#define AF_STR_loadProjectFileVersionNode "FileVersion"
#define AF_STR_loadProjectRootNodeBackwardsCompatibility "UnifiedTool"
#define AF_STR_loadProjectProjectNameNode "ProjectName"
#define AF_STR_loadProjectgApplicationPathNode "ApplicationPath"
#define AF_STR_loadProjectLogFilesFolderNode "LogFilesFolder"
#define AF_STR_loadProjectWorkDirNode "WorkingDirectory"
#define AF_STR_loadProjectAppArgsNode "ApplicationArguments"
#define AF_STR_loadProjectIsStoreApp "StoreApp"
#define AF_STR_loadProjectLastActiveModeNode "LastActiveMode"
#define AF_STR_loadProjectLastSessionTypeNode "LastSessionType"
#define AF_STR_loadProjectAppEnvVarsNode "ApplicationEnvironmentVariables"
#define AF_STR_loadProjectAppEnvVarsVarNode "EnvironmentVariable"
#define AF_STR_loadProjectAppEnvVarsNameNode "VariableName"
#define AF_STR_loadProjectAppEnvVarsValueNode "VariableValue"
#define AF_STR_loadProjectProductExtensionsNode "ProductExtensions"
#define AF_STR_loadProjectSourceFilesDirectoryNode "SourceFilesDirectory"
#define AF_STR_loadProjectSourceCodeRootDirectoryNode "SourceCodeRootDirectory"
#define AF_STR_loadProjectProfileNameNode "ProfileName"
#define AF_STR_loadProjectIsRemoteSession "IsRemoteSession"
#define AF_STR_loadProjectRecentlyUsedRemoteIPAddresses "RecentlyUsedRemoteIPAddresses"
#define AF_STR_loadProjectRemoteDaemonHostName "RemoteDaemonHostName"
#define AF_STR_loadProjectRemoteDaemonPortNumber "RemoteDaemonPortNumber"
#define AF_STR_loadProjectArchitecture32Bit L"32-bit GPU Build"
#define AF_STR_loadProjectArchitecture64Bit L"64-bit GPU Build"
// "System Information" dialog:
#define AF_STR_SystemInformationTitle "System Information"
#define AF_STR_InformationSystem "S&ystem"
#define AF_STR_InformationDisplay "&Display"
#define AF_STR_SystemInformationTitleSaveButton "&Save"
#define AF_STR_InformationOpenGLRenderer "Open&GL Renderer"
#define AF_STR_InformationPixelFormats "OpenGL Pi&xel Formats"
#define AF_STR_InformationOpenGLExtensions "OpenGL &Extensions"
#define AF_STR_InformationOpenCLPlatforms "OpenCL &Platforms"
#define AF_STR_InformationOpenCLDevices "OpenCL De&vices"
#define AF_STR_ErrorMessageSaveSystemInformationFailed "Could not save the system information."
#define AF_STR_DescriptionSystem "<b>Description:</b><br>System view collects and displays information about the configuration of your system."
#define AF_STR_DescriptionDisplay "<b>Description:</b><br>Display view collects and displays information about the configuration of your display system."
#define AF_STR_DescriptionGraphicCard "<b>Description:</b><br>Graphic card view collects and displays information about the configuration of your graphic accelerator system."
#define AF_STR_DescriptionPixelFormats "<b>Description:</b><br>Pixel format view collects and displays information about the pixel formats supported by your system."
#define AF_STR_DescriptionOpenGLExtensions "<b>Description:</b><br>OpenGL extension view collects and displays information about the OpenGL extensions supported by your system."
#define AF_STR_DescriptionOpenCLPlatforms "<b>Description:</b><br>OpenCL platforms view collects and displays information about the OpenCL platforms available on your system."
#define AF_STR_DescriptionOpenCLDevices "<b>Description:</b><br>OpenCL devices view collects and displays information about the OpenCL devices available on all OpenCL platforms installed on your system.<br>This information is collected using the OpenCL modules in your system path. If the AMD APP SDK is installed it may provide more advanced device capabilities."
#define AF_STR_NoOpenCLPlatforms "No OpenCL platforms are installed on the local computer"
#define AF_STR_NoOpenCLDevices "No OpenCL devices are available on the local computer's OpenCL platforms"
#define AF_STR_FailToCollectOpenCLDevicesInfo "Failed to collect OpenCL devices information"
#define AF_STR_CollectingOpenCLDevicesInfo "Collecting data..."
#define AF_STR_OpenCLDevicesTableMinColumnWidth 125
#define AF_STR_32BitHeadingPrefix L"32-bit"
#define AF_STR_64BitHeadingPrefix L"64-bit"
#define AF_STR_32HeadingStr AF_STR_LeftParenthesis AF_STR_32BitHeadingPrefix AF_STR_Comma AF_STR_Space
#define AF_STR_64HeadingStr AF_STR_LeftParenthesis AF_STR_64BitHeadingPrefix AF_STR_Comma AF_STR_Space
#define AF_STR_System_Snapshot_Header L"This file contains a system information snapshot"
#define AF_STR_AMD_DEVELOPER_WEBSITE_URL L"http://gpuopen.com/"
#define AF_STR_FAILED_TO_COLLECT_GPU_DETAILS_AND_EXCEPTION_DESC L"Failed to collect GPU details. Exception raised: %s"
#define AF_STR_FAILED_TO_COLLECT_GPU_DETAILS L"Failed to collect GPU details. Exception raised"
#define AF_STR_FAILED_TO_COLLECT_SYSTEM_INFORMATION L"Failed to collect system information. Exception raised"
// System information command:
#define AF_STR_SystemInformationCommandComputerName L"Computer Name"
#define AF_STR_SystemInformationCommandDomainName L"Domain Name"
#define AF_STR_SystemInformationCommandOSVersionName L"Operating System Version (name)"
#define AF_STR_SystemInformationCommandOSVersionNumber L"Operating System Version (number)"
#define AF_STR_SystemInformationCommandNumberOfCPUCores L"Number of CPU Cores"
#define AF_STR_SystemInformationCommandSystemType L"System Type"
#define AF_STR_SystemInformationCommandCPUType L"CPU Type"
#define AF_STR_SystemInformationCommandTotalPhysicalMemory L"Total Physical Memory"
#define AF_STR_SystemInformationCommandAvailablePhysicalMemory L"Available Physical Memory"
#define AF_STR_SystemInformationCommandTotalVirtualMemory L"Total Virtual Memory"
#define AF_STR_SystemInformationCommandAvailableVirtualMemory L"Available Virtual Memory"
#define AF_STR_SystemInformationCommandTotalPageFiles L"Total Page Files"
#define AF_STR_SystemInformationCommandAvailablePageFiles L"Available Page Files"
#define AF_STR_SystemInformationCommandDriverVersion L"AMD Radeon Software version"
#define AF_STR_SystemInformationCommandComputerPath L"Computer Path"
#define AF_STR_SystemInformationCommandNumberOfMonitors L"Number of Monitors"
#define AF_STR_SystemInformationCommandPrimaryMonitorName L"Primary Monitor Name"
#define AF_STR_SystemInformationCommandScreenResolution L"Screen Resolution"
#define AF_STR_SystemInformationCommandRendererVendor L"Renderer Vendor"
#define AF_STR_SystemInformationCommandRendererName L"Renderer Name"
#define AF_STR_SystemInformationCommandRendererVersion L"Renderer Version"
#define AF_STR_SystemInformationCommandShadingLanguageVersion L"Shading Language Version"
#define AF_STR_SystemInformationCommandRendererType L"Renderer Type"
#define AF_STR_SystemInformationCommandShadingLanguageUpdateError L"rcSLan"
#define AF_STR_SystemInformationCommandInstallableClient L"Installable client"
#define AF_STR_SystemInformationCommandHardwareRenderer L"Hardware renderer"
#define AF_STR_SystemInformationCommandMiniClient L"Mini client"
#define AF_STR_SystemInformationCommandGenericOpenGLSoftwareRenderer L"Generic OpenGL software renderer"
#define AF_STR_SystemInformationCommandSoftwareRenderer L"Software renderer"
#define AF_STR_SystemInformationCommandDBuff L"D buff"
#define AF_STR_SystemInformationCommandZBuff L"Z buff"
#define AF_STR_SystemInformationCommandStBuff L"St buff"
#define AF_STR_SystemInformationCommandColorBits L"Color bits"
#define AF_STR_SystemInformationCommandRBits L"R bits"
#define AF_STR_SystemInformationCommandGBits L"G bits"
#define AF_STR_SystemInformationCommandBBits L"B bits"
#define AF_STR_SystemInformationCommandABits L"A bits"
#define AF_STR_SystemInformationCommandAccBuff L"Acc buff"
#define AF_STR_SystemInformationCommandGDI L"GDI"
#define AF_STR_SystemInformationCommandStereo L"Stereo"
#define AF_STR_SystemInformationCommandHardware L"Hardware"
#define AF_STR_SystemInformationCommandPixelType L"Pixel type"
#define AF_STR_SystemInformationCommandColorIndex L"Color Index"
#define AF_STR_SystemInformationCommandExtensionName L"Extension name"
#define AF_STR_SystemInformationCommandExtensions L"Extensions"
#define AF_STR_SystemInformationCommandParameter L"Parameter"
#define AF_STR_SystemInformationCommandVendor L"Vendor"
#define AF_STR_SystemInformationCommandVersion L"Version"
#define AF_STR_SystemInformationCommandProfile L"Profile"
#define AF_STR_SystemInformationCommandPlatformID L"Platform ID"
#define AF_STR_SystemInformationCommandDeviceType L"Device Type"
#define AF_STR_SystemInformationCommandDeviceName L"Device Name"
#define AF_STR_SystemInformationCommandCommandQueueProperties L"Command Queue Properties"
#define AF_STR_SystemInformationCommandMaxGlobalVariableSize L"Max Global Variable Size"
#define AF_STR_SystemInformationCommandGlobalVariablePreferredTotalSize L"Global Variable Preferred Total Size"
#define AF_STR_SystemInformationCommandQueueOnDeviceProperties L"Queue On Device Properties"
#define AF_STR_SystemInformationCommandQueueOnDevicePreferredSize L"Queue On-Device Preferred Size"
#define AF_STR_SystemInformationCommandQueueOnDeviceMaxSize L"Queue On-Device Max Size"
#define AF_STR_SystemInformationCommandMaxOnDeviceQueues L"Max On-Device Queues"
#define AF_STR_SystemInformationCommandMaxOnDeviceEvents L"Max On-Device Events"
#define AF_STR_SystemInformationCommandSVMCapabilities L"Shared Virtual Memory Capabilities"
#define AF_STR_SystemInformationCommandMaxPipeArgs L"Max Pipe Args"
#define AF_STR_SystemInformationCommandPipeMaxActiveReservations L"Pipe Max Active Reservations"
#define AF_STR_SystemInformationCommandPipeMaxPacketSize L"Pipe Max Packet Size"
#define AF_STR_SystemInformationCommandPreferredPlatformAtomicAlignment L"Preferred Platform Atomic Alignment"
#define AF_STR_SystemInformationCommandPreferredGlobalAtomicAlignment L"Preferred Global Atomic Alignment"
#define AF_STR_SystemInformationCommandPreferredLocalAtomicAlignment L"Preferred Local Atomic Alignment"
#define AF_STR_SystemInformationCommandAddressBits L"Address Bits"
#define AF_STR_SystemInformationCommandIsAvailable L"Is Available"
#define AF_STR_SystemInformationCommandIsCompilerAvailable L"Is Compiler Available"
#define AF_STR_SystemInformationCommandSingleFPConfig L"Single FP Config"
#define AF_STR_SystemInformationCommandDoubleFPConfig L"Double FP Config"
#define AF_STR_SystemInformationCommandHalfFPConfig L"Half FP Config"
#define AF_STR_SystemInformationCommandIsLittleEndian L"Is Little Endian"
#define AF_STR_SystemInformationCommandErrorCorrectionSupport L"Error Correction Support"
#define AF_STR_SystemInformationCommandExecutionCapabilities L"Execution Capabilities"
#define AF_STR_SystemInformationCommandGlobalMemoryCacheSize L"Global Memory Cache Size"
#define AF_STR_SystemInformationCommandMemoryCacheType L"Memory Cache Type"
#define AF_STR_SystemInformationCommandGlobalMemoryCacheLineSize L"Global Memory Cache Line Size"
#define AF_STR_SystemInformationCommandGlobalMemorySize L"Global Memory Size"
#define AF_STR_SystemInformationCommandAreImageSupported L"Are Images Supported"
#define AF_STR_SystemInformationCommandHostUnifiedMemory L"Host Unified Memory"
#define AF_STR_SystemInformationCommandMaxImage2DDimensions L"Max Image 2D Dimensions"
#define AF_STR_SystemInformationCommandMaxImage3DDimensions L"Max Image 3D Dimensions"
#define AF_STR_SystemInformationCommandLocalMemorySize L"Local Memory Size"
#define AF_STR_SystemInformationCommandLocalMemoryType L"Local Memory Type"
#define AF_STR_SystemInformationCommandMaxClockFrequency L"Max Clock Frequency"
#define AF_STR_SystemInformationCommandMaxComputeUnits L"Max Compute Units"
#define AF_STR_SystemInformationCommandMaxConstantArguments L"Max Constant Arguments"
#define AF_STR_SystemInformationCommandMaxConstantBufferSize L"Max Constant Buffer Size"
#define AF_STR_SystemInformationCommandMaxMemoryAllocationSize L"Max Memory Allocation Size"
#define AF_STR_SystemInformationCommandMaxParameterSize L"Max Parameter Size"
#define AF_STR_SystemInformationCommandReadImageArguments L"Read Image Arguments"
#define AF_STR_SystemInformationCommandMaxSamplers L"Max Samplers"
#define AF_STR_SystemInformationCommandMaxWorkgroupSize L"Max Workgroup Size"
#define AF_STR_SystemInformationCommandMaxWorkItemDimensions L"Max Work Item Dimensions"
#define AF_STR_SystemInformationCommandMaxWorkItemSizes L"Max Work Item Sizes"
#define AF_STR_SystemInformationCommandMaxWriteImageArguments L"Max Write Image Arguments"
#define AF_STR_SystemInformationCommandMaxReadWriteImageArguments L"Max Read-Write Image Arguments"
#define AF_STR_SystemInformationCommandMemoryBaseAddressAlignment L"Memory Base Address Alignment"
#define AF_STR_SystemInformationCommandMinimalDataTypeAlignmentSize L"Minimal Data Type Alignment Size"
#define AF_STR_SystemInformationCommandOpenCLCVersion L"OpenCL C Version"
#define AF_STR_SystemInformationCommandNativeCharVectorWidth L"Native Char Vector Width"
#define AF_STR_SystemInformationCommandNativeShortVectorWidth L"Native Short Vector Width"
#define AF_STR_SystemInformationCommandNativeIntVectorWidth L"Native Int Vector Width"
#define AF_STR_SystemInformationCommandNativeLongVectorWidth L"Native Long Vector Width"
#define AF_STR_SystemInformationCommandNativeFloatVectorWidth L"Native Float Vector Width"
#define AF_STR_SystemInformationCommandNativeDoubleVectorWidth L"Native Double Vector Width"
#define AF_STR_SystemInformationCommandNativeHalfVectorWidth L"Native Half Vector Width"
#define AF_STR_SystemInformationCommandPreferredCharVectorWidth L"Preferred Char Vector Width"
#define AF_STR_SystemInformationCommandPreferredShortVectorWidth L"Preferred Short Vector Width"
#define AF_STR_SystemInformationCommandPreferredIntVectorWidth L"Preferred Int Vector Width"
#define AF_STR_SystemInformationCommandPreferredLongVectorWidth L"Preferred Long Vector Width"
#define AF_STR_SystemInformationCommandPreferredFloatVectorWidth L"Preferred Float Vector Width"
#define AF_STR_SystemInformationCommandPreferredDoubleVectorWidth L"Preferred Double Vector Width"
#define AF_STR_SystemInformationCommandPreferredHalfVectorWidth L"Preferred Half Vector Width"
#define AF_STR_SystemInformationCommandProfilingTimerResolution L"Profiling Timer Resolution"
#define AF_STR_SystemInformationCommandVendorID L"Vendor ID"
#define AF_STR_SystemInformationCommandCpuFamily L"CPU Family"
#define AF_STR_SystemInformationCommandPipePrefix L"AMDT_SI_PIPE_NAME"
#define AF_STR_SystemInformationCommandHelper32Name L"CXLSystemInformationHelper"
#define AF_STR_SystemInformationCommandHelper64Name L"CXLSystemInformationHelper-x64"
#define AF_STR_SystemInformationCommandTimeOut L"System Information gathering timed out after 10s"
// Context Information dialog
#define AF_STR_ContextsInformationDialogTitle L"Context Information"
#define AF_STR_ContextsInformationDialogSaveButton L"&Save"
#define AF_STR_ContextsInformationDialogStatus L"Status: "
#define AF_STR_ContextsInformationDialogStatusActive L"Active"
#define AF_STR_ContextsInformationDialogStatusDeleted L"Deleted"
#define AF_STR_ContextsInformationDialogStatusShared L", Shared"
#define AF_STR_ContextsInformationDialogStatusUsingShare L", Using Share"
#define AF_STR_ContextsInformationDialogMarkedForDeletion L"Marked for Deletion"
#define AF_STR_ContextsInformationDialogOpenGLVersion L"OpenGL Version"
#define AF_STR_ContextsInformationDialogOpenGLESVersion L"OpenGL ES Version"
#define AF_STR_ContextsInformationDialogShadingLangVersion L"Shading Language Version"
#define AF_STR_ContextsInformationDialogGLSharedContext L"OpenGL Shared Context"
#define AF_STR_ContextsInformationDialogGLSharingContexts L"OpenGL Sharing Contexts"
#define AF_STR_ContextsInformationDialogCLSharedContexts L"OpenCL Shared Context"
#define AF_STR_ContextsInformationDialogGLRendererTitle L"OpenGL Renderer"
#define AF_STR_ContextsInformationDialogRendererVendor L"Renderer Vendor"
#define AF_STR_ContextsInformationDialogRendererName L"Renderer Name"
#define AF_STR_ContextsInformationDialogRendererVersion L"Renderer Version"
#define AF_STR_ContextsInformationDialogRendererType L"Renderer Type"
#define AF_STR_ContextsInformationDialogIsBackwardCompatible L"Is Backward-Compatible"
#define AF_STR_ContextsInformationDialogIsForewardCompatible L"Is Forward-Compatible"
#define AF_STR_ContextsInformationDialogIsDebugContext L"Is Debug Context"
#define AF_STR_ContextsInformationDialogCodeXLForced L" (CodeXL forced)"
#define AF_STR_ContextsInformationDialogPixelFormatInfoHeader L"Pixel Format Information"
#define AF_STR_ContextsInformationDialogPixelFormatId L"Pixel Format ID"
#define AF_STR_ContextsInformationDialogHardwareAcceleration L"Hardware Acceleration"
#define AF_STR_ContextsInformationDialogDoubleBuffered L"Double-Buffered"
#define AF_STR_ContextsInformationDialogStereographic L"Stereographic"
#define AF_STR_ContextsInformationDialogSupportsNative L"Supports Native Rendering (GDI)"
#define AF_STR_ContextsInformationDialogSupportsNativeShort L"Native Rendering"
#define AF_STR_ContextsInformationDialogChannelHeader L"Channel"
#define AF_STR_ContextsInformationDialogBitsHeader L"Bits"
#define AF_STR_ContextsInformationDialogIndexChannel L"Index"
#define AF_STR_ContextsInformationDialogRedChannel L"Red"
#define AF_STR_ContextsInformationDialogGreenChannel L"Green"
#define AF_STR_ContextsInformationDialogBlueChannel L"Blue"
#define AF_STR_ContextsInformationDialogAlphaChannel L"Alpha"
#define AF_STR_ContextsInformationDialogDepthChannel L"Depth"
#define AF_STR_ContextsInformationDialogStencilChannel L"Stencil"
#define AF_STR_ContextsInformationDialogAccumulationChannel L"Accumulation"
#define AF_STR_ContextsInformationDialogChooseAContext L"Choose a render / compute context to view its information"
#define AF_STR_ContextsInformationDialogCouldNotGetInfo L"Could not get context information"
#define AF_STR_ContextsInformationDialogGPUAffinity L"GPU Affinities"
#define AF_STR_ContextsInformationDialogGPUAffinityGPUName L"GPU %d (%ls)"
#define AF_STR_ContextsInformationDialogGPUAffinityNotSupported L"GPU Affinity information is not supported on this hardware"
#define AF_STR_ContextsInformationDialogSaveInfoFileHeaderAppNameDateAndTime L"////////////////////////////////////////////////////////////\n" \
L"// This File contains %ls information\n" \
L"// Project name: %ls\n" \
L"// Generation date: %ls\n" \
L"// Generation time: %ls\n"
#define AF_STR_ContextsInformationDialogSaveInfoFileHeader1 L"// %ls %d ("
#define AF_STR_ContextsInformationDialogSaveInfoFileHeader2 L")\n" \
L"//\n" \
L"// Generated by CodeXL - an OpenCL and OpenGL Debugger, Profile and Analyzer\n" \
L"// http://gpuopen.com/\n" \
L"////////////////////////////////////////////////////////////\n\n"
#define AF_STR_ContextsInformationDialogSaveInfoFileAlignString L"%-24s "
#define AF_STR_ContextsInformationDialogSaveInfoFileGeneralHeader L"\nGeneral\n-------\n"
#define AF_STR_ContextsInformationDialogSaveInfoFilePixelFormatInfoHeader L"\nPixel Format Information\n------------------------\n"
#define AF_STR_ContextsInformationDialogSaveInfoFileChannelHeader L"Channel"
#define AF_STR_ContextsInformationDialogSaveInfoFileBitsHeader L"Bits"
#define AF_STR_ContextsInformationDialogSaveInfoFileGPUAffinity L"\nGPU Affinities\n--------------\n"
#define AF_STR_ErrorMessageSaveContextInformationFailed L"Could not save context information"
#define AF_STR_ContextsInformationDialogAvailableOnProcessSuspensionMessage L"Context information is available only when debugged process is suspended"
#define AF_STR_ContextsInformationDialogDriversTitle L"Drivers versions"
#define AF_STR_ContextsInformationDialogDriversCALVersion L"CAL version"
#define AF_STR_ContextsInformationDialogDriversCatalystVersion L"AMD Radeon Software version"
#define AF_STR_ContextsInformationsDialogDevices L"Context Devices"
#define AF_STR_ContextsInformationsDialogDevicesUnderline L"==============="
#define AF_STR_ContextsInformationsDialogDeviceHeader L"Device %d"
#define AF_STR_ContextsInformationsDialogDeviceHeaderUnderline L"---------"
#define AF_STR_ContextsInformationsDialogDeviceId L"Device Id"
#define AF_STR_ContextsInformationsDialogDeviceType L"Device Type"
#define AF_STR_ContextsInformationsDialogDeviceName L"Device Name"
#define AF_STR_ContextsInformationsDialogDeviceVersion L"Device Version"
#define AF_STR_ContextsInformationsDialogDeviceVendor L"Device Vendor"
#define AF_STR_SendErrorReportString7 L"System DLL Versions:"
#define AF_STR_SendErrorReportAdditionalStringHeader "Additional Information:"
#define AF_STR_SendErrorReportAdditionalStringOpenCL "- OpenCL Engine loaded:"
#define AF_STR_SendErrorReportAdditionalStringOpenGL "- OpenGL Engine loaded:"
#define AF_STR_SendErrorReportAdditionalStringKernel "- Kernel Debugging Entered:"
// afSourceCodeView:
#define AF_STR_SourceCodeDeleteBreakpoint "Delete Breakpoint"
#define AF_STR_SourceCodeEnableBreakpoint "Enable Breakpoint"
#define AF_STR_SourceCodeDisableBreakpoint "Disable Breakpoint"
#define AF_STR_SourceCodeTextWasNotFound L"The specified text was not found: "
#define AF_STR_SourceCodePassedEndOfDocument L"Passed the end of the document"
#define AF_STR_SourceCodeAddWatch "Add Watch"
#define AF_STR_sourceCodeShowLineNumbers "Show Line Numbers"
#define AF_STR_sourceCodeSaveAs "Save as"
// Teapot strings files:
// Application file paths
// NOTE: rgorton - 6-April-2012
// Be careful about changing these directory names, even to changing
// the case - they are tightly tied to the packaging/installation, and
// also to the underlying filesystem. These now match the physical
// directory names on disk in the source tree.
#define AF_STR_CodeXLImagesDirName L"Images"
#define AF_STR_CodeXLTeapotExampleProjectName L"CodeXL Teapot"
#define AF_STR_CodeXLTeapotExampleSourceFileFolder1 L"AMDTTeapot"
#define AF_STR_CodeXLTeapotExampleSourceFileFolder2 L"AMDTTeapotLib"
#define AF_STR_CodeXLTeapotExampleSrcFolder L"src"
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
#define AF_STR_CodeXLTeapotExampleBinaryName L"CXLTeaPot"
#define AF_STR_CodeXLSampleBinaryExtension L"exe"
#define AF_STR_CODEXLExampleReleaseDirName L"Release"
#elif AMDT_BUILD_TARGET == AMDT_LINUX_OS
#define AF_STR_CodeXLTeapotExampleBinaryName L"CXLTeaPot-bin"
#define AF_STR_CodeXLSampleBinaryExtension L""
#define AF_STR_CODEXLExampleReleaseDirName L"release"
#endif
#define AF_STR_CodeXLTeapotLastMode L"Debug Mode"
#if AMDT_BUILD_TARGET == AMDT_LINUX_OS
// The scons build layout puts content into debug rather than debug/bin
#define AF_STR_CodeXLTeapotDebugBinDirName L"debug"
#else
#define AF_STR_CodeXLTeapotDebugBinDirName L"Debug\\Bin"
#endif
#define AF_STR_CodeXLSampleResourcesDirName L"res"
#define AF_STR_CodeXLWindowsHelpFileName L"CodeXL_User_Guide.chm"
#define AF_STR_CodeXLDialogSmallLogoFileName L"CodeXLDialogSmallLogo.png"
#define AF_STR_CodeXLAboutLogoFileName L"CodeXLAboutLogo.png"
#define AF_STR_CheckForUpdatesIconFileName L"CheckForUpdates.png"
#define AF_STR_CodeXLVSPackageWindowsHelpFileName L"CodeXL_User_Guide.chm"
#define AF_STR_CodeXLWindowsTutorialFileName L"CodeXLTutorial"
#define AF_STR_CodeXLWindowTeapotSolutionName L"AMDTTeaPot%ls.sln"
#define AF_STR_VS2010 L"VS2010"
#define AF_STR_VS2012 L"VS2012"
#define AF_STR_VS2013 L"VS2013"
#define AF_STR_VS2015 L"VS2015"
#define AF_STR_OldSampleProjectQuestion "The project contains a CodeXL sample with a path that no longer exists. Do you want to relocate the sample path to the new CodeXL samples location?"
/// Samples source file names
#define AF_STR_TeapotSrc1 "amdtmainwin.cpp"
#define AF_STR_TeapotSrc2 "amdtteapot.cpp"
#define AF_STR_TeapotSrc3 "teapot.cpp"
#define AF_STR_TeapotSrc4 "glwindow.cpp"
#define AF_STR_TeapotSrc5 "amdtteapotoglcanvas.cpp"
#define AF_STR_TeapotSrc6 "amdtteapotrenderstate.cpp"
#define AF_STR_TeapotSrc7 "amdtteapotoclsmokesystem.cpp"
#define AF_STR_TeapotSrc8 "amdtopenglmath.cpp"
#define AF_STR_TeapotSrc9 "amdtfluidgrid.cpp"
#define AF_STR_TeapotSrc10 "amdtimage.cpp"
#define AF_STR_TeapotSrc11 "amdtopenclhelper.cpp"
#define AF_STR_TeapotSrc12 "amdtopenglhelper.cpp"
#define AF_STR_TeapotSrc13 "amdtgtkmain.cpp"
#define AF_STR_TeapotSrc14 "amdtmainwin.h"
#define AF_STR_TeapotSrc15 "amdtmisc.h"
#define AF_STR_TeapotSrc16 "amdtteapot.h"
#define AF_STR_TeapotSrc17 "amdtteapotsmokesimulationveclength.h"
#define AF_STR_TeapotSrc18 "amdtteapotsmokesimulationvecfield.h"
#define AF_STR_TeapotSrc19 "amdtteapotsmokesimulationvec.h"
#define AF_STR_TeapotSrc20 "amdtteapotsmokesimulationscalarfield.h"
#define AF_STR_TeapotSrc21 "amdtteapotsmokesimulationindex.h"
#define AF_STR_TeapotSrc22 "amdtteapotsmokesimulationgen.h"
#define AF_STR_TeapotSrc23 "amdtteapotsmokesimulationclamp.h"
#define AF_STR_TeapotSrc24 "amdtteapotsmokesimulation.h"
#define AF_STR_TeapotSrc25 "gremedyglextensions.h"
#define AF_STR_TeapotSrc26 "gremedyclextensions.h"
#define AF_STR_TeapotSrc27 "amdtteapotmenubar.h"
#define AF_STR_TeapotSrc28 "amdtteapotoclsmokesystem.h"
#define AF_STR_TeapotSrc29 "amdtteapotoglcanvas.h"
#define AF_STR_TeapotSrc30 "amdtteapotoglcanvasstresstest.h"
#define AF_STR_TeapotSrc31 "amdtteapotrenderstate.h"
#define AF_STR_TeapotSrc32 "amdttimer.h"
#define AF_STR_TeapotSrc33 "amdtopenglhelper.h"
#define AF_STR_TeapotSrc34 "amdtopenglmath.h"
#define AF_STR_TeapotSrc35 "amdtteapotapp.h"
#define AF_STR_TeapotSrc36 "amdtteapotconstants.h"
#define AF_STR_TeapotSrc37 "amdtteapotframe.h"
#define AF_STR_TeapotSrc38 "amdtfluidgrid.h"
#define AF_STR_TeapotSrc39 "amdtimage.h"
#define AF_STR_TeapotSrc40 "amdtopenclhelper.h"
// Generic Context menu items that doesn't appear in the menu bar
#define AF_STR_DeleteSelected L"&Delete Selected\t" AF_STR_keyboardShortcutDeleteMenu
#define AF_STR_DeleteSelectedA "&Delete Selected\t" AF_STR_keyboardShortcutDeleteMenuA
#define AF_STR_SelectAll L"Select &All\t" AF_STR_keyboardShortcutSelectAllMenu
#define AF_STR_SelectAllA "Select &All\t" AF_STR_keyboardShortcutSelectAllMenuA
#define AF_STR_ExportToCSV "&Export to CSV"
#define AF_STR_ShowLineNumbers L"Show &Line Numbers\t"
#define AF_STR_contextSaveStateVariables "Export State Variables Snapshot..."
#define AF_STR_contextSaveFunctionCallsStatistics L"&Export Function Calls Statistics..."
#define AF_STR_contextSaveProfilingData L"&Export Profiling Data..."
#define AF_STR_SelectAllDifferent L"Select All Items with Different Values"
// Main application flow:
#define AF_STR_beforeExitQuestion "Do you want to stop %1?"
#define AF_STR_HelpFileLoadErrorMessage "Could not load the help file"
#define AF_STR_TutorialFileLoadErrorMessage "Could not load the tutorial file"
#define AF_STR_QuickStartFileLoadErrorMessage "Could not load the Quick Start Guide file"
#define AF_STR_exitWithoutSaving L"The project could not be saved, quit anyway?"
#define AF_STR_TeapotSampleDoesNotExist "The Teapot Sample project does not exist."
// File dialog strings:
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
#define AF_STR_executableFilesDetails "Program Files (*.exe);;All files (*.*)"
#else
#define AF_STR_executableFilesDetails "All files (*)"
#endif
#define AF_STR_macProgramFilesDetails L"Applications (*.app);;All files (*.*)"
#define AF_STR_iPhoneOnDeviceProgramFilesDetails L"Xcode projects (*.xcodeproj);;All files (*.*)"
#define AF_STR_allFileDetails "All files (*)"
#define AF_STR_sourceFileDetails "Source Files (*.cl *.c *.cpp *.cxx *.cc *.h *.hpp *.hxx *.hh *.cs)"
#define AF_STR_textFileDetails "Text Files (*.txt)"
#define AF_STR_systemInformationFileTitle "Save System Information as"
#define AF_STR_systemInformationFileSample L"SystemInformation.txt"
#define AF_STR_systemInformationFileDetails "Text Documents (*.txt)"
#define AF_STR_saveDataDialogHeader L"Save Data as"
#define AF_STR_saveDataDialogHeaderA "Save Data as"
#define AF_STR_saveImageDialogHeader "Save Image as"
#define AF_STR_openFileDialogHeader L"Open File"
#define AF_STR_openFileDialogFailed L"Could not find the file specified."
#define AF_STR_saveFileDialogHeader L"Save File"
#define AF_STR_saveFileDialogNothingToSave L"There is nothing to save!"
#define AF_STR_openProjectDialogHeader "Open Project"
#define AF_STR_saveProjectDialogHeader "Save Project as"
// Splash screen:
#define AF_STR_SplashScreenFileName L"CodeXLSplashScreen" // Without extension
#define AF_STR_LogMsg_LoadingSplashScreen L"Loading splash screen"
#define AF_STR_LogMsg_FinishedLoadingSplashScreen L"Finished loading splash screen"
// Menu commands:
// HTML strings:
// General HTML:
#define AF_STR_HtmlTable2Padding L"<table width=100% cellspacing=3>"
#define AF_STR_HtmlTableTagEnd L"</table>"
#define AF_STR_HtmlTREnd L"</tr>"
#define AF_STR_HtmlTDEnd L"</td>"
#define AF_STR_HtmlFontTagStart L""
#define AF_STR_HtmlFontTagEnd L""
#define AF_STR_HtmlBoldTagStart L"<b>"
#define AF_STR_HtmlBoldTagEnd L"</b>"
#define AF_STR_HtmlBoldTagStartA "<b>"
#define AF_STR_HtmlBoldTagEndA "</b>"
#define AF_STR_HtmlNewLine L"<br />"
#define AF_STR_HtmlImage L"<IMG SRC=\"%ls\">"
#define AF_STR_HtmlImageWithSizeSpecifications L"<img SRC=\"%ls\" WIDTH=\"%d\" HEIGHT=\"%d\">"
#define AF_STR_HtmlImageWithSizeSpecsAndRightAlign L"<img SRC=\"%ls\" WIDTH=\"%d\" HEIGHT=\"%d\" STYLE=\"float:right;\">"
#define AF_STR_HtmlImage2 L"<IMG src=\"%ls\" alt=\"%ls\" align=middle border=0 valign=bottom />"
#define AF_STR_HtmlColorWhite L"FFFFFF"
#define AF_STR_HtmlEmptyLine L"<br>"
#define AF_STR_HtmlQuot L"""
#define AF_STR_HtmlNBSP " "
#define AF_STR_propertiesViewCaption L"Properties"
#define AF_STR_propertiesViewCommandName L"&Properties"
#define AF_STR_informationViewCaption L"Output"
#define AF_STR_informationViewCommandName L"&Output"
#define AF_STR_HtmlNoSourceFoundFileName "NoSource"
#define AF_STR_HtmlFindSourceWebpageTitle L"No Source Available"
#define AF_STR_HtmlFindSourceWebpage "<!doctype html><html lang=\"eng\"><head><meta charset=\"utf-8\">"\
"<title>No Source Available</title><style>"\
"body{font-family: %1, clean, sans-serif;}h1{font-weight: bold;font-size: 1.5em;}</style>"\
"</head><body><h1>%2 was not found</h1><p>CodeXL requires the location of this file to display the source for the current call stack frame.</p><p><a href = \"FindSource-%3\">Click to locate the file %2</a></p></body></html>"
#define AF_STR_HtmlNoDebugInformationWebpage "<!doctype html><html lang=\"eng\"><head><meta charset=\"utf-8\"><title>No Debug Information</title>"\
"<style>body{font-family: %1, clean, sans-serif;}h1{font-weight: bold;font-size: 1.5em;}</style></head>"\
"<body><h1>No debug information available for file %2</h1></body></html>"
#define AF_STR_HtmlNoDebugInformationNoFileWebpage "<!doctype html><html lang=\"eng\"><head><meta charset=\"utf-8\"><title>No Debug Information</title>"\
"<style>body{font-family: \"Helvetica Neue\", clean, sans-serif;}h1{font-weight: bold;font-size: 1.5em;}</style>"\
"</head><body><h1>No debug information available</h1><p>The debugged module does not contain debug information. Try to build it with debug information (-g) and restart debug session.</p><p>Module details: %1</p></body></html>"
#define AF_STR_HtmlFindSourceLink "FindSource"
// Execution mode HTML properties:
#define AF_STR_HtmlPropertiesTableRowStart L"<tr bgcolor=#F5F5F5><td>"
#define AF_STR_HtmlPropertiesTableRowStartWithHighlightAndColspan L"<tr bgcolor=#CCCCCC><td colspan=%u>"
#define AF_STR_HtmlPropertiesTableRowStartWithWeakHighlight L"<tr bgcolor=#E0E0E0><td>"
#define AF_STR_HtmlPropertiesTableRowStartWithRowspan L"<tr bgcolor=#F5F5F5><td rowspan=%u valign=center>"
#define AF_STR_HtmlPropertiesTableRowStartWithRowspanAlignTop L"<tr bgcolor=#F5F5F5><td rowspan=%u valign=top>"
#define AF_STR_HtmlPropertiesTableRowStartWithColspan L"<tr bgcolor=#F5F5F5><td colspan=%u>"
#define AF_STR_HtmlPropertiesTableColEnd L"</td><td>"
#define AF_STR_HtmlPropertiesTableColEndHighlightedCell L"</td><td bgcolor=#cccccc>"
#define AF_STR_HtmlPropertiesTableRowEnd L"</td></tr>"
#define AF_STR_HtmlPropertiesLeftTagStart L"<left>"
#define AF_STR_HtmlPropertiesLeftTagEnd L"</left>"
#define AF_STR_HtmlPropertiesRightTagStart L"<tr><td align=right>"
#define AF_STR_HtmlPropertiesThumbnailFileNameSuffix L"-thumb"
#define AF_STR_HtmlPropertiesNonbreakingSpace L" "
#define AF_STR_HtmlPropertiesFunctionArgumentsListStart L"<b>(</b>"
#define AF_STR_HtmlPropertiesFunctionArgumentsListEnd L"<b>)</b>"
#define AF_STR_HtmlPropertiesTotal L"<b>Total: </b>"
#define AF_STR_HtmlPropertiesFontHeaderCommentTagStart L"<font SIZE=+1>"
#define AF_STR_HtmlPropertiesFontHeaderCommentTagEnd L"</font>"
#define AF_STR_HtmlPropertiesFontHeaderTagStart L"<b>"
#define AF_STR_HtmlPropertiesFontHeaderTagEnd L"</B><BR /><BR />"
#define AF_STR_HtmlPropertiesLink1ParamStart L"<a HREF='%ls-%d'>"
#define AF_STR_HtmlPropertiesLink2ParamStart L"<a HREF='%ls-%d-%d'>"
#define AF_STR_HtmlPropertiesLink3ParamStart L"<a HREF='%ls-%d-%d-%d'>"
#define AF_STR_HtmlPropertiesLinkHREF1ParamStart L"%ls-%d"
#define AF_STR_HtmlPropertiesLinkHREF2ParamStart L"%ls-%d-%d"
#define AF_STR_HtmlPropertiesLinkHREF3ParamStart L"%ls-%d-%d-%d"
#define AF_STR_HtmlMultipleItemsCaption L"Multiple Items Selection in Tree"
#define AF_STR_HtmlMultipleItems L"Multiple tree items selected. Select a single item to display it's properties."
// Image names:
#define AF_STR_WarningYellowIconFileName L"WarningIconYellow.png"
#define AF_STR_WarningYellowIconSmallFileName L"WarningIconYellowSmall.png"
#define AF_STR_WarningOrangeIconFileName L"WarningIconOrange.png"
#define AF_STR_WarningOrangeIconSmallFileName L"WarningIconOrangeSmall.png"
#define AF_STR_WarningRedIconFileName L"WarningIconRed.png"
#define AF_STR_WarningRedIconSmallFileName L"WarningIconRedSmall.png"
#define AF_STR_LightBulbSmallFileName L"LightBulbIconSmall.png"
#define AF_STR_InformationIconFileName L"InformationIcon.png"
#define AF_STR_InformationIconSmallFileName L"InformationIconSmall.png"
#define AF_STR_ShadingProgramFileName L"ShadingProgramIcon.png"
#define AF_STR_pngFileExt L"png"
// Execution mode manager strings
#define AF_STR_APIStepDebugging "API Step (" AF_STR_APIStepDebuggingShortcut ")"
#define AF_STR_DrawStepDebugging "Draw Step (" AF_STR_DrawStepDebuggingShortcut ")"
#define AF_STR_FrameStepDebugging "Frame Step (" AF_STR_FrameStepDebuggingShortcut ")"
#define AF_STR_StepOverDebugging "Step Over (" AF_STR_StepOverDebuggingShortcut ")"
#define AF_STR_StepInDebugging "Step In (" AF_STR_StepInDebuggingShortcut ")"
#define AF_STR_StepOutDebugging "Step Out (" AF_STR_StepOutDebuggingShortcut ")"
#define AF_STR_BreakDebugging "Break (" AF_STR_PauseDebuggingShortcut ")"
#define AF_STR_PauseProfiling "Pause (" AF_STR_PauseDebuggingShortcut ")"
#define AF_STR_StopDebugging "Stop (" AF_STR_StopDebuggingShortcut ")"
#define AF_STR_Start "Start (" AF_STR_StartDebuggingShortcut ")"
#define AF_STR_StartTooltip "Start %1 (" AF_STR_StartDebuggingShortcut ")"
#define AF_STR_Build "Build (" AF_STR_BuildShortcut ")"
#define AF_STR_CancelBuild "Cancel Build (" AF_STR_CancelBuildShortcut ")"
#define AF_STR_StartDebuggingShortcut "F5"
#define AF_STR_PauseDebuggingShortcut "F6"
#define AF_STR_StopDebuggingShortcut "Shift+F5"
#define AF_STR_APIStepDebuggingShortcut "Ctrl+F10"
#define AF_STR_DrawStepDebuggingShortcut "Ctrl+Shift+F10"
#define AF_STR_FrameStepDebuggingShortcut "Ctrl+F11"
#define AF_STR_StepOverDebuggingShortcut "F10"
#define AF_STR_StepInDebuggingShortcut "F11"
#define AF_STR_StepOutDebuggingShortcut "Shift+F11"
#define AF_STR_BuildShortcut "F7"
#define AF_STR_CancelBuildShortcut "Shift+F7"
// Item identification:
#define AF_STR_ItemIDUnknown L"Unknown item"
#define AF_STR_AppRoot L"Application Root"
#define AF_STR_GLContext L"GL Context"
#define AF_STR_GLTextures L"Textures"
#define AF_STR_GLTexture L"Texture"
#define AF_STR_GLRenderBuffers L"Render Buffers"
#define AF_STR_GLRenderBuffer L"Render Buffer"
#define AF_STR_GLStaticBuffers L"Static Buffers"
#define AF_STR_GLStaticBuffer L"Static Buffer"
#define AF_STR_GLAllPBuffers L"All PBuffers"
#define AF_STR_GLPBuffers L"PBuffers"
#define AF_STR_GLPBuffer L"PBuffer"
#define AF_STR_GLPBufferStaticBuffer L"PBuffer Static Buffer"
#define AF_STR_GLSyncs L"Sync Objects"
#define AF_STR_GLSync L"Sync"
#define AF_STR_GLVBOs L"VBOs"
#define AF_STR_GLVBO L"VBO"
#define AF_STR_Programs L"Programs"
#define AF_STR_Program L"Program"
#define AF_STR_GLShaders L"Shaders"
#define AF_STR_GLVertexShader L"Vertex Shader"
#define AF_STR_GLTessellationControlShader L"Tessellation Control Shader"
#define AF_STR_GLTessellationEvaluationShader L"Tessellation Evaluation Shader"
#define AF_STR_GLGeometryShader L"Geometry Shader"
#define AF_STR_GLFragmentShader L"Fragment Shader"
#define AF_STR_GLComputeShader L"Compute Shader"
#define AF_STR_GLUnknownShader L"Shader"
#define AF_STR_GLDisplayLists L"Display Lists"
#define AF_STR_GLDisplayList L"Display List"
#define AF_STR_GLFBOs L"FBOs"
#define AF_STR_GLFBO L"FBO"
#define AF_STR_GLFBOAttachment L"FBO Attachemnt"
#define AF_STR_CLContext L"CL Context"
#define AF_STR_CLImages L"CL Images"
#define AF_STR_CLImage L"CL Image"
#define AF_STR_CLBuffers L"CL Buffers"
#define AF_STR_CLBuffer L"CL Buffer"
#define AF_STR_CLSubBuffer L"CL Sub Buffer"
#define AF_STR_CLPipes L"CL Pipes"
#define AF_STR_CLPipe L"CL Pipe"
#define AF_STR_CLSamplers L"CL Samplers"
#define AF_STR_CLSampler L"CL Sampler"
#define AF_STR_CLEvents L"CL Events"
#define AF_STR_CLEvent L"CL Event"
#define AF_STR_CLCommandQueues L"CL Command Queues"
#define AF_STR_CLCommandQueue L"CL Command Queue"
#define AF_STR_CLDevice L"CL Device"
#define AF_STR_CLKernel L"Kernel"
#define AF_STR_CLKernelVariable L"Kernel variable"
#define AF_STR_ProfileSession L"Profile session"
#define AF_STR_ProfileSessionType L"Profile session type"
#define AF_STR_ProfileSessionGPUSummary L"GPU Profile session summary"
#define AF_STR_ProfileSessionGPUAPISummary L"GPU Profile session API summary"
#define AF_STR_ProfileSessionGPUContextSummary L"GPU Profile session context summary"
#define AF_STR_ProfileSessionGPUKernelSummary L"GPU Profile session kernel summary"
#define AF_STR_ProfileSessionGPUTop10TransferSummary L"GPU Profile session top10 transfer summary"
#define AF_STR_ProfileSessionGPUTop10KernelsSummary L"GPU Profile session top10 kernel summary"
#define AF_STR_ProfileSessionGPUBestPracticeSummary L"GPU Profile session best practice summary"
#define AF_STR_ProfileSessionGPUKernels L"GPU Profile session kernels"
#define AF_STR_ProfileSessionGPUKernel L"GPU Profile session kernel"
#define AF_STR_AnalyzerExeFile L"Analyzer executable file"
#define AF_STR_AnalyzerOpenCLSource L"Analyzer OpenCL source code"
#define AF_STR_AnalyzerKernel L"Analyzer kernel"
#define AF_STR_AnalyzerStatistics L"Analyzer kernel statistics"
#define AF_STR_AnalyzerAnalysis L"Analyzer kernel analysis"
#define AF_STR_AnalyzerDevice L"Analyzer kernel device"
#define AF_STR_AnalyzerHistory L"Analyzer kernel history"
#if (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS)
#define AF_STR_AnalyzerFile L"Analyzer Kernel/DirectX file"
#define AF_STR_AnalyzerAddFile L"Analyzer add existing OpenCL/DirectX file"
#define AF_STR_AnalyzerNewFile L"Analyzer create new OpenCL/DirectX file"
#else // Building for Linux
#define AF_STR_AnalyzerFile L"Analyzer Kernel file"
#define AF_STR_AnalyzerAddFile L"Analyzer add existing OpenCL file"
#define AF_STR_AnalyzerNewFile L"Analyzer create new OpenCL file"
#endif // AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
// Images and buffers load status messages:
#define AF_STR_ImagesAndBuffersViewLoadFailure L"Object is currently unavailable"
#define AF_STR_ImagesAndBuffersViewImagesBuffersProcessIsRunning L"Textures, Buffers and Images information are only displayed when the debugged process has been suspended"
#define AF_STR_ImagesAndBuffersViewImagesBuffersProcessIsRunningTitle L"Process is running"
#define AF_STR_ImagesAndBuffersViewImagesBuffersProcessIsNotRunningTitle L"Process is not running"
#define AF_STR_ImagesAndBuffersViewVariablesProcessIsRunning L"Kernel variables information is only displayed when the debugged process has been suspended"
#define AF_STR_ImagesAndBuffersViewKernelIsNotDebuggedTitle L"Process is not in kernel debugging"
#define AF_STR_ImagesAndBuffersViewKernelInteroperabilityTitle L"CL-GL interoperability object"
#define AF_STR_ImagesAndBuffersViewKernelIsNotDebugged L"Kernel variables are displayed only when a kernel is being debugged"
#define AF_STR_ImagesAndBuffersViewKernelDebugged L"Images and buffers are not available when a kernel is being debugged"
#define AF_STR_ImagesAndBuffersViewObjectNotAvailable L"%ls is currently unavailable"
#define AF_STR_ImagesAndBuffersViewObjectsNotAvailable L"%ls are not currently available"
#define AF_STR_ImagesAndBuffersViewImageTypeUnknown L"Image type is unknown"
#define AF_STR_ImagesAndBuffersViewTextureTypeUnknown L"Texture type is unknown"
#define AF_STR_ImagesAndBuffersViewGLCLInterop L"CL-GL interoperability objects are currently not supported"
#define AF_STR_ImagesAndBuffersViewGLBeginEndMessage L"Images and buffers are unavailable while the process is in glBegin-glEnd block"
#define AF_STR_ImagesAndBuffersViewGLBeginEndTitle L"Process is in glBegin-glEnd block"
#define AF_STR_ImagesAndBuffersViewObjectUnavailableMessageHeader L"%ls is unavailable"
#define AF_STR_ImagesAndBuffersViewObjectUnavailableMessageTitle L"Item is unavailable"
#define AF_STR_ImagesAndBuffersViewVariableDoNotExistMessageTitle L"The variable doesn't exist in this context"
#define AF_STR_ImagesAndBuffersViewBoundToFBO L"Object is unavailble when an FBO is bound"
#define AF_STR_ImagesAndBuffersViewerNoObjectsAvailableMessage L"%ls Are Unavailable"
// CodeXL version XML file:
#define AF_STR_CodeXLVersionXMLFileName L"VersionSettings"
#define AF_STR_CodeXLVersionXMLVersionSettingsNodeName "VersionSettings"
#define AF_STR_CodeXLVersionXMLTitleCaptionNodeName "TitleCaption"
#define AF_STR_CodeXLVersionXMLCheckForNewVersionURLNodeName "CheckForNewVersionURL"
// HTML properties strings:
#define AF_STR_ProcessEventsViewPropertiesTitleProcessStarted L"Process Started"
#define AF_STR_ProcessEventsViewPropertiesTitleProcessStopped L"Process Stopped"
#define AF_STR_ProcessEventsViewExePath L"Executable Path"
#define AF_STR_ProcessEventsViewWorkDir L"Work Directory"
#define AF_STR_ProcessEventsViewStartTime L"Start Time"
#define AF_STR_ProcessEventsViewProcessExit L"Process Exit"
#define AF_STR_ProcessEventsViewExitCode L"Exit Code"
#define AF_STR_ProcessEventsViewExitTime L"Exit Time"
#define AF_STR_ProcessEventsViewCreationTime L"Creation Time"
#define AF_STR_ProcessEventsViewPropertiesTitleProcessCreated L"Process Created"
// Mdi sub Window
#define AF_STR_CopyFullPath "Copy Full Path"
#define AF_STR_OpenContaningFolder "Open Contaning Folder"
// Multi directory dialog:
#define AF_STR_MultiDirDialogCaption "Source Files Directories:"
#define AF_STR_MultiDirDialogTableHeader "Directories"
#define AF_STR_MultiDirDeleteTooltip "Delete Directory"
#define AF_STR_MultiDirNewTooltip "New Directory"
#define AF_STR_MultiDirUpTooltip "Move Directory Up"
#define AF_STR_MultiDirDownTooltip "Move Directory Down"
// Document update String
#define AF_STR_UpdateOutOfDate "%1\nThis file has been modified outside of this source editor tab.\nDo you want to reload it ?"
// Startup dialog:
#define AF_STR_StartupDialogCaption "CodeXL - No project loaded"
#define AF_STR_StartupDialogDescription "To start working with CodeXL, please select one of the following:"
#define AF_STR_StartupDialogDebugCaption "<font size=+1>DEBUG<font>"
#define AF_STR_StartupDialogProfileCaption "<font size=+1>PROFILE<font>"
#define AF_STR_StartupDialogAnalyzeCaption "<font size=+1>ANALYZE<font>"
#define AF_STR_StartupButtonTableHTML "<table cellpadding=0 cellspacing=0><tr><td style='vertical-align: middle;'><img src ='mydata://image.jpg' style='float:left;'></img></td><td style='padding-left:10px;'>%1</td></tr><table>"
#define AF_STR_StartupDialogButtonTableHTML "<table cellpadding=0 cellspacing=0><tr><td style='vertical-align: middle;'><img src ='mydata://image.jpg' style='float:left;'></img></td><td style='padding-left:10px;'>%1</td></tr><table>"
#define AF_STR_StartupDialogNewProjectTitle "Create new project"
#define AF_STR_StartupDialogNewProjectDescription "<br>After creating a new project you can select the desired mode to debug or profile your application,<br>or to statically analyze your shaders and kernels."
#define AF_STR_StartupDialogNewProjectDebuggingTitle "Create new project for Debugging"
#define AF_STR_StartupDialogNewProjectDebuggingDescription "<br>Debugging allows you to set breakpoints, watch variables and much more.<br>Automatically selects Debug mode."
#define AF_STR_StartupDialogNewProjectProfilingTitle "Create new project for Profiling"
#define AF_STR_StartupDialogNewProjectProfilingDescription "<br>Profile code that runs on the GPU. Select a session type to define what data is collected.<br>Automatically selects Profile mode."
#if (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS)
#define AF_STR_StartupDialogNewProjectAnalyzeTitle "Create a new source file for analysis"
#define AF_STR_StartupDialogNewProjectAnalyzeDescription "<br>Create and build an OpenCL/DirectX kernel for multiple hardware targets and analyze the ISA result to gain insight into<br>optimizing its performance."
#define AF_STR_StartupDialogAddCLFileAnalyzeTitle "Add an existing source file for Analysis"
#define AF_STR_StartupDialogAddCLFileAnalyzeDescription "<br>Compile an OpenCL/DirectX file for multiple hardware targets and analyze the ISA result to gain insight into<br>optimizing its performance."
#else // Building for Linux
#define AF_STR_StartupDialogNewProjectAnalyzeTitle "Create a new OpenCL/OpenGL file for Analysis"
#define AF_STR_StartupDialogNewProjectAnalyzeDescription "<br>Create and Compile an OpenCL kernel for multiple hardware targets and analyze the ISA result to gain insight into<br>optimizing its performance."
#define AF_STR_StartupDialogAddCLFileAnalyzeTitle "Add an existing OpenCL/OpenGL file for Analysis"
#define AF_STR_StartupDialogAddCLFileAnalyzeDescription "<br>Compile an OpenCL file for multiple hardware targets and analyze the ISA result to gain insight into<br>optimizing its performance."
#endif // (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS)
// Aid functions
#define AF_STR_AMD_GPU_COMPONENT_NOT_INSTALLED L"CodeXL GPU Profiler: An AMD GPU was not detected. Local GPU Profiling will be disabled.\n"
#define AF_STR_AMD_CATALYST_COMPONENT_NOT_INSTALLED L"CodeXL Static Analyzer: AMD Radeon Software was not detected. Static Analysis will be disabled.\n"
// Memory Error messages
#define AF_STR_memAllocFailureHeadline "CodeXL - Memory Allocation Failure"
#define AF_STR_memAllocFailureClientMsg "Insufficient memory in executed application."
// CSV export strings:
#define AF_STR_saveCSVFilePostfix ".csv"
#define AF_STR_csvFileDetails L"CSV (Comma delimited) (*.csv)"
/// History management tags. These tags are used for widgets and actions that support history management. afBrowseAction + afLineEdit.
#define AF_Str_NewProjectRemoteHostIPLineEdit "NewProjectRemoteHostIP"
#define AF_Str_NewProjectBrowseForEXE "NewProjectBrowseForEXE"
#define AF_Str_NewProjectBrowseForWorkingFolder "NewProjectBrowseForWorkingFolder"
#define AF_Str_NewProjectBrowseForSourceCodeFolder "NewProjectBrowseForSourceCodeFolder"
#define AF_Str_NewProjectBrowseForSourceCodeRootFolder "NewProjectBrowseForSourceCodeRootFolder"
#define AF_Str_OpenFileBrowseFolder "OpenFileBrowseFolder"
/// Progress bar strings:
#define AF_STR_ProgressMessageFormat L"%ls %ls..."
#define AF_Str_optionsDialogD3DCompileType L"D3D"
/// About dialog
#define AF_STR_HelpAboutLGPLCopyRightCaption "LGPL Components:"
#define AF_STR_HelpAboutLGPLCopyRightHeader "The GNU Lesser General Public License, version 2.1 (LGPL-2.1)\nGNU Lesser General Public License"
#define AF_STR_HelpAboutLGPLCopyRightBody "Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\nUse of the Qt library is governed by the GNU\nLesser General Public License version 2.1 (LGPL v 2.1)."
/// CodeXl Special Folders
#define AF_STR_CSV_FILE_CACHE L"CSV_FILE_CACHE"
| 25,933 |
347 | package org.ovirt.engine.core.bll.storage.disk.cinder;
import java.util.Collection;
import java.util.Collections;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.Typed;
import javax.inject.Inject;
import org.ovirt.engine.core.bll.InternalCommandAttribute;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.storage.disk.image.RemoveImageCommand;
import org.ovirt.engine.core.bll.tasks.interfaces.CommandCallback;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.RemoveCinderDiskVolumeParameters;
import org.ovirt.engine.core.common.businessentities.SubjectEntity;
import org.ovirt.engine.core.common.businessentities.storage.CinderDisk;
import org.ovirt.engine.core.compat.CommandStatus;
import org.ovirt.engine.core.compat.Guid;
@InternalCommandAttribute
public class RemoveCinderDiskVolumeCommand<T extends RemoveCinderDiskVolumeParameters> extends RemoveImageCommand<T> {
private Guid storageDomainId;
@Inject
@Typed(RemoveCinderDiskVolumeCommandCallback.class)
private Instance<RemoveCinderDiskVolumeCommandCallback> callbackProvider;
public RemoveCinderDiskVolumeCommand(T parameters, CommandContext cmdContext) {
super(parameters, cmdContext);
}
@Override
public void executeCommand() {
CinderDisk volumeToDelete = getParameters().getRemovedVolume();
if (!deleteVolumeFromCinder(volumeToDelete)) {
setCommandStatus(CommandStatus.FAILED);
}
persistCommand(getParameters().getParentCommand(), true);
setSucceeded(true);
}
private boolean deleteVolumeFromCinder(CinderDisk lastCinderVolume) {
try {
getCinderBroker().deleteVolumeByClassificationType(lastCinderVolume);
} catch (Exception e) {
log.error("Failed to remove volume '{}' of cider disk id '{}'. Exception: {}",
lastCinderVolume.getImageId(),
lastCinderVolume.getId(),
e);
return false;
}
return true;
}
@Override
public Guid getStorageDomainId() {
if (storageDomainId == null) {
storageDomainId = getParameters().getRemovedVolume().getStorageIds().get(0);
}
return storageDomainId;
}
@Override
protected void endWithFailure() {
super.endWithFailure();
CinderDisk cinderVolume = getParameters().getRemovedVolume();
log.error("Could not remove Cinder volume id '{}' of disk id '{}'.",
cinderVolume.getImageId(),
cinderVolume.getId());
}
@Override
public CommandCallback getCallback() {
return callbackProvider.get();
}
@Override
protected Collection<SubjectEntity> getSubjectEntities() {
return Collections.singleton(new SubjectEntity(VdcObjectType.Storage,
getParameters().getRemovedVolume().getStorageIds().get(0)));
}
}
| 1,129 |
634 | <reponame>halotroop2288/consulo
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util;
import consulo.disposer.Disposable;
import com.intellij.util.containers.WeakList;
import consulo.disposer.Disposer;
import consulo.logging.Logger;
import org.jetbrains.annotations.Contract;
import javax.annotation.Nonnull;
/**
* @author <NAME>
*/
public class LowMemoryWatcher {
private static final Logger LOG = Logger.getInstance(LowMemoryWatcher.class);
public enum LowMemoryWatcherType {
ALWAYS,
ONLY_AFTER_GC
}
private static final WeakList<LowMemoryWatcher> ourListeners = new WeakList<>();
private final Runnable myRunnable;
private final LowMemoryWatcherType myType;
public static void onLowMemorySignalReceived(boolean afterGc) {
LOG.info("Low memory signal received: afterGc=" + afterGc);
for (LowMemoryWatcher watcher : ourListeners.toStrongList()) {
try {
if (watcher.myType == LowMemoryWatcherType.ALWAYS || watcher.myType == LowMemoryWatcherType.ONLY_AFTER_GC && afterGc) {
watcher.myRunnable.run();
}
}
catch (Throwable e) {
LOG.info(e);
}
}
}
/**
* Registers a runnable to run on low memory events
*
* @param runnable the action which executes on low-memory condition. Can be executed:
* - in arbitrary thread
* - in unpredictable time
* - multiple copies in parallel so please make it reentrant.
* @param notificationType When ONLY_AFTER_GC, then the runnable will be invoked only if the low-memory condition still exists after GC.
* When ALWAYS, then the runnable also will be invoked when the low-memory condition is detected before GC.
* @return a LowMemoryWatcher instance holding the runnable. This instance should be kept in memory while the
* low memory notification functionality is needed. As soon as it's garbage-collected, the runnable won't receive any further notifications.
*/
@Contract(pure = true) // to avoid ignoring the result
public static LowMemoryWatcher register(@Nonnull Runnable runnable, @Nonnull LowMemoryWatcherType notificationType) {
return new LowMemoryWatcher(runnable, notificationType);
}
@Contract(pure = true) // to avoid ignoring the result
public static LowMemoryWatcher register(@Nonnull Runnable runnable) {
return new LowMemoryWatcher(runnable, LowMemoryWatcherType.ALWAYS);
}
/**
* Registers a runnable to run on low memory events. The notifications will be issued until parentDisposable is disposed.
*/
public static void register(@Nonnull Runnable runnable, @Nonnull LowMemoryWatcherType notificationType, @Nonnull Disposable parentDisposable) {
final LowMemoryWatcher watcher = new LowMemoryWatcher(runnable, notificationType);
Disposer.register(parentDisposable, () -> watcher.stop());
}
public static void register(@Nonnull Runnable runnable, @Nonnull Disposable parentDisposable) {
register(runnable, LowMemoryWatcherType.ALWAYS, parentDisposable);
}
private LowMemoryWatcher(@Nonnull Runnable runnable, @Nonnull LowMemoryWatcherType type) {
myRunnable = runnable;
myType = type;
ourListeners.add(this);
}
public void stop() {
ourListeners.remove(this);
}
/**
* LowMemoryWatcher maintains a background thread where all the handlers are invoked.
* In server environments, this thread may run indefinitely and prevent the class loader from
* being gc-ed. Thus it's necessary to invoke this method to stop that thread and let the classes be garbage-collected.
*/
static void stopAll() {
ourListeners.clear();
}
}
| 1,393 |
1,540 | <reponame>punamsapkale/testng
package test.uniquesuite;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import testhelper.OutputDirectoryPatch;
public class TestAfter {
@Test
public void testAfter() {
TestNG tng = new TestNG();
tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory());
tng.setTestClasses(new Class[] {TestAfter1.class, TestAfter2.class});
tng.run();
Assert.assertEquals(BaseAfter.m_afterCount, 1);
}
@AfterTest
public void afterTest() {
BaseAfter.m_afterCount = 0;
BaseBefore.m_beforeCount = 0;
BaseBefore.m_afterCount = 0;
}
}
/////
| 255 |
812 | <reponame>narojkumar99/Melophile
package com.vpaliy.data.repository;
import com.vpaliy.data.mapper.Mapper;
import com.vpaliy.data.source.PersonalInfo;
import com.vpaliy.data.source.local.handler.PlaylistHandler;
import com.vpaliy.data.source.local.handler.TrackHandler;
import com.vpaliy.data.source.remote.Filter;
import com.vpaliy.domain.model.Playlist;
import com.vpaliy.domain.model.Track;
import com.vpaliy.domain.model.User;
import com.vpaliy.domain.repository.PersonalRepository;
import com.vpaliy.soundcloud.SoundCloudService;
import com.vpaliy.soundcloud.model.UserEntity;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Single;
import javax.inject.Inject;
import javax.inject.Singleton;
import android.support.annotation.NonNull;
@Singleton
public class MusicPersonalRepository
implements PersonalRepository {
private SoundCloudService service;
private Mapper<User, UserEntity> userMapper;
private PersonalInfo personalInfo;
private PlaylistHandler playlistHandler;
private TrackHandler trackHandler;
private Filter filter;
@Inject
public MusicPersonalRepository(SoundCloudService service,
Mapper<User, UserEntity> userMapper,
PlaylistHandler playlistHandler,
TrackHandler trackHandler, Filter filter,
PersonalInfo personalInfo) {
this.service = service;
this.userMapper = userMapper;
this.personalInfo = personalInfo;
this.trackHandler = trackHandler;
this.playlistHandler = playlistHandler;
this.filter = filter;
}
@Override
public Completable likeTrack(@NonNull Track track) {
personalInfo.like(track.getId());
return service.loveTrack(track.getId());
}
@Override
public Completable unfollow(@NonNull User user) {
personalInfo.removeFollower(user.getId());
return service.unfollowUser(user.getId());
}
@Override
public Completable follow(@NonNull User user) {
personalInfo.follow(user.getId());
return service.followUser(user.getId());
}
@Override
public Single<List<Playlist>> fetchPlaylistHistory() {
return Single.fromCallable(() -> playlistHandler.querySaved());
}
@Override
public Single<List<Track>> fetchTrackHistory() {
return Single.fromCallable(() -> trackHandler.queryHistory());
}
@Override
public Single<User> fetchMyself() {
return service.me()
.map(filter::filter)
.map(userMapper::map);
}
@Override
public Completable clearFavoritePlaylists() {
return null;
}
@Override
public Completable clearFavoriteTracks() {
return null;
}
@Override
public Completable likePlaylist(Playlist playlist) {
return null;
}
@Override
public Completable unfollowAll() {
return null;
}
@Override
public Completable unlikePlaylist(Playlist playlist) {
return null;
}
@Override
public Completable unlikeTrack(Track track) {
return null;
}
@Override
public Completable removePlaylist(Playlist playlist) {
return null;
}
@Override
public Completable removeTrack(Track track) {
return null;
}
@Override
public Single<List<Playlist>> fetchFavoritePlaylist() {
return null;
}
@Override
public Single<List<Track>> fetchFavoriteTracks() {
return null;
}
@Override
public Completable savePlaylist(@NonNull Playlist playlist) {
return null;
}
@Override
public Completable saveTrack(@NonNull Track track) {
return null;
}
@Override
public Completable clearPlaylists() {
return null;
}
@Override
public Completable clearTracks() {
return null;
}
@Override
public Single<List<User>> fetchFollowers() {
return null;
}
}
| 1,341 |
1,131 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.network.contrail.management;
import java.io.IOException;
import com.cloud.domain.DomainVO;
import com.cloud.projects.ProjectVO;
public interface ServerDBSync {
public final static short SYNC_STATE_IN_SYNC = 0;
public final static short SYNC_STATE_OUT_OF_SYNC = 1;
public final static short SYNC_STATE_UNKNOWN = -1;
/*
* API for syncing all classes of vnc objects with cloudstack
* Sync cloudstack and vnc objects.
*/
public short syncAll(short syncMode);
public void syncClass(Class<?> cls);
public void createProject(ProjectVO project, StringBuffer syncLogMesg) throws IOException;
public void createDomain(DomainVO domain, StringBuffer logMesg) throws IOException;
}
| 435 |
381 | /*
* F42Handler.h
*
* Created on: 15 maj 2014
* Author: MattLech
*/
#ifndef F42HANDLER_H_
#define F42HANDLER_H_
#include "GCodeHandler.h"
#include "Config.h"
#include "CurrentState.h"
#include "pins.h"
#include "Config.h"
#include "PinControl.h"
class F42Handler : public GCodeHandler
{
public:
static F42Handler *getInstance();
int execute(Command *);
private:
F42Handler();
F42Handler(F42Handler const &);
void operator=(F42Handler const &);
};
#endif /* F42HANDLER_H_ */
| 194 |
5,300 | <filename>frameworks/Java/act/src/main/java/com/techempower/act/model/Fortune.java
package com.techempower.act.model;
/*-
* #%L
* TEB ActFramework Project
* %%
* Copyright (C) 2016 - 2017 ActFramework
* %%
* 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.
* #L%
*/
import act.sys.Env;
import act.util.SimpleBean;
import com.techempower.act.AppEntry;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "fortune")
@Table(name = "fortune")
@org.mongodb.morphia.annotations.Entity(value = "fortune", noClassnameStored = true)
@Env.RequireProfile(value = AppEntry.PROFILE_JSON_PLAINTEXT, except = true)
public final class Fortune implements SimpleBean, Comparable<Fortune> {
@Id
@org.mongodb.morphia.annotations.Id
public Integer id;
public String message;
public Fortune(Integer id, String message) {
this.id = id;
this.message = message;
}
@Override
public int compareTo(Fortune o) {
return message.compareTo(o.message);
}
}
| 524 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Groan",
"definitions": [
"A deep inarticulate sound conveying pain, despair, pleasure, etc.",
"A complaint.",
"A low creaking sound made by an object under pressure."
],
"parts-of-speech": "Noun"
} | 119 |
543 | <reponame>fredells/riiablo
package com.riiablo.engine.server;
import com.artemis.ComponentMapper;
import com.artemis.annotations.All;
import com.artemis.systems.IteratingSystem;
import com.badlogic.gdx.physics.box2d.Body;
import com.riiablo.engine.server.component.Box2DBody;
import com.riiablo.engine.server.component.Position;
@All({Box2DBody.class, Position.class})
public class Box2DSynchronizerPost extends IteratingSystem {
protected ComponentMapper<Box2DBody> mBox2DBody;
protected ComponentMapper<Position> mPosition;
@Override
protected void process(int entityId) {
Body body = mBox2DBody.get(entityId).body;
mPosition.get(entityId).position.set(body.getPosition());
}
}
| 238 |
1,668 | package org.elixir_lang.eex.lexer;
import com.intellij.lexer.FlexAdapter;
import org.elixir_lang.eex.lexer.Flex;
import java.io.Reader;
public class Adapter extends FlexAdapter {
public Adapter() {
super(new Flex((Reader) null));
}
}
| 99 |
370 | <reponame>daiwei89/wdai_petuum_public<filename>src/petuum_ps/server/server_thread_group.cpp
#include <petuum_ps/server/server_thread_group.hpp>
#include <petuum_ps/server/server_thread.hpp>
#include <petuum_ps/server/ssp_push_server_thread.hpp>
#include <petuum_ps/server/ssp_aggr_server_thread.hpp>
#include <petuum_ps/thread/context.hpp>
namespace petuum {
ServerThreadGroup::ServerThreadGroup(int32_t server_id_st_):
server_thread_vec_(GlobalContext::get_num_comm_channels_per_client()) {
pthread_barrier_init(&init_barrier_, NULL,
GlobalContext::get_num_comm_channels_per_client() + 1);
switch(GlobalContext::get_consistency_model()) {
case SSP:
{
int idx = 0;
for (auto &server_thread : server_thread_vec_) {
server_thread = new ServerThread(
GlobalContext::get_server_thread_id(
GlobalContext::get_client_id(), idx),
&init_barrier_);
++idx;
}
}
break;
case SSPPush:
{
int idx = 0;
for (auto &server_thread : server_thread_vec_) {
server_thread = new SSPPushServerThread(
GlobalContext::get_server_thread_id(
GlobalContext::get_client_id(), idx),
&init_barrier_);
++idx;
}
}
break;
case SSPAggr:
{
int idx = 0;
for (auto &server_thread : server_thread_vec_) {
server_thread = new SSPAggrServerThread(
GlobalContext::get_server_thread_id(
GlobalContext::get_client_id(), idx),
&init_barrier_);
++idx;
}
}
break;
default:
LOG(FATAL) << "Unknown consistency model "
<< GlobalContext::get_consistency_model();
}
}
ServerThreadGroup::~ServerThreadGroup() {
for (auto &server_thread : server_thread_vec_) {
delete server_thread;
}
}
void ServerThreadGroup::Start() {
for (const auto &server_thread : server_thread_vec_) {
server_thread->Start();
}
pthread_barrier_wait(&init_barrier_);
}
void ServerThreadGroup::ShutDown() {
for (const auto &server_thread : server_thread_vec_) {
server_thread->ShutDown();
}
}
}
| 1,045 |
631 | <gh_stars>100-1000
from __future__ import absolute_import
import socket
try:
_GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT
except AttributeError:
_GLOBAL_DEFAULT_TIMEOUT = object()
| 74 |
14,425 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;
import org.apache.hadoop.classification.InterfaceAudience;
/**
* Class for dealing with caching SASL client factories.
*/
@InterfaceAudience.LimitedPrivate({ "HDFS", "MapReduce" })
public class FastSaslClientFactory implements SaslClientFactory {
private final Map<String, List<SaslClientFactory>> factoryCache =
new HashMap<String, List<SaslClientFactory>>();
public FastSaslClientFactory(Map<String, ?> props) {
final Enumeration<SaslClientFactory> factories =
Sasl.getSaslClientFactories();
while (factories.hasMoreElements()) {
SaslClientFactory factory = factories.nextElement();
for (String mech : factory.getMechanismNames(props)) {
if (!factoryCache.containsKey(mech)) {
factoryCache.put(mech, new ArrayList<SaslClientFactory>());
}
factoryCache.get(mech).add(factory);
}
}
}
@Override
public String[] getMechanismNames(Map<String, ?> props) {
return factoryCache.keySet().toArray(new String[0]);
}
@Override
public SaslClient createSaslClient(String[] mechanisms,
String authorizationId, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
for (String mechanism : mechanisms) {
List<SaslClientFactory> factories = factoryCache.get(mechanism);
if (factories != null) {
for (SaslClientFactory factory : factories) {
SaslClient saslClient =
factory.createSaslClient(new String[] {mechanism},
authorizationId, protocol, serverName, props, cbh);
if (saslClient != null) {
return saslClient;
}
}
}
}
return null;
}
} | 989 |
730 | <reponame>belzecue/mifthtools<filename>other/exchangers/houdini/exchanger.py
def get_exchange_path():
return '' | 47 |
743 | <reponame>althink/hermes<filename>hermes-client/src/main/java/pl/allegro/tech/hermes/client/HermesClientBuilder.java
package pl.allegro.tech.hermes.client;
import pl.allegro.tech.hermes.client.metrics.MetricsMessageDeliveryListener;
import pl.allegro.tech.hermes.client.metrics.MetricsProvider;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class HermesClientBuilder {
private HermesSender sender;
private URI uri = URI.create("http://localhost:8080");
private final Map<String, String> defaultHeaders = new HashMap<>();
private int retries = 3;
private Predicate<HermesResponse> retryCondition = new HermesClientBasicRetryCondition();
private long retrySleepInMillis = 100;
private long maxRetrySleepInMillis = 300;
private Supplier<ScheduledExecutorService> schedulerFactory = Executors::newSingleThreadScheduledExecutor;
private Optional<MetricsProvider> metrics = Optional.empty();
public HermesClientBuilder(HermesSender sender) {
this.sender = sender;
this.defaultHeaders.put(HermesMessage.CONTENT_TYPE_HEADER, HermesMessage.APPLICATION_JSON);
}
public static HermesClientBuilder hermesClient(HermesSender sender) {
return new HermesClientBuilder(sender);
}
public HermesClient build() {
HermesClient hermesClient = new HermesClient(sender, uri, defaultHeaders, retries, retryCondition,
retrySleepInMillis, maxRetrySleepInMillis, schedulerFactory.get());
metrics.ifPresent((metricsProvider) -> {
hermesClient.addMessageDeliveryListener(new MetricsMessageDeliveryListener(metricsProvider));
});
return hermesClient;
}
public HermesClientBuilder withURI(URI uri) {
this.uri = uri;
return this;
}
public HermesClientBuilder withMetrics(MetricsProvider metrics) {
this.metrics = Optional.of(metrics);
return this;
}
public HermesClientBuilder withDefaultContentType(String defaultContentType) {
defaultHeaders.put(HermesMessage.CONTENT_TYPE_HEADER, defaultContentType);
return this;
}
public HermesClientBuilder withDefaultHeaderValue(String header, String value) {
defaultHeaders.put(header, value);
return this;
}
public HermesClientBuilder withRetries(int retries) {
this.retries = retries;
return this;
}
public HermesClientBuilder withRetries(int retries, Predicate<HermesResponse> retryCondition) {
this.retryCondition = retryCondition;
return withRetries(retries);
}
public HermesClientBuilder withRetrySleep(long retrySleepInMillis) {
this.retrySleepInMillis = retrySleepInMillis;
return this;
}
public HermesClientBuilder withRetrySleep(long retrySleepInMillis, long maxRetrySleepInMillis) {
this.retrySleepInMillis = retrySleepInMillis;
this.maxRetrySleepInMillis = maxRetrySleepInMillis;
return this;
}
public HermesClientBuilder withScheduler(ScheduledExecutorService scheduler) {
this.schedulerFactory = () -> scheduler;
return this;
}
}
| 1,197 |
412 | /*
* Jigasi, the JItsi GAteway to SIP.
*
* Copyright @ 2017 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jigasi.rest;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.*;
import org.jitsi.jigasi.*;
import org.jitsi.jigasi.transcription.*;
import org.jitsi.rest.*;
import org.osgi.framework.*;
/**
* Activate a jetty instance which is able to serve
* {@link org.jitsi.jigasi.transcription.Transcript} which are locally stored
* with a {@link org.jitsi.jigasi.transcription.LocalTxtTranscriptHandler} or
* {@link org.jitsi.jigasi.transcription.LocalJsonTranscriptHandler}
*
* @author <NAME>
*/
public class TranscriptServerBundleActivator
extends AbstractJettyBundleActivator
{
/**
* The prefix of the property names for the Jetty instance managed by
* this {@link AbstractJettyBundleActivator}.
*/
public static final String JETTY_PROPERTY_PREFIX
= "org.jitsi.jigasi.transcription";
/**
* Create a new Bundle which serves locally stored
* {@link org.jitsi.jigasi.transcription.Transcript}s formatted by a
* {@link org.jitsi.jigasi.transcription.TranscriptPublisher}
*/
public TranscriptServerBundleActivator()
{
super(JETTY_PROPERTY_PREFIX);
}
/**
* {@inheritDoc}
*/
@Override
protected int getDefaultPort()
{
return -1;
}
/**
* {@inheritDoc}
*/
@Override
protected int getDefaultTlsPort()
{
return -1;
}
/**
* {@inheritDoc}
*/
@Override
protected Handler initializeHandlerList(BundleContext bundleContext,
Server server)
throws Exception
{
ResourceHandler fileHandler = new ResourceHandler();
fileHandler.setDirectoriesListed(false);
fileHandler.setResourceBase(
AbstractTranscriptPublisher.getLogDirPath());
return fileHandler;
}
}
| 935 |
6,132 | <reponame>mikenawrocki/angr<gh_stars>1000+
import os
import time
import angr
from angr import options as so
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../binaries')
p = angr.Project(os.path.join(test_location, 'tests', 'x86_64', 'perf_unicorn_0'))
s_unicorn = p.factory.entry_state(add_options=so.unicorn | {so.STRICT_PAGE_ACCESS}, remove_options={so.LAZY_SOLVES}) # unicorn
def main():
sm_unicorn = p.factory.simulation_manager(s_unicorn)
sm_unicorn.run()
if __name__ == "__main__":
import logging
logging.getLogger('angr.state_plugins.unicorn_engine').setLevel('DEBUG')
logging.getLogger('angr.engines.unicorn').setLevel('DEBUG')
tstart = time.time()
main()
tend = time.time()
print('Elapsed: %f sec' % (tend - tstart))
| 324 |
14,668 | <filename>ash/wm/desks/expanded_desks_bar_button.h
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_WM_DESKS_EXPANDED_DESKS_BAR_BUTTON_H_
#define ASH_WM_DESKS_EXPANDED_DESKS_BAR_BUTTON_H_
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/view.h"
namespace gfx {
struct VectorIcon;
} // namespace gfx
namespace views {
class Label;
} // namespace views
namespace ash {
class DeskButtonBase;
class DesksBarView;
// A desk button view in the expanded desks bar. It includes the
// InnerExpandedDesksBarButton and a name label below, which has the same style
// as a DeskMiniView, but the name label is not changeable and not focusable.
class ExpandedDesksBarButton : public views::View {
public:
METADATA_HEADER(ExpandedDesksBarButton);
ExpandedDesksBarButton(DesksBarView* bar_view,
const gfx::VectorIcon* button_icon,
const std::u16string& button_label,
bool initially_enabled,
base::RepeatingClosure callback);
ExpandedDesksBarButton(const ExpandedDesksBarButton&) = delete;
ExpandedDesksBarButton& operator=(const ExpandedDesksBarButton&) = delete;
~ExpandedDesksBarButton() override = default;
const gfx::VectorIcon* button_icon() const { return button_icon_; }
DeskButtonBase* inner_button() { return inner_button_; }
void set_active(bool active) { active_ = active; }
// Updates `inner_button_`'s state on current desks state.
void SetButtonState(bool enabled);
// Updates the `label_`'s color on DesksController::CanCreateDesks.
void UpdateLabelColor(bool enabled);
bool IsPointOnButton(const gfx::Point& screen_location) const;
// Updates the border color of the ExpandedDesksBarButton based on
// the dragged item's position and `active_`.
void UpdateBorderColor() const;
// views::View:
void Layout() override;
private:
DesksBarView* const bar_view_; // Not owned.
const gfx::VectorIcon* const button_icon_;
const std::u16string button_label_;
DeskButtonBase* inner_button_;
views::Label* label_;
// If `active_` is true, then the border of `inner_button_` will be
// highlighted if it's not already focused.
bool active_ = false;
};
} // namespace ash
#endif // ASH_WM_DESKS_EXPANDED_DESKS_BAR_BUTTON_H_
| 844 |
831 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.uibuilder.model;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.ide.common.resources.configuration.LayoutDirectionQualifier;
import com.android.resources.LayoutDirection;
import com.android.tools.idea.configurations.Configuration;
import junit.framework.TestCase;
import static com.android.tools.idea.uibuilder.model.TextDirection.LEFT_TO_RIGHT;
import static com.android.tools.idea.uibuilder.model.TextDirection.RIGHT_TO_LEFT;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TextDirectionTest extends TestCase {
public void test() {
assertSame(LEFT_TO_RIGHT, TextDirection.fromConfiguration(null));
Configuration configuration = mock(Configuration.class);
FolderConfiguration folderConfig = new FolderConfiguration();
when(configuration.getFullConfig()).thenReturn(folderConfig);
// Nothing specified
assertSame(LEFT_TO_RIGHT, TextDirection.fromConfiguration(configuration));
// LTR specified
folderConfig.setLayoutDirectionQualifier(new LayoutDirectionQualifier(LayoutDirection.LTR));
assertSame(LEFT_TO_RIGHT, TextDirection.fromConfiguration(configuration));
// RTL specified
folderConfig.setLayoutDirectionQualifier(new LayoutDirectionQualifier(LayoutDirection.RTL));
assertSame(RIGHT_TO_LEFT, TextDirection.fromConfiguration(configuration));
assertSame(SegmentType.START, LEFT_TO_RIGHT.getLeftSegment());
assertSame(SegmentType.END, RIGHT_TO_LEFT.getLeftSegment());
assertSame(SegmentType.END, LEFT_TO_RIGHT.getRightSegment());
assertSame(SegmentType.START, RIGHT_TO_LEFT.getRightSegment());
assertTrue(LEFT_TO_RIGHT.isLeftSegment(SegmentType.START));
assertFalse(LEFT_TO_RIGHT.isLeftSegment(SegmentType.END));
assertTrue(RIGHT_TO_LEFT.isLeftSegment(SegmentType.END));
assertFalse(RIGHT_TO_LEFT.isLeftSegment(SegmentType.START));
}
} | 807 |
1,953 | <reponame>yohannrub/grails-core<gh_stars>1000+
/*
* Copyright 2004-2005 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.grails.compiler.injection;
import grails.artefact.Enhanced;
import grails.compiler.ast.GrailsArtefactClassInjector;
import grails.util.GrailsNameUtils;
import groovy.lang.Closure;
import groovy.lang.MissingMethodException;
import groovy.transform.CompileStatic;
import groovy.transform.TypeChecked;
import groovy.transform.TypeCheckingMode;
import org.apache.groovy.ast.tools.AnnotatedNodeUtils;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.*;
import org.codehaus.groovy.classgen.VariableScopeVisitor;
import org.codehaus.groovy.control.Janitor;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.runtime.MetaClassHelper;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.transform.sc.StaticCompileTransformation;
import org.codehaus.groovy.transform.trait.Traits;
import org.grails.datastore.mapping.model.config.GormProperties;
import org.grails.io.support.FileSystemResource;
import org.grails.io.support.Resource;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.*;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
/**
* Helper methods for working with Groovy AST trees.
*
* @author <NAME>
* @since 0.3
*/
public class GrailsASTUtils {
public static final String DOMAIN_DIR = "domain";
public static final String GRAILS_APP_DIR = "grails-app";
public static final String METHOD_MISSING_METHOD_NAME = "methodMissing";
public static final String STATIC_METHOD_MISSING_METHOD_NAME = "$static_methodMissing";
public static final Token EQUALS_OPERATOR = Token.newSymbol("==", 0, 0);
public static final Token LOGICAL_AND_OPERATOR = Token.newSymbol("&&", 0, 0);
public static final Token NOT_EQUALS_OPERATOR = Token.newSymbol("!=", 0, 0);
public static final String OBJECT_CLASS = "java.lang.Object";
private static final ClassNode ENHANCED_CLASS_NODE = new ClassNode(Enhanced.class);
public static final ClassNode MISSING_METHOD_EXCEPTION = new ClassNode(MissingMethodException.class);
public static final ConstantExpression NULL_EXPRESSION = new ConstantExpression(null);
public static final Token ASSIGNMENT_OPERATOR = Token.newSymbol(Types.ASSIGNMENT_OPERATOR, 0, 0);
public static final ClassNode OBJECT_CLASS_NODE = new ClassNode(Object.class).getPlainNodeReference();
public static final ClassNode VOID_CLASS_NODE = ClassHelper.VOID_TYPE;
public static final ClassNode INTEGER_CLASS_NODE = new ClassNode(Integer.class).getPlainNodeReference();
private static final ClassNode COMPILESTATIC_CLASS_NODE = ClassHelper.make(CompileStatic.class);
private static final ClassNode TYPECHECKINGMODE_CLASS_NODE = ClassHelper.make(TypeCheckingMode.class);
public static final Parameter[] ZERO_PARAMETERS = new Parameter[0];
public static final ArgumentListExpression ZERO_ARGUMENTS = new ArgumentListExpression();
public static void warning(final SourceUnit sourceUnit, final ASTNode node, final String warningMessage) {
final String sample = sourceUnit.getSample(node.getLineNumber(), node.getColumnNumber(), new Janitor());
System.err.println("WARNING: " + warningMessage + "\n\n" + sample);
}
/**
* Generates a fatal compilation error.
*
* @param sourceUnit the SourceUnit
* @param astNode the ASTNode which caused the error
* @param message The error message
*/
public static void error(final SourceUnit sourceUnit, final ASTNode astNode, final String message) {
error(sourceUnit, astNode, message, true);
}
/**
* Generates a fatal compilation error.
*
* @param sourceUnit the SourceUnit
* @param astNode the ASTNode which caused the error
* @param message The error message
* @param fatal indicates if this is a fatal error
*/
public static void error(final SourceUnit sourceUnit, final ASTNode astNode, final String message, final boolean fatal) {
final SyntaxException syntaxException = new SyntaxException(message, astNode.getLineNumber(), astNode.getColumnNumber());
final SyntaxErrorMessage syntaxErrorMessage = new SyntaxErrorMessage(syntaxException, sourceUnit);
sourceUnit.getErrorCollector().addError(syntaxErrorMessage, fatal);
}
/**
* Returns whether a classNode has the specified property or not
*
* @param classNode The ClassNode
* @param propertyName The name of the property
* @return true if the property exists in the ClassNode
*/
public static boolean hasProperty(ClassNode classNode, String propertyName) {
if (classNode == null || !StringUtils.hasText(propertyName)) {
return false;
}
final MethodNode method = classNode.getMethod(GrailsNameUtils.getGetterName(propertyName), Parameter.EMPTY_ARRAY);
if (method != null) return true;
// check read-only field with setter
if( classNode.getField(propertyName) != null && !classNode.getMethods(GrailsNameUtils.getSetterName(propertyName)).isEmpty()) {
return true;
}
for (PropertyNode pn : classNode.getProperties()) {
if (pn.getName().equals(propertyName) && !pn.isPrivate()) {
return true;
}
}
return false;
}
public static boolean hasOrInheritsProperty(ClassNode classNode, String propertyName) {
if (hasProperty(classNode, propertyName)) {
return true;
}
ClassNode parent = classNode.getSuperClass();
while (parent != null && !getFullName(parent).equals("java.lang.Object")) {
if (hasProperty(parent, propertyName)) {
return true;
}
parent = parent.getSuperClass();
}
return false;
}
/**
* Tests whether the ClasNode implements the specified method name.
*
* @param classNode The ClassNode
* @param methodName The method name
* @return true if it does implement the method
*/
public static boolean implementsZeroArgMethod(ClassNode classNode, String methodName) {
MethodNode method = classNode.getDeclaredMethod(methodName, Parameter.EMPTY_ARRAY);
return method != null && (method.isPublic() || method.isProtected()) && !method.isAbstract();
}
@SuppressWarnings("rawtypes")
public static boolean implementsOrInheritsZeroArgMethod(ClassNode classNode, String methodName, List ignoreClasses) {
if (implementsZeroArgMethod(classNode, methodName)) {
return true;
}
ClassNode parent = classNode.getSuperClass();
while (parent != null && !getFullName(parent).equals("java.lang.Object")) {
if (!ignoreClasses.contains(parent) && implementsZeroArgMethod(parent, methodName)) {
return true;
}
parent = parent.getSuperClass();
}
return false;
}
/**
* Gets the full name of a ClassNode.
*
* @param classNode The class node
* @return The full name
*/
public static String getFullName(ClassNode classNode) {
return classNode.getName();
}
public static ClassNode getFurthestParent(ClassNode classNode) {
ClassNode parent = classNode.getSuperClass();
while (parent != null && !getFullName(parent).equals("java.lang.Object")) {
classNode = parent;
parent = parent.getSuperClass();
}
return classNode;
}
public static ClassNode getFurthestUnresolvedParent(ClassNode classNode) {
ClassNode parent = classNode.getSuperClass();
while (parent != null && !getFullName(parent).equals("java.lang.Object") && !parent.isResolved()) {
classNode = parent;
parent = parent.getSuperClass();
}
return classNode;
}
/**
* Adds a delegate method to the target class node where the first argument
* is to the delegate method is 'this'. In other words a method such as
* foo(Object instance, String bar) would be added with a signature of foo(String)
* and 'this' is passed to the delegate instance
*
* @param classNode The class node
* @param delegate The expression that looks up the delegate
* @param declaredMethod The declared method
* @return The added method node or null if it couldn't be added
*/
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod) {
return addDelegateInstanceMethod(classNode, delegate, declaredMethod, null, true);
}
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation) {
return addDelegateInstanceMethod(classNode, delegate, declaredMethod, markerAnnotation, true);
}
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, boolean thisAsFirstArgument) {
return addDelegateInstanceMethod(classNode,delegate,declaredMethod, null, thisAsFirstArgument);
}
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation, boolean thisAsFirstArgument) {
return addDelegateInstanceMethod(classNode,delegate,declaredMethod, markerAnnotation, thisAsFirstArgument, null, false);
}
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders) {
return addDelegateInstanceMethod(classNode, delegate, declaredMethod, markerAnnotation, thisAsFirstArgument, genericsPlaceholders, false);
}
/**
* Adds a delegate method to the target class node where the first argument
* is to the delegate method is 'this'. In other words a method such as
* foo(Object instance, String bar) would be added with a signature of foo(String)
* and 'this' is passed to the delegate instance
*
* @param classNode The class node
* @param delegate The expression that looks up the delegate
* @param declaredMethod The declared method
* @param thisAsFirstArgument Whether 'this' should be passed as the first argument to the method
* @return The added method node or null if it couldn't be added
*/
public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) {
Parameter[] parameterTypes = thisAsFirstArgument ? getRemainingParameterTypes(declaredMethod.getParameters()) : declaredMethod.getParameters();
String methodName = declaredMethod.getName();
if (classNode.hasDeclaredMethod(methodName, copyParameters(parameterTypes, genericsPlaceholders))) {
return null;
}
ClassNode returnType = declaredMethod.getReturnType();
String propertyName = !returnType.isPrimaryClassNode() ? GrailsNameUtils.getPropertyForGetter(methodName, returnType.getTypeClass()) : GrailsNameUtils.getPropertyForGetter(methodName);
if (propertyName != null && parameterTypes.length == 0 && classNode.hasProperty(propertyName)) {
return null;
}
propertyName = GrailsNameUtils.getPropertyForSetter(methodName);
if (propertyName != null && parameterTypes.length == 1 && classNode.hasProperty(propertyName)) {
return null;
}
BlockStatement methodBody = new BlockStatement();
ArgumentListExpression arguments = createArgumentListFromParameters(parameterTypes, thisAsFirstArgument, genericsPlaceholders);
returnType = replaceGenericsPlaceholders(returnType, genericsPlaceholders);
MethodCallExpression methodCallExpression = new MethodCallExpression(delegate, methodName, arguments);
methodCallExpression.setMethodTarget(declaredMethod);
if(!noNullCheck) {
ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, declaredMethod);
VariableExpression apiVar = addApiVariableDeclaration(delegate, declaredMethod, methodBody);
IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar, missingMethodException);
methodBody.addStatement(ifStatement);
} else {
methodBody.addStatement(new ExpressionStatement(methodCallExpression));
}
MethodNode methodNode = new MethodNode(methodName,
Modifier.PUBLIC, returnType, copyParameters(parameterTypes, genericsPlaceholders),
GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY, methodBody);
copyAnnotations(declaredMethod, methodNode);
if(shouldAddMarkerAnnotation(markerAnnotation, methodNode)) {
methodNode.addAnnotation(markerAnnotation);
}
classNode.addMethod(methodNode);
AnnotatedNodeUtils.markAsGenerated(classNode, methodNode);
return methodNode;
}
private static boolean shouldAddMarkerAnnotation(AnnotationNode markerAnnotation, MethodNode methodNode) {
return markerAnnotation != null && methodNode.getAnnotations(markerAnnotation.getClassNode()).isEmpty();
}
private static IfStatement createIfElseStatementForApiMethodCall(MethodCallExpression methodCallExpression, VariableExpression apiVar, ThrowStatement missingMethodException) {
BlockStatement ifBlock = new BlockStatement();
ifBlock.addStatement(missingMethodException);
BlockStatement elseBlock = new BlockStatement();
elseBlock.addStatement(new ExpressionStatement(methodCallExpression));
return new IfStatement(new BooleanExpression(new BinaryExpression(apiVar, EQUALS_OPERATOR, NULL_EXPRESSION)),ifBlock,elseBlock);
}
private static VariableExpression addApiVariableDeclaration(Expression delegate, MethodNode declaredMethod, BlockStatement methodBody) {
VariableExpression apiVar = new VariableExpression("$api_" + declaredMethod.getName(), delegate.getType());
DeclarationExpression de = new DeclarationExpression(apiVar, ASSIGNMENT_OPERATOR, delegate);
methodBody.addStatement(new ExpressionStatement(de));
return apiVar;
}
private static ThrowStatement createMissingMethodThrowable(ClassNode classNode, MethodNode declaredMethodNode) {
ArgumentListExpression exceptionArgs = new ArgumentListExpression();
exceptionArgs.addExpression(new ConstantExpression(declaredMethodNode.getName()));
exceptionArgs.addExpression(new ClassExpression(classNode));
return new ThrowStatement(new ConstructorCallExpression(MISSING_METHOD_EXCEPTION, exceptionArgs));
}
/**
* Creates an argument list from the given parameter types.
*
* @param parameterTypes The parameter types
* @param thisAsFirstArgument Whether to include a reference to 'this' as the first argument
* @param genericsPlaceholders
*
* @return the arguments
*/
public static ArgumentListExpression createArgumentListFromParameters(Parameter[] parameterTypes, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders) {
ArgumentListExpression arguments = new ArgumentListExpression();
if (thisAsFirstArgument) {
arguments.addExpression(new VariableExpression("this"));
}
for (Parameter parameterType : parameterTypes) {
arguments.addExpression(new VariableExpression(parameterType.getName(), replaceGenericsPlaceholders(parameterType.getType(), genericsPlaceholders)));
}
return arguments;
}
/**
* Gets the remaining parameters excluding the first parameter in the given list
*
* @param parameters The parameters
* @return A new array with the first parameter removed
*/
public static Parameter[] getRemainingParameterTypes(Parameter[] parameters) {
if (parameters.length == 0) {
return GrailsArtefactClassInjector.ZERO_PARAMETERS;
}
Parameter[] newParameters = new Parameter[parameters.length - 1];
System.arraycopy(parameters, 1, newParameters, 0, parameters.length - 1);
return newParameters;
}
/**
* Adds a static method call to given class node that delegates to the given method
*
* @param classNode The class node
* @param delegateMethod The delegate method
* @return The added method node or null if it couldn't be added
*/
public static MethodNode addDelegateStaticMethod(ClassNode classNode, MethodNode delegateMethod) {
ClassExpression classExpression = new ClassExpression(delegateMethod.getDeclaringClass());
return addDelegateStaticMethod(classExpression, classNode, delegateMethod);
}
/**
* Adds a static method to the given class node that delegates to the given method
* and resolves the object to invoke the method on from the given expression.
*
* @param expression The expression
* @param classNode The class node
* @param delegateMethod The delegate method
* @return The added method node or null if it couldn't be added
*/
public static MethodNode addDelegateStaticMethod(Expression expression, ClassNode classNode, MethodNode delegateMethod) {
return addDelegateStaticMethod(expression, classNode, delegateMethod, null, null, true);
}
/**
* Adds a static method to the given class node that delegates to the given method
* and resolves the object to invoke the method on from the given expression.
*
* @param delegate The expression
* @param classNode The class node
* @param delegateMethod The delegate method
* @param markerAnnotation A marker annotation to be added to all methods
* @return The added method node or null if it couldn't be added
*/
public static MethodNode addDelegateStaticMethod(Expression delegate, ClassNode classNode, MethodNode delegateMethod, AnnotationNode markerAnnotation, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) {
Parameter[] parameterTypes = delegateMethod.getParameters();
String declaredMethodName = delegateMethod.getName();
if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) {
declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME;
}
if (classNode.hasDeclaredMethod(declaredMethodName, copyParameters(parameterTypes, genericsPlaceholders))) {
return null;
}
BlockStatement methodBody = new BlockStatement();
ArgumentListExpression arguments = createArgumentListFromParameters(parameterTypes, false, genericsPlaceholders);
MethodCallExpression methodCallExpression = new MethodCallExpression(
delegate, delegateMethod.getName(), arguments);
methodCallExpression.setMethodTarget(delegateMethod);
if(!noNullCheck && !(delegate instanceof ClassExpression)) {
ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod);
VariableExpression apiVar = addApiVariableDeclaration(delegate, delegateMethod, methodBody);
IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar, missingMethodException);
methodBody.addStatement(ifStatement);
} else {
methodBody.addStatement(new ExpressionStatement(methodCallExpression));
}
ClassNode returnType = replaceGenericsPlaceholders(delegateMethod.getReturnType(), genericsPlaceholders);
MethodNode methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType,
copyParameters(parameterTypes, genericsPlaceholders), GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY,
methodBody);
copyAnnotations(delegateMethod, methodNode);
if (shouldAddMarkerAnnotation(markerAnnotation, methodNode)) {
methodNode.addAnnotation(markerAnnotation);
}
classNode.addMethod(methodNode);
return AnnotatedNodeUtils.markAsGenerated(classNode, methodNode);
}
/**
* Adds or modifies an existing constructor to delegate to the
* given static constructor method for initialization logic.
*
* @param classNode The class node
* @param constructorMethod The constructor static method
*/
public static ConstructorNode addDelegateConstructor(ClassNode classNode, MethodNode constructorMethod, Map<String, ClassNode> genericsPlaceholders) {
BlockStatement constructorBody = new BlockStatement();
Parameter[] constructorParams = getRemainingParameterTypes(constructorMethod.getParameters());
ArgumentListExpression arguments = createArgumentListFromParameters(constructorParams, true, genericsPlaceholders);
MethodCallExpression constructCallExpression = new MethodCallExpression(
new ClassExpression(constructorMethod.getDeclaringClass()), "initialize", arguments);
constructCallExpression.setMethodTarget(constructorMethod);
ExpressionStatement constructorInitExpression = new ExpressionStatement(constructCallExpression);
if (constructorParams.length > 0) {
constructorBody.addStatement(new ExpressionStatement(new ConstructorCallExpression(ClassNode.THIS, GrailsArtefactClassInjector.ZERO_ARGS)));
}
constructorBody.addStatement(constructorInitExpression);
if (constructorParams.length == 0) {
// handle default constructor
ConstructorNode constructorNode = getDefaultConstructor(classNode);
if (constructorNode != null) {
List<AnnotationNode> annotations = constructorNode.getAnnotations(new ClassNode(GrailsDelegatingConstructor.class));
if (annotations.size() == 0) {
Statement existingBodyCode = constructorNode.getCode();
if (existingBodyCode instanceof BlockStatement) {
((BlockStatement) existingBodyCode).addStatement(constructorInitExpression);
}
else {
constructorNode.setCode(constructorBody);
}
}
} else {
constructorNode = new ConstructorNode(Modifier.PUBLIC, constructorBody);
classNode.addConstructor(constructorNode);
AnnotatedNodeUtils.markAsGenerated(classNode, constructorNode);
}
constructorNode.addAnnotation(new AnnotationNode(new ClassNode(GrailsDelegatingConstructor.class)));
return constructorNode;
}
else {
// create new constructor, restoring default constructor if there is none
ConstructorNode cn = findConstructor(classNode, constructorParams);
if (cn == null) {
cn = new ConstructorNode(Modifier.PUBLIC, copyParameters(constructorParams, genericsPlaceholders), null, constructorBody);
classNode.addConstructor(cn);
AnnotatedNodeUtils.markAsGenerated(classNode, cn);
}
else {
List<AnnotationNode> annotations = cn.getAnnotations(new ClassNode(GrailsDelegatingConstructor.class));
if (annotations.size() == 0) {
Statement code = cn.getCode();
constructorBody.addStatement(code);
cn.setCode(constructorBody);
}
}
ConstructorNode defaultConstructor = getDefaultConstructor(classNode);
if (defaultConstructor == null) {
// add empty
ConstructorNode constructorNode = new ConstructorNode(Modifier.PUBLIC, new BlockStatement());
classNode.addConstructor(constructorNode);
AnnotatedNodeUtils.markAsGenerated(classNode, constructorNode);
}
cn.addAnnotation(new AnnotationNode(new ClassNode(GrailsDelegatingConstructor.class)));
return cn;
}
}
/**
* Finds a constructor for the given class node and parameter types
*
* @param classNode The class node
* @param constructorParams The parameter types
* @return The located constructor or null
*/
public static ConstructorNode findConstructor(ClassNode classNode,Parameter[] constructorParams) {
List<ConstructorNode> declaredConstructors = classNode.getDeclaredConstructors();
for (ConstructorNode declaredConstructor : declaredConstructors) {
if (parametersEqual(constructorParams, declaredConstructor.getParameters())) {
return declaredConstructor;
}
}
return null;
}
/**
* @return true if the two arrays are of the same size and have the same contents
*/
public static boolean parametersEqual(Parameter[] a, Parameter[] b) {
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].getType().equals(b[i].getType())) {
return false;
}
}
return true;
}
/**
* Obtains the default constructor for the given class node.
*
* @param classNode The class node
* @return The default constructor or null if there isn't one
*/
public static ConstructorNode getDefaultConstructor(ClassNode classNode) {
for (ConstructorNode cons : classNode.getDeclaredConstructors()) {
if (cons.getParameters().length == 0) {
return cons;
}
}
return null;
}
public static Parameter[] copyParameters(Parameter[] parameterTypes) {
return copyParameters(parameterTypes, null);
}
public static Parameter[] copyParameters(Parameter[] parameterTypes, Map<String, ClassNode> genericsPlaceholders) {
Parameter[] newParameterTypes = new Parameter[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
Parameter parameterType = parameterTypes[i];
Parameter newParameter = new Parameter(replaceGenericsPlaceholders(parameterType.getType(), genericsPlaceholders), parameterType.getName(), parameterType.getInitialExpression());
copyAnnotations(parameterType, newParameter);
newParameterTypes[i] = newParameter;
}
return newParameterTypes;
}
private static final Map<String, ClassNode> emptyGenericsPlaceHoldersMap = Collections.emptyMap();
public static ClassNode nonGeneric(ClassNode type) {
return replaceGenericsPlaceholders(type, emptyGenericsPlaceHoldersMap);
}
@SuppressWarnings("unchecked")
public static ClassNode nonGeneric(ClassNode type, final ClassNode wildcardReplacement) {
return replaceGenericsPlaceholders(type, emptyGenericsPlaceHoldersMap, wildcardReplacement);
}
public static ClassNode replaceGenericsPlaceholders(ClassNode type, Map<String, ClassNode> genericsPlaceholders) {
return replaceGenericsPlaceholders(type, genericsPlaceholders, null);
}
public static ClassNode replaceGenericsPlaceholders(ClassNode type, Map<String, ClassNode> genericsPlaceholders, ClassNode defaultPlaceholder) {
if (type.isArray()) {
return replaceGenericsPlaceholders(type.getComponentType(), genericsPlaceholders).makeArray();
}
if (!type.isUsingGenerics() && !type.isRedirectNode()) {
return type.getPlainNodeReference();
}
if(type.isGenericsPlaceHolder() && genericsPlaceholders != null) {
final ClassNode placeHolderType;
if(genericsPlaceholders.containsKey(type.getUnresolvedName())) {
placeHolderType = genericsPlaceholders.get(type.getUnresolvedName());
} else {
placeHolderType = defaultPlaceholder;
}
if(placeHolderType != null) {
return placeHolderType.getPlainNodeReference();
} else {
return ClassHelper.make(Object.class).getPlainNodeReference();
}
}
final ClassNode nonGen = type.getPlainNodeReference();
if("java.lang.Object".equals(type.getName())) {
nonGen.setGenericsPlaceHolder(false);
nonGen.setGenericsTypes(null);
nonGen.setUsingGenerics(false);
} else {
if(type.isUsingGenerics()) {
GenericsType[] parameterized = type.getGenericsTypes();
if (parameterized != null && parameterized.length > 0) {
GenericsType[] copiedGenericsTypes = new GenericsType[parameterized.length];
for (int i = 0; i < parameterized.length; i++) {
GenericsType parameterizedType = parameterized[i];
GenericsType copiedGenericsType = null;
if (parameterizedType.isPlaceholder() && genericsPlaceholders != null) {
ClassNode placeHolderType = genericsPlaceholders.get(parameterizedType.getName());
if(placeHolderType != null) {
copiedGenericsType = new GenericsType(placeHolderType.getPlainNodeReference());
} else {
copiedGenericsType = new GenericsType(ClassHelper.make(Object.class).getPlainNodeReference());
}
} else {
copiedGenericsType = new GenericsType(replaceGenericsPlaceholders(parameterizedType.getType(), genericsPlaceholders));
}
copiedGenericsTypes[i] = copiedGenericsType;
}
nonGen.setGenericsTypes(copiedGenericsTypes);
}
}
}
return nonGen;
}
public static boolean isCandidateInstanceMethod(ClassNode classNode, MethodNode declaredMethod) {
Parameter[] parameterTypes = declaredMethod.getParameters();
return isCandidateMethod(declaredMethod) && parameterTypes != null &&
parameterTypes.length > 0 && isAssignableFrom(parameterTypes[0].getType(), classNode);
}
/**
* Determines if the class or interface represented by the superClass
* argument is either the same as, or is a superclass or superinterface of,
* the class or interface represented by the specified subClass parameter.
*
* @param superClass The super class to check
* @param childClass The sub class the check
* @return true if the childClass is either equal to or a sub class of the specified superClass
*/
public static boolean isAssignableFrom(ClassNode superClass, ClassNode childClass) {
ClassNode currentSuper = childClass;
while (currentSuper != null) {
if (currentSuper.equals(superClass)) {
return true;
}
currentSuper = currentSuper.getSuperClass();
}
return false;
}
public static boolean isSubclassOfOrImplementsInterface(ClassNode childClass, ClassNode superClass) {
String superClassName = superClass.getName();
return isSubclassOfOrImplementsInterface(childClass, superClassName);
}
public static boolean isSubclassOfOrImplementsInterface(ClassNode childClass, String superClassName) {
return isSubclassOf(childClass, superClassName) || implementsInterface(childClass, superClassName);
}
private static boolean implementsInterface(ClassNode classNode, String interfaceName) {
ClassNode currentClassNode = classNode;
while (currentClassNode != null && !currentClassNode.getName().equals(OBJECT_CLASS)) {
ClassNode[] interfaces = currentClassNode.getInterfaces();
if (implementsInterfaceInternal(interfaces, interfaceName)) return true;
currentClassNode = currentClassNode.getSuperClass();
}
return false;
}
private static boolean implementsInterfaceInternal(ClassNode[] interfaces, String interfaceName) {
for (ClassNode anInterface : interfaces) {
if(anInterface.getName().equals(interfaceName)) {
return true;
}
ClassNode[] childInterfaces = anInterface.getInterfaces();
if(childInterfaces != null && childInterfaces.length>0) {
return implementsInterfaceInternal(childInterfaces,interfaceName );
}
}
return false;
}
public static boolean isCandidateMethod(MethodNode declaredMethod) {
return !declaredMethod.isSynthetic() &&
!declaredMethod.getName().contains("$")
&& Modifier.isPublic(declaredMethod.getModifiers()) &&
!Modifier.isAbstract(declaredMethod.getModifiers());
}
public static boolean isConstructorMethod(MethodNode declaredMethod) {
return declaredMethod.isStatic() && declaredMethod.isPublic() &&
declaredMethod.getName().equals("initialize") &&
declaredMethod.getParameters().length >= 1 &&
declaredMethod.getParameters()[0].getType().equals(AbstractGrailsArtefactTransformer.OBJECT_CLASS);
}
public static boolean isDomainClass(final ClassNode classNode, final SourceUnit sourceNode) {
@SuppressWarnings("unchecked")
boolean isDomainClass = GrailsASTUtils.hasAnyAnnotations(classNode,
grails.persistence.Entity.class,
javax.persistence.Entity.class);
if (!isDomainClass && sourceNode != null) {
final String sourcePath = sourceNode.getName();
final String grailsAppDirToLookFor = File.separator +
GRAILS_APP_DIR + File.separator;
final int indexOfGrailsAppDir = sourcePath.lastIndexOf(grailsAppDirToLookFor);
if(indexOfGrailsAppDir >= 0) {
final String pathToGrailsAppDir =
sourcePath.substring(0, indexOfGrailsAppDir +
grailsAppDirToLookFor.length());
final String pathToDomainDir = pathToGrailsAppDir +
DOMAIN_DIR + File.separator;
final String className = classNode.getName();
final String relativePathToDomainSourceFile =
className.replace('.', File.separatorChar) + ".groovy";
final String pathToDomainSourceFile = pathToDomainDir +
relativePathToDomainSourceFile;
isDomainClass = new File(pathToDomainSourceFile).exists();
}
}
return isDomainClass;
}
public static void addDelegateInstanceMethods(ClassNode classNode, ClassNode delegateNode, Expression delegateInstance) {
addDelegateInstanceMethods(classNode, delegateNode, delegateInstance, null);
}
public static void addDelegateInstanceMethods(ClassNode classNode, ClassNode delegateNode, Expression delegateInstance, Map<String, ClassNode> genericsPlaceholders) {
addDelegateInstanceMethods(classNode, classNode, delegateNode, delegateInstance, genericsPlaceholders, false, false);
}
public static void addDelegateInstanceMethods(ClassNode supportedSuperType, ClassNode classNode, ClassNode delegateNode, Expression delegateInstance) {
addDelegateInstanceMethods(supportedSuperType, classNode, delegateNode, delegateInstance, null, false, false);
}
public static void addDelegateInstanceMethods(ClassNode supportedSuperType, ClassNode classNode, ClassNode delegateNode, Expression delegateInstance, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck, boolean addCompileStatic) {
while (!delegateNode.equals(AbstractGrailsArtefactTransformer.OBJECT_CLASS)) {
List<MethodNode> declaredMethods = delegateNode.getMethods();
for (MethodNode declaredMethod : declaredMethods) {
if (isConstructorMethod(declaredMethod)) {
addDelegateConstructor(classNode, declaredMethod, genericsPlaceholders);
}
else if (isCandidateInstanceMethod(supportedSuperType, declaredMethod)) {
MethodNode methodNode = addDelegateInstanceMethod(classNode, delegateInstance, declaredMethod, null, true, genericsPlaceholders, noNullCheck);
if(addCompileStatic) {
addCompileStaticAnnotation(methodNode);
}
}
}
delegateNode = delegateNode.getSuperClass();
}
}
public static FieldNode addFieldIfNonExistent(ClassNode classNode, ClassNode fieldType, String fieldName) {
if (classNode != null && classNode.getField(fieldName) == null) {
return classNode.addField(fieldName, Modifier.PRIVATE, fieldType,
new ConstructorCallExpression(fieldType, new ArgumentListExpression()));
}
return null;
}
/**
* Adds the given expression as a member of the given annotation
*
* @param annotationNode The annotation node
* @param memberName The name of the member
* @param expression The expression
*/
public static void addExpressionToAnnotationMember(AnnotationNode annotationNode, String memberName, Expression expression) {
Expression exclude = annotationNode.getMember(memberName);
if(exclude instanceof ListExpression) {
((ListExpression)exclude).addExpression(expression);
}
else if(exclude != null) {
ListExpression list = new ListExpression();
list.addExpression(exclude);
list.addExpression(expression);
annotationNode.setMember(memberName, list);
}
else {
annotationNode.setMember(memberName, expression);
}
}
/**
* Adds an annotation to the give nclass node if it doesn't already exist
*
* @param classNode The class node
* @param annotationClass The annotation class
*/
public static void addAnnotationIfNecessary(ClassNode classNode, Class<? extends Annotation> annotationClass) {
addAnnotationOrGetExisting(classNode, annotationClass);
}
/**
* Adds an annotation to the given class node or returns the existing annotation
*
* @param classNode The class node
* @param annotationClass The annotation class
*/
public static AnnotationNode addAnnotationOrGetExisting(ClassNode classNode, Class<? extends Annotation> annotationClass) {
return addAnnotationOrGetExisting(classNode, annotationClass, Collections.<String, Object>emptyMap());
}
/**
* Adds an annotation to the given class node or returns the existing annotation
*
* @param classNode The class node
* @param annotationClass The annotation class
*/
public static AnnotationNode addAnnotationOrGetExisting(ClassNode classNode, Class<? extends Annotation> annotationClass, Map<String, Object> members) {
ClassNode annotationClassNode = ClassHelper.make(annotationClass);
return addAnnotationOrGetExisting(classNode, annotationClassNode, members);
}
public static AnnotationNode addAnnotationOrGetExisting(ClassNode classNode, ClassNode annotationClassNode) {
return addAnnotationOrGetExisting(classNode, annotationClassNode, Collections.<String, Object>emptyMap());
}
public static AnnotationNode addAnnotationOrGetExisting(ClassNode classNode, ClassNode annotationClassNode, Map<String, Object> members) {
List<AnnotationNode> annotations = classNode.getAnnotations();
AnnotationNode annotationToAdd = new AnnotationNode(annotationClassNode);
if (annotations.isEmpty()) {
classNode.addAnnotation(annotationToAdd);
}
else {
AnnotationNode existing = findAnnotation(annotationClassNode, annotations);
if (existing != null){
annotationToAdd = existing;
}
else {
classNode.addAnnotation(annotationToAdd);
}
}
if(members != null && !members.isEmpty()) {
for (Map.Entry<String, Object> memberEntry : members.entrySet()) {
Object value = memberEntry.getValue();
annotationToAdd.setMember( memberEntry.getKey(), value instanceof Expression ? (Expression)value : new ConstantExpression(value));
}
}
return annotationToAdd;
}
/**
* Add the grails.artefact.Enhanced annotation to classNode if it does not already exist and ensure that
* all of the features in the enhancedFor array are represented in the enhancedFor attribute of the
* Enhanced annnotation
* @param classNode the class to add the Enhanced annotation to
* @param enhancedFor an array of feature names to include in the enhancedFor attribute of the annotation
* @return the AnnotationNode associated with the Enhanced annotation for classNode
* @see Enhanced
*/
public static AnnotationNode addEnhancedAnnotation(final ClassNode classNode, final String... enhancedFor) {
final AnnotationNode enhancedAnnotationNode;
final List<AnnotationNode> annotations = classNode.getAnnotations(ENHANCED_CLASS_NODE);
if (annotations.isEmpty()) {
enhancedAnnotationNode = new AnnotationNode(ENHANCED_CLASS_NODE);
String grailsVersion = getGrailsVersion();
if(grailsVersion == null) {
grailsVersion = System.getProperty("grails.version");
}
if(grailsVersion != null) {
enhancedAnnotationNode.setMember("version", new ConstantExpression(grailsVersion));
}
classNode.addAnnotation(enhancedAnnotationNode);
} else {
enhancedAnnotationNode = annotations.get(0);
}
if(enhancedFor != null && enhancedFor.length > 0) {
ListExpression enhancedForArray = (ListExpression) enhancedAnnotationNode.getMember("enhancedFor");
if(enhancedForArray == null) {
enhancedForArray = new ListExpression();
enhancedAnnotationNode.setMember("enhancedFor", enhancedForArray);
}
final List<Expression> featureNameExpressions = enhancedForArray.getExpressions();
for(final String feature : enhancedFor) {
boolean exists = false;
for(Expression expression : featureNameExpressions) {
if(expression instanceof ConstantExpression && feature.equals(((ConstantExpression)expression).getValue())) {
exists = true;
break;
}
}
if(!exists) {
featureNameExpressions.add(new ConstantExpression(feature));
}
}
}
return enhancedAnnotationNode;
}
private static String getGrailsVersion() {
return GrailsASTUtils.class.getPackage().getImplementationVersion();
}
public static AnnotationNode findAnnotation(ClassNode annotationClassNode, List<AnnotationNode> annotations) {
for (AnnotationNode annotation : annotations) {
if (annotation.getClassNode().equals(annotationClassNode)) {
return annotation;
}
}
return null;
}
public static AnnotationNode findAnnotation(ClassNode classNode, Class<?> type) {
List<AnnotationNode> annotations = classNode.getAnnotations();
return annotations == null ? null : findAnnotation(new ClassNode(type),annotations);
}
/**
* Returns true if classNode is marked with annotationClass
* @param classNode A ClassNode to inspect
* @param annotationClass an annotation to look for
* @return true if classNode is marked with annotationClass, otherwise false
*/
public static boolean hasAnnotation(final ClassNode classNode, final Class<? extends Annotation> annotationClass) {
return !classNode.getAnnotations(new ClassNode(annotationClass)).isEmpty();
}
/**
* Returns true if MethodNode is marked with annotationClass
* @param methodNode A MethodNode to inspect
* @param annotationClass an annotation to look for
* @return true if classNode is marked with annotationClass, otherwise false
*/
public static boolean hasAnnotation(final MethodNode methodNode, final Class<? extends Annotation> annotationClass) {
return !methodNode.getAnnotations(new ClassNode(annotationClass)).isEmpty();
}
/**
* @param classNode a ClassNode to search
* @param annotationsToLookFor Annotations to look for
* @return true if classNode is marked with any of the annotations in annotationsToLookFor
*/
public static boolean hasAnyAnnotations(final ClassNode classNode, final Class<? extends Annotation>... annotationsToLookFor) {
for (Class<? extends Annotation> annotationClass : annotationsToLookFor) {
if(hasAnnotation(classNode, annotationClass)) {
return true;
}
}
return false;
}
public static boolean removeAnnotation(final MethodNode methodNode, final Class<? extends Annotation> annotationClass) {
List<AnnotationNode> annotations = methodNode.getAnnotations(new ClassNode(annotationClass));
if (annotations.size() > 0) {
methodNode.getAnnotations().removeAll(annotations);
return true;
} else {
return false;
}
}
public static void addMethodIfNotPresent(ClassNode controllerClassNode, MethodNode methodNode) {
MethodNode existing = controllerClassNode.getMethod(methodNode.getName(), methodNode.getParameters());
if (existing == null) {
controllerClassNode.addMethod(methodNode);
AnnotatedNodeUtils.markAsGenerated(controllerClassNode, methodNode);
}
}
public static ExpressionStatement createPrintlnStatement(String message) {
return new ExpressionStatement(new MethodCallExpression(new VariableExpression("this"),"println", new ArgumentListExpression(new ConstantExpression(message))));
}
public static ExpressionStatement createPrintlnStatement(String message, String variable) {
return new ExpressionStatement(new MethodCallExpression(new VariableExpression("this"),"println", new ArgumentListExpression(new BinaryExpression(new ConstantExpression(message),Token.newSymbol(Types.PLUS, 0, 0),new VariableExpression(variable)))));
}
/**
* Wraps a method body in try / catch logic that catches any errors and logs an error, but does not rethrow!
*
* @param methodNode The method node
*/
public static void wrapMethodBodyInTryCatchDebugStatements(MethodNode methodNode) {
BlockStatement code = (BlockStatement) methodNode.getCode();
BlockStatement newCode = new BlockStatement();
TryCatchStatement tryCatchStatement = new TryCatchStatement(code, new BlockStatement());
newCode.addStatement(tryCatchStatement);
methodNode.setCode(newCode);
BlockStatement catchBlock = new BlockStatement();
ArgumentListExpression logArguments = new ArgumentListExpression();
logArguments.addExpression(new BinaryExpression(new ConstantExpression("Error initializing class: "),Token.newSymbol(Types.PLUS, 0, 0),new VariableExpression("e")));
logArguments.addExpression(new VariableExpression("e"));
catchBlock.addStatement(new ExpressionStatement(new MethodCallExpression(new VariableExpression("log"), "error", logArguments)));
tryCatchStatement.addCatch(new CatchStatement(new Parameter(new ClassNode(Throwable.class), "e"),catchBlock));
}
/**
* Evaluates a constraints closure and returns metadata about the constraints configured in the closure. The
* Map returned has property names as keys and the value associated with each of those property names is
* a Map<String, Expression> which has constraint names as keys and the Expression associated with that constraint
* as values.
*
* @param closureExpression the closure expression to evaluate
* @return the Map as described above
*/
public static Map<String, Map<String, Expression>> getConstraintMetadata(final ClosureExpression closureExpression) {
final List<MethodCallExpression> methodExpressions = new ArrayList<MethodCallExpression>();
final Map<String, Map<String, Expression>> results = new LinkedHashMap<String, Map<String, Expression>>();
final Statement closureCode = closureExpression.getCode();
if (closureCode instanceof BlockStatement) {
final List<Statement> closureStatements = ((BlockStatement) closureCode).getStatements();
for (final Statement closureStatement : closureStatements) {
if (closureStatement instanceof ExpressionStatement) {
final Expression expression = ((ExpressionStatement) closureStatement).getExpression();
if (expression instanceof MethodCallExpression) {
methodExpressions.add((MethodCallExpression) expression);
}
} else if (closureStatement instanceof ReturnStatement) {
final ReturnStatement returnStatement = (ReturnStatement) closureStatement;
Expression expression = returnStatement.getExpression();
if (expression instanceof MethodCallExpression) {
methodExpressions.add((MethodCallExpression) expression);
}
}
for (final MethodCallExpression methodCallExpression : methodExpressions) {
final Expression objectExpression = methodCallExpression.getObjectExpression();
if (objectExpression instanceof VariableExpression && "this".equals(((VariableExpression)objectExpression).getName())) {
final Expression methodCallArguments = methodCallExpression.getArguments();
if (methodCallArguments instanceof TupleExpression) {
final List<Expression> methodCallArgumentExpressions = ((TupleExpression) methodCallArguments).getExpressions();
if (methodCallArgumentExpressions != null && methodCallArgumentExpressions.size() == 1 && methodCallArgumentExpressions.get(0) instanceof NamedArgumentListExpression) {
final Map<String, Expression> constraintNameToExpression = new LinkedHashMap<String, Expression>();
final List<MapEntryExpression> mapEntryExpressions = ((NamedArgumentListExpression) methodCallArgumentExpressions.get(0)).getMapEntryExpressions();
for (final MapEntryExpression mapEntryExpression : mapEntryExpressions) {
final Expression keyExpression = mapEntryExpression.getKeyExpression();
if (keyExpression instanceof ConstantExpression) {
final Object value = ((ConstantExpression) keyExpression).getValue();
if (value instanceof String) {
constraintNameToExpression.put((String)value, mapEntryExpression.getValueExpression());
}
}
}
results.put(methodCallExpression.getMethodAsString(), constraintNameToExpression);
}
}
}
}
}
}
return results;
}
/**
* Returns a map containing the names and types of the given association type. eg. GrailsDomainClassProperty.HAS_MANY
* @param classNode The target class ndoe
* @param associationType The associationType
* @return A map
*/
public static Map<String, ClassNode> getAssocationMap(ClassNode classNode, String associationType) {
PropertyNode property = classNode.getProperty(associationType);
Map<String, ClassNode> associationMap = new HashMap<String, ClassNode>();
if (property != null && property.isStatic()) {
Expression e = property.getInitialExpression();
if (e instanceof MapExpression) {
MapExpression me = (MapExpression) e;
for (MapEntryExpression mee : me.getMapEntryExpressions()) {
String key = mee.getKeyExpression().getText();
Expression valueExpression = mee.getValueExpression();
if (valueExpression instanceof ClassExpression) {
associationMap.put(key, valueExpression.getType());
}
}
}
}
return associationMap;
}
public static Map<String,ClassNode> getAllAssociationMap(ClassNode classNode) {
Map<String, ClassNode> associationMap = new HashMap<String, ClassNode>();
associationMap.putAll( getAssocationMap(classNode, GormProperties.HAS_MANY));
associationMap.putAll( getAssocationMap(classNode, GormProperties.HAS_ONE));
associationMap.putAll( getAssocationMap(classNode, GormProperties.BELONGS_TO));
return associationMap;
}
public static ClassNode findInterface(ClassNode classNode, ClassNode interfaceNode) {
while(!classNode.equals(OBJECT_CLASS_NODE)) {
Set<ClassNode> interfaces = classNode.getAllInterfaces();
for (ClassNode anInterface : interfaces) {
if(anInterface.equals(interfaceNode)) return anInterface;
}
classNode = classNode.getSuperClass();
}
return null;
}
public static boolean hasZeroArgsConstructor(ClassNode implementationNode) {
List<ConstructorNode> constructors = implementationNode.getDeclaredConstructors();
if(constructors.isEmpty()) return true;
for (ConstructorNode constructor : constructors) {
if(constructor.getParameters().length == 0 ) return true;
}
return false;
}
/**
* Whether the given class node is an inner class
*
* @param classNode The class node
* @return True if it is
*/
public static boolean isInnerClassNode(ClassNode classNode) {
return (classNode instanceof InnerClassNode) || classNode.getName().contains("$");
}
/**
* Returns true if the given class name is a parent class of the given class
*
* @param classNode The class node
* @param parentClassName the parent class name
* @return True if it is a subclass
*/
public static boolean isSubclassOf(ClassNode classNode, String parentClassName) {
ClassNode currentSuper = classNode.getSuperClass();
while (currentSuper != null && !currentSuper.getName().equals(OBJECT_CLASS)) {
if (currentSuper.getName().equals(parentClassName)) return true;
currentSuper = currentSuper.getSuperClass();
}
return false;
}
@Target(ElementType.CONSTRUCTOR)
@Retention(RetentionPolicy.SOURCE)
private static @interface GrailsDelegatingConstructor {}
/**
* Marks a method to be staticly compiled
*
* @param annotatedNode
* @return The annotated method
*/
public static AnnotatedNode addCompileStaticAnnotation(AnnotatedNode annotatedNode) {
return addCompileStaticAnnotation(annotatedNode, false);
}
/**
* Adds @CompileStatic annotation to method
*
* @param annotatedNode
* @param skip
* @return The annotated method
*/
public static AnnotatedNode addCompileStaticAnnotation(AnnotatedNode annotatedNode, boolean skip) {
if(annotatedNode != null) {
AnnotationNode an = new AnnotationNode(COMPILESTATIC_CLASS_NODE);
if(skip) {
an.addMember("value", new PropertyExpression(new ClassExpression(TYPECHECKINGMODE_CLASS_NODE), "SKIP"));
}
annotatedNode.addAnnotation(an);
if(!skip) {
annotatedNode.getDeclaringClass().addTransform(StaticCompileTransformation.class, an);
}
}
return annotatedNode;
}
/**
* Set the method target of a MethodCallExpression to the first matching method with same number of arguments.
* This doesn't check argument types.
*
* @param methodCallExpression
* @param targetClassNode
*/
public static MethodCallExpression applyDefaultMethodTarget(final MethodCallExpression methodCallExpression, final ClassNode targetClassNode) {
return applyMethodTarget(methodCallExpression, targetClassNode, (ClassNode[])null);
}
/**
* Set the method target of a MethodCallExpression to the first matching method with same number of arguments.
* This doesn't check argument types.
*
* @param methodCallExpression
* @param targetClass
* @return The method call expression
*/
public static MethodCallExpression applyDefaultMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass) {
return applyDefaultMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference());
}
/**
* Set the method target of a MethodCallExpression to the first matching method with same number and type of arguments.
*
* A null parameter type will match any type
*
* @param methodCallExpression
* @param targetClassNode
* @param targetParameterTypes
* @return The method call expression
*/
public static MethodCallExpression applyMethodTarget(final MethodCallExpression methodCallExpression, final ClassNode targetClassNode, final ClassNode... targetParameterTypes) {
String methodName = methodCallExpression.getMethodAsString();
if(methodName==null) return methodCallExpression;
int argumentCount = methodCallExpression.getArguments() != null ? ((TupleExpression)methodCallExpression.getArguments()).getExpressions().size() : 0;
String methodFoundInClass = null;
for (MethodNode method : targetClassNode.getMethods(methodName)) {
int methodParameterCount = method.getParameters() != null ? method.getParameters().length : 0;
if (methodParameterCount == argumentCount && (targetParameterTypes == null || (parameterTypesMatch(method.getParameters(), targetParameterTypes)))) {
String methodFromClass = method.getDeclaringClass().getName();
if(methodFoundInClass == null) {
methodCallExpression.setMethodTarget(method);
methodFoundInClass = methodFromClass;
} else if (methodFromClass.equals(methodFoundInClass)) {
throw new RuntimeException("Multiple methods with same name '" + methodName + "' and argument count (" + argumentCount + ") in " + targetClassNode.getName() + ". Cannot apply default method target.");
}
}
}
return methodCallExpression;
}
/**
* Set the method target of a MethodCallExpression to the first matching method with same number and type of arguments.
*
* @param methodCallExpression
* @param targetClass
* @param targetParameterClassTypes
* @return The method call expression
*/
public static MethodCallExpression applyMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass, final Class<?>... targetParameterClassTypes) {
return applyMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference(), convertTargetParameterTypes(targetParameterClassTypes));
}
/**
* Set the method target of a MethodCallExpression to the first matching method with same number and type of arguments.
*
* @param methodCallExpression
* @param targetClassNode
* @param targetParameterClassTypes
* @return The method call expression
*/
public static MethodCallExpression applyMethodTarget(final MethodCallExpression methodCallExpression, final ClassNode targetClassNode, final Class<?>... targetParameterClassTypes) {
return applyMethodTarget(methodCallExpression, targetClassNode, convertTargetParameterTypes(targetParameterClassTypes));
}
private static ClassNode[] convertTargetParameterTypes(final Class<?>[] targetParameterClassTypes) {
ClassNode[] targetParameterTypes = null;
if(targetParameterClassTypes != null) {
targetParameterTypes = new ClassNode[targetParameterClassTypes.length];
for(int i=0;i < targetParameterClassTypes.length;i++) {
targetParameterTypes[i] = targetParameterClassTypes[i] != null ? ClassHelper.make(targetParameterClassTypes[i]).getPlainNodeReference() : null;
}
}
return targetParameterTypes;
}
private static boolean parameterTypesMatch(Parameter[] parameters, ClassNode[] targetParameterTypes) {
if(targetParameterTypes==null || targetParameterTypes.length==0) return true;
for(int i=0;i < parameters.length;i++) {
if(targetParameterTypes.length > i && targetParameterTypes[i] != null && !parameters[i].getType().getName().equals(targetParameterTypes[i].getName())) {
return false;
}
}
return true;
}
/**
* Build static direct call to getter of a property
*
* @param objectExpression
* @param propertyName
* @param targetClassNode
* @return The method call expression
*/
public static MethodCallExpression buildGetPropertyExpression(final Expression objectExpression, final String propertyName, final ClassNode targetClassNode) {
return buildGetPropertyExpression(objectExpression, propertyName, targetClassNode, false);
}
/**
* Build static direct call to getter of a property
*
* @param objectExpression
* @param propertyName
* @param targetClassNode
* @param useBooleanGetter
* @return The method call expression
*/
public static MethodCallExpression buildGetPropertyExpression(final Expression objectExpression, final String propertyName, final ClassNode targetClassNode, final boolean useBooleanGetter) {
String methodName = (useBooleanGetter ? "is" : "get") + MetaClassHelper.capitalize(propertyName);
MethodCallExpression methodCallExpression = new MethodCallExpression(objectExpression, methodName, MethodCallExpression.NO_ARGUMENTS);
MethodNode getterMethod = targetClassNode.getGetterMethod(methodName);
if(getterMethod != null) {
methodCallExpression.setMethodTarget(getterMethod);
}
return methodCallExpression;
}
/**
* Build static direct call to setter of a property
*
* @param objectExpression
* @param propertyName
* @param targetClassNode
* @param valueExpression
* @return The method call expression
*/
public static MethodCallExpression buildSetPropertyExpression(final Expression objectExpression, final String propertyName, final ClassNode targetClassNode, final Expression valueExpression) {
String methodName = "set" + MetaClassHelper.capitalize(propertyName);
MethodCallExpression methodCallExpression = new MethodCallExpression(objectExpression, methodName, new ArgumentListExpression(valueExpression));
MethodNode setterMethod = targetClassNode.getSetterMethod(methodName);
if(setterMethod != null) {
methodCallExpression.setMethodTarget(setterMethod);
}
return methodCallExpression;
}
/**
* Build static direct call to put entry in Map
*
* @param objectExpression
* @param keyName
* @param valueExpression
* @return The method call expression
*/
public static MethodCallExpression buildPutMapExpression(final Expression objectExpression, final String keyName, final Expression valueExpression) {
return applyDefaultMethodTarget(new MethodCallExpression(objectExpression, "put", new ArgumentListExpression(new ConstantExpression(keyName), valueExpression)), Map.class);
}
/**
* Build static direct call to get entry from Map
*
* @param objectExpression
* @param keyName
* @return The method call expression
*/
public static MethodCallExpression buildGetMapExpression(final Expression objectExpression, final String keyName) {
return applyDefaultMethodTarget(new MethodCallExpression(objectExpression, "get", new ArgumentListExpression(new ConstantExpression(keyName))), Map.class);
}
public static Expression buildGetThisObjectExpression(boolean inClosureBlock) {
if (!inClosureBlock) {
return buildThisExpression();
} else {
return buildGetPropertyExpression(buildThisExpression(), "thisObject", ClassHelper.make(Closure.class).getPlainNodeReference());
}
}
public static Expression buildThisExpression() {
return new VariableExpression("this");
}
public static MethodCallExpression noImplicitThis(MethodCallExpression methodCallExpression) {
return applyImplicitThis(methodCallExpression, false);
}
public static MethodCallExpression applyImplicitThis(MethodCallExpression methodCallExpression, boolean useImplicitThis) {
methodCallExpression.setImplicitThis(useImplicitThis);
return methodCallExpression;
}
public static void copyAnnotations(final AnnotatedNode from, final AnnotatedNode to) {
copyAnnotations(from, to, null, null);
}
public static void copyAnnotations(final AnnotatedNode from, final AnnotatedNode to, final Set<String> included, final Set<String> excluded) {
final List<AnnotationNode> annotationsToCopy = from.getAnnotations();
for(final AnnotationNode node : annotationsToCopy) {
String annotationClassName = node.getClassNode().getName();
if((excluded==null || !excluded.contains(annotationClassName)) &&
(included==null || included.contains(annotationClassName))) {
final AnnotationNode copyOfAnnotationNode = cloneAnnotation(node);
to.addAnnotation(copyOfAnnotationNode);
}
}
}
public static AnnotationNode cloneAnnotation(final AnnotationNode node) {
final AnnotationNode copyOfAnnotationNode = new AnnotationNode(node.getClassNode());
final Map<String, Expression> members = node.getMembers();
for(final Map.Entry<String, Expression> entry : members.entrySet()) {
copyOfAnnotationNode.addMember(entry.getKey(), entry.getValue());
}
return copyOfAnnotationNode;
}
public static void filterAnnotations(final AnnotatedNode annotatedNode, final Set<String> classNamesToRetain, final Set<String> classNamesToRemove) {
for(Iterator<AnnotationNode> iterator = annotatedNode.getAnnotations().iterator(); iterator.hasNext(); ) {
final AnnotationNode node = iterator.next();
String annotationClassName = node.getClassNode().getName();
if((classNamesToRemove==null || classNamesToRemove.contains(annotationClassName)) &&
(classNamesToRetain==null || !classNamesToRetain.contains(annotationClassName))) {
iterator.remove();
}
}
}
public static void removeCompileStaticAnnotations(final AnnotatedNode annotatedNode) {
filterAnnotations(annotatedNode, null, new HashSet<String>(Arrays.asList(new String[]{CompileStatic.class.getName(), TypeChecked.class.getName()})));
}
public static void markApplied(ASTNode astNode, Class<?> transformationClass) {
resolveRedirect(astNode).setNodeMetaData(appliedTransformationKey(transformationClass), Boolean.TRUE);
}
private static ASTNode resolveRedirect(ASTNode astNode) {
if(astNode instanceof ClassNode) {
astNode = ((ClassNode)astNode).redirect();
}
return astNode;
}
private static String appliedTransformationKey(Class<?> transformationClass) {
return "APPLIED_" + transformationClass.getName();
}
public static boolean isApplied(ASTNode astNode, Class<?> transformationClass) {
return resolveRedirect(astNode).getNodeMetaData(appliedTransformationKey(transformationClass)) == Boolean.TRUE;
}
public static void processVariableScopes(SourceUnit source, ClassNode classNode) {
processVariableScopes(source, classNode, null);
}
public static void processVariableScopes(SourceUnit source, ClassNode classNode, MethodNode methodNode) {
VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source);
if(methodNode == null) {
scopeVisitor.visitClass(classNode);
} else {
scopeVisitor.prepareVisit(classNode);
scopeVisitor.visitMethod(methodNode);
}
}
public static boolean isGetterMethod(MethodNode md) {
String methodName = md.getName();
return (((methodName.startsWith("get") && methodName.length() > 3) || (methodName.startsWith("is") && methodName.length() > 2)) && (md.getParameters()==null || md.getParameters().length == 0));
}
public static boolean isSetterMethod(MethodNode md) {
String methodName = md.getName();
return ((methodName.startsWith("set") &&
methodName.length() > 3) &&
Character.isUpperCase(methodName.substring(3).charAt(0)) &&
md.getParameters() != null &&
md.getParameters().length == 1);
}
public static boolean isSetterOrGetterMethod(MethodNode md) {
return isGetterMethod(md) || isSetterMethod(md);
}
/**
* Find URL of SourceUnit
*
* source.getSource().getURI() fails in Groovy-Eclipse compiler
*
* @param source
* @return URL of SourceUnit
*/
public static URL getSourceUrl(SourceUnit source) {
URL url = null;
final String filename = source.getName();
if(filename==null) {
return null;
}
Resource resource = new FileSystemResource(filename);
if (resource.exists()) {
try {
url = resource.getURL();
} catch (IOException e) {
// ignore
}
}
return url;
}
public static URL getSourceUrl(ClassNode classNode) {
return getSourceUrl(classNode.getModule().getContext());
}
public static boolean hasParameters(MethodNode methodNode) {
return methodNode.getParameters().length > 0;
}
public static boolean isInheritedFromTrait(MethodNode methodNode) {
return hasAnnotation(methodNode, Traits.TraitBridge.class);
}
}
| 26,641 |
1,822 | // Copyright (c) 2020 <NAME>
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// hpxinspect:nodeprecatedinclude:boost/system/error_code.hpp
// hpxinspect:nodeprecatedname:boost::system::error_code
#pragma once
#include <hpx/config.hpp>
#include <boost/system/error_code.hpp>
#include <system_error>
#include <type_traits>
///////////////////////////////////////////////////////////////////////////////
/// \cond NODETAIL
namespace hpx {
class compat_error_code
{
public:
explicit compat_error_code(std::error_code& ec)
: _ec(ec)
, _compat()
{
}
~compat_error_code()
{
_ec = _compat;
}
operator boost::system::error_code&() noexcept
{
return _compat;
}
template <typename E,
typename Enable = typename std::enable_if<
boost::system::is_error_code_enum<E>::value>::type>
static bool equal(std::error_code const& lhs, E rhs) noexcept
{
return lhs == std::error_code(make_error_code(rhs));
}
private:
std::error_code& _ec;
boost::system::error_code _compat;
};
} // namespace hpx
| 610 |
5,169 | {
"name": "MJGAvailability",
"version": "1.0.0",
"summary": "Help checking iOS API availability.",
"homepage": "https://github.com/JohnWong/MJGAvailability",
"description": "Help checking iOS API availability. 帮助检查iOS API的可用性",
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/JohnWong/MJGAvailability.git",
"tag": "1.0.0"
},
"license": "BSD",
"platforms": {
"ios": "2.0",
"osx": "10.6"
},
"source_files": "Source/*.{h,m}"
}
| 232 |
827 | """Helper function for _load_compcor."""
prefix_compcor = {"temporal_anat": ["t", "a"],
"temporal": ["t"],
"anat": ["a"]}
anat_masker = {"combined": ["combined"],
"separated": ["WM", "CSF"],
None: None}
def _find_compcor(confounds_json, compcor, n_compcor):
"""Build list for the number of compcor components."""
prefix_set, anat_mask = _check_compcor_method(compcor)
collector = []
for prefix in prefix_set:
# all possible compcor confounds in order, mixing different
# types of mask
all_compcor_name = [
comp
for comp in confounds_json.keys()
if f"{prefix}_comp_cor" in comp
]
# filter by prefix first (anat vs temporal)
compcor_cols_filt = _prefix_confound_filter(prefix, all_compcor_name)
if prefix == "a":
# apply acompor mask option if relevant, and select top components
compcor_cols_filt = _acompcor_mask(
confounds_json, anat_mask, compcor_cols_filt, n_compcor
)
else:
# select top components
compcor_cols_filt = _select_compcor(compcor_cols_filt, n_compcor)
# Aggregate components across all masks
collector += compcor_cols_filt
return collector
def _select_compcor(compcor_cols, n_compcor):
"""Retain a specified number of compcor components."""
# only select if not "all", or less components are requested than there
# actually is
if (n_compcor != "all") and (n_compcor < len(compcor_cols)):
compcor_cols = compcor_cols[0:n_compcor]
return compcor_cols
def _check_compcor_method(compcor):
"""Load compcor options and check if method is acceptable."""
compcor_type = compcor.split("_")
if len(compcor_type) > 1:
compcor_type = "_".join(compcor_type[:-1])
anat_mask_type = compcor.split("_")[-1:][0]
else:
compcor_type = compcor_type[0]
anat_mask_type = None
# get relevant prefix from compcor strategy
prefix_set = prefix_compcor[compcor_type]
# get relevant compcor mask
anat_mask = anat_masker[anat_mask_type]
return prefix_set, anat_mask
def _acompcor_mask(confounds_json, anat_mask, compcor_cols_filt, n_compcor):
"""Filter according to acompcor mask(s) and select top components."""
collector = []
for mask in anat_mask:
cols = _json_mask(compcor_cols_filt, confounds_json, mask)
cols = _select_compcor(cols, n_compcor)
collector += cols
return collector
def _json_mask(compcor_cols_filt, confounds_json, mask):
"""Extract anat compcor components from a given mask."""
return [
compcor_col
for compcor_col in compcor_cols_filt
if confounds_json[compcor_col]["Mask"] in mask
]
def _prefix_confound_filter(prefix, all_compcor_name):
"""Get confound columns by prefix and acompcor mask."""
compcor_cols_filt = []
for nn in range(len(all_compcor_name)):
nn_str = str(nn).zfill(2)
compcor_col = f"{prefix}_comp_cor_{nn_str}"
compcor_cols_filt.append(compcor_col)
return compcor_cols_filt
| 1,389 |
530 | from typing import Optional, Union
from tartiflette.language.ast import (
ListTypeNode,
NamedTypeNode,
NonNullTypeNode,
)
from tartiflette.types.list import GraphQLList
from tartiflette.types.non_null import GraphQLNonNull
__all__ = ("schema_type_from_ast",)
def schema_type_from_ast(
schema: "GraphQLSchema",
type_node: Union["ListTypeNode", "NonNullTypeNode", "NamedTypeNode"],
) -> Optional[Union["GraphQLList", "GraphQLNonNull", "GraphQLType"]]:
"""
Given a Schema and an AST node describing a type, return a GraphQLType
definition which applies to that type.
:param schema: schema instance to use
:param type_node: AST node describing a type
:type schema: GraphQLSchema
:type type_node: Union[ListTypeNode, NonNullTypeNode, NamedTypeNode]
:return: a GraphQLType definition which applies to that type or None
:rtype: Optional[Union[GraphQLList, GraphQLNonNull, GraphQLType]]
"""
if isinstance(type_node, ListTypeNode):
inner_type = schema_type_from_ast(schema, type_node.type)
return GraphQLList(inner_type) if inner_type else None
if isinstance(type_node, NonNullTypeNode):
inner_type = schema_type_from_ast(schema, type_node.type)
return GraphQLNonNull(inner_type) if inner_type else None
if isinstance(type_node, NamedTypeNode):
try:
return schema.find_type(type_node.name.value)
except KeyError:
pass
return None
raise TypeError(f"Unexpected type kind: {type_node.__class__.__name__}")
| 575 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/xr/xr_transient_input_hit_test_result.h"
#include "device/vr/public/mojom/vr_service.mojom-blink.h"
#include "third_party/blink/renderer/modules/xr/xr_hit_test_result.h"
#include "third_party/blink/renderer/modules/xr/xr_input_source.h"
namespace blink {
XRTransientInputHitTestResult::XRTransientInputHitTestResult(
XRInputSource* input_source,
const Vector<device::mojom::blink::XRHitResultPtr>& results)
: input_source_(input_source) {
for (const auto& result : results) {
results_.push_back(MakeGarbageCollected<XRHitTestResult>(
input_source->session(), *result));
}
}
XRInputSource* XRTransientInputHitTestResult::inputSource() {
return input_source_;
}
HeapVector<Member<XRHitTestResult>> XRTransientInputHitTestResult::results() {
return results_;
}
void XRTransientInputHitTestResult::Trace(Visitor* visitor) const {
visitor->Trace(input_source_);
visitor->Trace(results_);
ScriptWrappable::Trace(visitor);
}
} // namespace blink
| 427 |
575 | <reponame>mghgroup/Glide-Browser
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <vector>
#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/service_manager/public/cpp/constants.h"
#include "services/service_manager/public/cpp/identity.h"
#include "services/service_manager/public/cpp/manifest.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#include "services/service_manager/public/cpp/service.h"
#include "services/service_manager/public/cpp/service_receiver.h"
#include "services/service_manager/public/cpp/test/test_service_manager.h"
#include "services/service_manager/public/mojom/constants.mojom.h"
#include "services/service_manager/public/mojom/service_manager.mojom.h"
#include "services/service_manager/tests/lifecycle/lifecycle.test-mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace service_manager {
namespace {
const char kTestName[] = "lifecycle_unittest";
const char kTestAppName[] = "lifecycle_unittest_app";
const char kTestParentName[] = "lifecycle_unittest_parent";
const char kTestPackageName[] = "lifecycle_unittest_package";
const char kTestPackageAppNameA[] = "lifecycle_unittest_package_app_a";
const char kTestPackageAppNameB[] = "lifecycle_unittest_package_app_b";
const char kTestLifecycleControlCapability[] = "lifecycle_control";
const char kTestParentCapability[] = "lifecycle_unittest:parent";
const std::vector<Manifest>& GetTestManifests() {
static base::NoDestructor<std::vector<Manifest>> manifests{
{ManifestBuilder()
.WithServiceName(kTestName)
.WithOptions(ManifestOptionsBuilder()
.CanRegisterOtherServiceInstances(true)
.Build())
.RequireCapability(kTestParentName, kTestParentCapability)
.RequireCapability("*", kTestLifecycleControlCapability)
.RequireCapability(mojom::kServiceName,
"service_manager:service_manager")
.Build(),
ManifestBuilder()
.WithServiceName(kTestAppName)
.WithOptions(ManifestOptionsBuilder()
.WithExecutionMode(
Manifest::ExecutionMode::kStandaloneExecutable)
.WithSandboxType("none")
.Build())
.ExposeCapability(
kTestLifecycleControlCapability,
Manifest::InterfaceList<test::mojom::LifecycleControl>())
.Build(),
ManifestBuilder()
.WithServiceName(kTestParentName)
.WithOptions(ManifestOptionsBuilder()
.WithExecutionMode(
Manifest::ExecutionMode::kStandaloneExecutable)
.WithSandboxType("none")
.Build())
.ExposeCapability(kTestParentCapability,
Manifest::InterfaceList<test::mojom::Parent>())
.RequireCapability(kTestAppName, kTestLifecycleControlCapability)
.Build(),
ManifestBuilder()
.WithServiceName(kTestPackageName)
.WithOptions(ManifestOptionsBuilder()
.WithExecutionMode(
Manifest::ExecutionMode::kStandaloneExecutable)
.WithSandboxType("none")
.Build())
.ExposeCapability(
kTestLifecycleControlCapability,
Manifest::InterfaceList<test::mojom::LifecycleControl>())
.PackageService(
ManifestBuilder()
.WithServiceName(kTestPackageAppNameA)
.ExposeCapability(
kTestLifecycleControlCapability,
Manifest::InterfaceList<test::mojom::LifecycleControl>())
.Build())
.PackageService(
ManifestBuilder()
.WithServiceName(kTestPackageAppNameB)
.ExposeCapability(
kTestLifecycleControlCapability,
Manifest::InterfaceList<test::mojom::LifecycleControl>())
.Build())
.Build()}};
return *manifests;
}
struct Instance {
Instance() : pid(0) {}
Instance(const Identity& identity, uint32_t pid)
: identity(identity), pid(pid) {}
Identity identity;
uint32_t pid;
};
class InstanceState : public mojom::ServiceManagerListener {
public:
InstanceState(mojo::PendingReceiver<mojom::ServiceManagerListener> receiver,
base::OnceClosure on_init_complete)
: receiver_(this, std::move(receiver)),
on_init_complete_(std::move(on_init_complete)),
on_destruction_(destruction_loop_.QuitClosure()) {}
~InstanceState() override {}
bool HasInstanceForName(const std::string& name) const {
return instances_.find(name) != instances_.end();
}
size_t GetNewInstanceCount() const {
return instances_.size() - initial_instances_.size();
}
void WaitForInstanceDestruction() {
// If the instances have already stopped then |destruction_loop_.Run()|
// will immediately return.
destruction_loop_.Run();
}
private:
// mojom::ServiceManagerListener:
void OnInit(std::vector<mojom::RunningServiceInfoPtr> instances) override {
for (const auto& instance : instances) {
Instance i(instance->identity, instance->pid);
initial_instances_[i.identity.name()] = i;
instances_[i.identity.name()] = i;
}
std::move(on_init_complete_).Run();
}
void OnServiceCreated(mojom::RunningServiceInfoPtr instance) override {
instances_[instance->identity.name()] =
Instance(instance->identity, instance->pid);
}
void OnServiceStarted(const service_manager::Identity& identity,
uint32_t pid) override {
for (auto& instance : instances_) {
if (instance.second.identity == identity) {
instance.second.pid = pid;
break;
}
}
}
void OnServiceFailedToStart(
const service_manager::Identity& identity) override {
}
void OnServiceStopped(const service_manager::Identity& identity) override {
for (auto it = instances_.begin(); it != instances_.end(); ++it) {
if (it->second.identity == identity) {
instances_.erase(it);
break;
}
}
if (GetNewInstanceCount() == 0)
std::move(on_destruction_).Run();
}
void OnServicePIDReceived(const service_manager::Identity& identity,
uint32_t pid) override {
for (auto& instance : instances_) {
if (instance.second.identity == identity) {
instance.second.pid = pid;
break;
}
}
}
// All currently running instances.
std::map<std::string, Instance> instances_;
// The initial set of instances.
std::map<std::string, Instance> initial_instances_;
mojo::Receiver<mojom::ServiceManagerListener> receiver_;
base::OnceClosure on_init_complete_;
// Set when the client wants to wait for this object to track the destruction
// of an instance before proceeding.
base::RunLoop destruction_loop_;
base::OnceClosure on_destruction_;
DISALLOW_COPY_AND_ASSIGN(InstanceState);
};
} // namespace
class LifecycleTest : public testing::Test {
public:
LifecycleTest()
: test_service_manager_(GetTestManifests()),
test_service_receiver_(
&test_service_,
test_service_manager_.RegisterInstance(
Identity{kTestName, kSystemInstanceGroup, base::Token{},
base::Token::CreateRandom()})) {}
~LifecycleTest() override {}
Connector* connector() { return test_service_receiver_.GetConnector(); }
protected:
void SetUp() override {
instances_ = TrackInstances();
}
void TearDown() override {
instances_.reset();
}
bool CanRunCrashTest() {
return !base::CommandLine::ForCurrentProcess()->HasSwitch("single-process");
}
mojo::Remote<test::mojom::LifecycleControl> ConnectTo(
const std::string& name) {
mojo::Remote<test::mojom::LifecycleControl> lifecycle;
connector()->BindInterface(name, lifecycle.BindNewPipeAndPassReceiver());
PingPong(lifecycle.get());
return lifecycle;
}
void PingPong(test::mojom::LifecycleControl* lifecycle) {
base::RunLoop loop;
lifecycle->Ping(loop.QuitClosure());
loop.Run();
}
InstanceState* instances() { return instances_.get(); }
private:
std::unique_ptr<InstanceState> TrackInstances() {
mojo::Remote<mojom::ServiceManager> service_manager;
connector()->Connect(service_manager::mojom::kServiceName,
service_manager.BindNewPipeAndPassReceiver());
mojo::PendingRemote<mojom::ServiceManagerListener> listener;
base::RunLoop loop;
InstanceState* state = new InstanceState(
listener.InitWithNewPipeAndPassReceiver(), loop.QuitClosure());
service_manager->AddListener(std::move(listener));
loop.Run();
return base::WrapUnique(state);
}
base::test::TaskEnvironment task_environment_;
TestServiceManager test_service_manager_;
Service test_service_;
ServiceReceiver test_service_receiver_;
std::unique_ptr<InstanceState> instances_;
DISALLOW_COPY_AND_ASSIGN(LifecycleTest);
};
TEST_F(LifecycleTest, Standalone_GracefulQuit) {
mojo::Remote<test::mojom::LifecycleControl> lifecycle =
ConnectTo(kTestAppName);
EXPECT_TRUE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(1u, instances()->GetNewInstanceCount());
base::RunLoop loop;
lifecycle.set_disconnect_handler(loop.QuitClosure());
lifecycle->GracefulQuit();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
TEST_F(LifecycleTest, Standalone_Crash) {
if (!CanRunCrashTest()) {
LOG(INFO) << "Skipping Standalone_Crash test in --single-process mode.";
return;
}
mojo::Remote<test::mojom::LifecycleControl> lifecycle =
ConnectTo(kTestAppName);
EXPECT_TRUE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(1u, instances()->GetNewInstanceCount());
base::RunLoop loop;
lifecycle.set_disconnect_handler(loop.QuitClosure());
lifecycle->Crash();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
TEST_F(LifecycleTest, Standalone_CloseServiceManagerConnection) {
mojo::Remote<test::mojom::LifecycleControl> lifecycle =
ConnectTo(kTestAppName);
EXPECT_TRUE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(1u, instances()->GetNewInstanceCount());
base::RunLoop loop;
lifecycle.set_disconnect_handler(loop.QuitClosure());
lifecycle->CloseServiceManagerConnection();
instances()->WaitForInstanceDestruction();
// |lifecycle| pipe should still be valid.
PingPong(lifecycle.get());
}
TEST_F(LifecycleTest, PackagedApp_GracefulQuit) {
mojo::Remote<test::mojom::LifecycleControl> lifecycle =
ConnectTo(kTestPackageAppNameA);
// There should be two new instances - one for the app and one for the package
// that vended it.
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_EQ(2u, instances()->GetNewInstanceCount());
base::RunLoop loop;
lifecycle.set_disconnect_handler(loop.QuitClosure());
lifecycle->GracefulQuit();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_FALSE(instances()->HasInstanceForName(kTestAppName));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
TEST_F(LifecycleTest, PackagedApp_Crash) {
if (!CanRunCrashTest()) {
LOG(INFO) << "Skipping Standalone_Crash test in --single-process mode.";
return;
}
mojo::Remote<test::mojom::LifecycleControl> lifecycle =
ConnectTo(kTestPackageAppNameA);
// There should be two new instances - one for the app and one for the package
// that vended it.
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_EQ(2u, instances()->GetNewInstanceCount());
base::RunLoop loop;
lifecycle.set_disconnect_handler(loop.QuitClosure());
lifecycle->Crash();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
// When a single package provides multiple apps out of one process, crashing one
// app crashes all.
TEST_F(LifecycleTest, PackagedApp_CrashCrashesOtherProvidedApp) {
if (!CanRunCrashTest()) {
LOG(INFO) << "Skipping Standalone_Crash test in --single-process mode.";
return;
}
mojo::Remote<test::mojom::LifecycleControl> lifecycle_a =
ConnectTo(kTestPackageAppNameA);
mojo::Remote<test::mojom::LifecycleControl> lifecycle_b =
ConnectTo(kTestPackageAppNameB);
mojo::Remote<test::mojom::LifecycleControl> lifecycle_package =
ConnectTo(kTestPackageName);
// There should be three instances, one for each packaged app and the package
// itself.
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameB));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageName));
size_t instance_count = instances()->GetNewInstanceCount();
ASSERT_EQ(3u, instance_count);
base::RunLoop loop;
base::RepeatingClosure quit_on_last = base::BarrierClosure(
static_cast<int>(instance_count), loop.QuitClosure());
lifecycle_a.set_disconnect_handler(quit_on_last);
lifecycle_b.set_disconnect_handler(quit_on_last);
lifecycle_package.set_disconnect_handler(quit_on_last);
// Now crash one of the packaged apps.
lifecycle_a->Crash();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageAppNameB));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
// When a single package provides multiple apps out of one process, crashing one
// app crashes all.
TEST_F(LifecycleTest, PackagedApp_GracefulQuitPackageQuitsAll) {
mojo::Remote<test::mojom::LifecycleControl> lifecycle_a =
ConnectTo(kTestPackageAppNameA);
mojo::Remote<test::mojom::LifecycleControl> lifecycle_b =
ConnectTo(kTestPackageAppNameB);
mojo::Remote<test::mojom::LifecycleControl> lifecycle_package =
ConnectTo(kTestPackageName);
// There should be three instances, one for each packaged app and the package
// itself.
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageAppNameB));
EXPECT_TRUE(instances()->HasInstanceForName(kTestPackageName));
size_t instance_count = instances()->GetNewInstanceCount();
ASSERT_EQ(3u, instance_count);
base::RunLoop loop;
base::RepeatingClosure quit_on_last = base::BarrierClosure(
static_cast<int>(instance_count), loop.QuitClosure());
lifecycle_a.set_disconnect_handler(quit_on_last);
lifecycle_b.set_disconnect_handler(quit_on_last);
lifecycle_package.set_disconnect_handler(quit_on_last);
// Now quit the package. All the packaged apps should close.
lifecycle_package->GracefulQuit();
loop.Run();
instances()->WaitForInstanceDestruction();
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageName));
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageAppNameA));
EXPECT_FALSE(instances()->HasInstanceForName(kTestPackageAppNameB));
EXPECT_EQ(0u, instances()->GetNewInstanceCount());
}
} // namespace service_manager
| 6,352 |
796 | <reponame>ProtectorYT364/BlockLauncher
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_MAX_NUM_ERRORS
#define net_zhuoweizhang_mcpelauncher_ScriptManager_MAX_NUM_ERRORS 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_X
#define net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_X 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_Y
#define net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_Y 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_Z
#define net_zhuoweizhang_mcpelauncher_ScriptManager_AXIS_Z 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_ITEMID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_ITEMID 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_DAMAGE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_DAMAGE 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_AMOUNT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_AMOUNT 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_ARCH_ARM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_ARCH_ARM 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_ARCH_I386
#define net_zhuoweizhang_mcpelauncher_ScriptManager_ARCH_I386 1L
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetPlayerLoc
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetPlayerLoc
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetPlayerEnt
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetPlayerEnt
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetLevel
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetLevel
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetPosition
* Signature: (JFFF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetPosition
(JNIEnv *, jclass, jlong, jfloat, jfloat, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetVel
* Signature: (JFI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetVel
(JNIEnv *, jclass, jlong, jfloat, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeExplode
* Signature: (FFFFZZF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeExplode
(JNIEnv *, jclass, jfloat, jfloat, jfloat, jfloat, jboolean, jboolean, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddItemInventory
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddItemInventory
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeRideAnimal
* Signature: (JJ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeRideAnimal
(JNIEnv *, jclass, jlong, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetCarriedItem
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetCarriedItem
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePreventDefault
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePreventDefault
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetTile
* Signature: (IIIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetTile
(JNIEnv *, jclass, jint, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSpawnEntity
* Signature: (FFFILjava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSpawnEntity
(JNIEnv *, jclass, jfloat, jfloat, jfloat, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeClientMessage
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeClientMessage
(JNIEnv *, jclass, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetNightMode
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetNightMode
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetTile
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetTile
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetPositionRelative
* Signature: (JFFF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetPositionRelative
(JNIEnv *, jclass, jlong, jfloat, jfloat, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetRot
* Signature: (JFF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetRot
(JNIEnv *, jclass, jlong, jfloat, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetYaw
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetYaw
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetPitch
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetPitch
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetCarriedItem
* Signature: (JIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetCarriedItem
(JNIEnv *, jclass, jlong, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeOnGraphicsReset
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeOnGraphicsReset
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDefineItem
* Signature: (ILjava/lang/String;ILjava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDefineItem
(JNIEnv *, jclass, jint, jstring, jint, jstring, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetFov
* Signature: (FZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetFov
(JNIEnv *, jclass, jfloat, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetMobSkin
* Signature: (JLjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetMobSkin
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetEntityLoc
* Signature: (JI)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetEntityLoc
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeRemoveEntity
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeRemoveEntity
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetEntityTypeId
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetEntityTypeId
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetAnimalAge
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetAnimalAge
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetAnimalAge
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetAnimalAge
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSelectLevel
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSelectLevel
(JNIEnv *, jclass, jstring, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLeaveGame
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLeaveGame
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeJoinServer
* Signature: (Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeJoinServer
(JNIEnv *, jclass, jstring, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetGameSpeed
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetGameSpeed
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetAllEntities
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetAllEntities
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetSelectedSlotId
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetSelectedSlotId
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetSelectedSlotId
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetSelectedSlotId
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetMobHealth
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetMobHealth
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetMobHealth
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetMobHealth
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetMobMaxHealth
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetMobMaxHealth
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetEntityRenderType
* Signature: (JI)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetEntityRenderType
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeRequestFrameCallback
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeRequestFrameCallback
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetSignText
* Signature: (III)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetSignText
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetSignText
* Signature: (IIILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetSignText
(JNIEnv *, jclass, jint, jint, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetSneaking
* Signature: (JZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetSneaking
(JNIEnv *, jclass, jlong, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeIsSneaking
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeIsSneaking
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetPlayerName
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetPlayerName
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemName
* Signature: (IIZ)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemName
(JNIEnv *, jclass, jint, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetTextureCoordinatesForItem
* Signature: (II[F)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetTextureCoordinatesForItem
(JNIEnv *, jclass, jint, jint, jfloatArray);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetTextureCoordinatesForBlock
* Signature: (III[F)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetTextureCoordinatesForBlock
(JNIEnv *, jclass, jint, jint, jint, jfloatArray);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDefineBlock
* Signature: (ILjava/lang/String;[Ljava/lang/String;[IIZII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDefineBlock
(JNIEnv *, jclass, jint, jstring, jobjectArray, jintArray, jint, jboolean, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetDestroyTime
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetDestroyTime
(JNIEnv *, jclass, jint, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetExplosionResistance
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetExplosionResistance
(JNIEnv *, jclass, jint, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetStepSound
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetStepSound
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetLightLevel
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetLightLevel
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetLightOpacity
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetLightOpacity
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetColor
* Signature: (I[I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetColor
(JNIEnv *, jclass, jint, jintArray);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetShape
* Signature: (IFFFFFFI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetShape
(JNIEnv *, jclass, jint, jfloat, jfloat, jfloat, jfloat, jfloat, jfloat, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetRenderLayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetRenderLayer
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockGetRenderLayer
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockGetRenderLayer
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetInventorySlot
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetInventorySlot
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetEntityVel
* Signature: (JI)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetEntityVel
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetI18NString
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetI18NString
(JNIEnv *, jclass, jstring, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddShapedRecipe
* Signature: (III[Ljava/lang/String;[I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddShapedRecipe
(JNIEnv *, jclass, jint, jint, jint, jobjectArray, jintArray);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeShowTipMessage
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeShowTipMessage
(JNIEnv *, jclass, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntitySetNameTag
* Signature: (JLjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntitySetNameTag
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetStonecutterItem
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetStonecutterItem
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetItemCategory
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetItemCategory
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSendChat
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSendChat
(JNIEnv *, jclass, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetNameTag
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetNameTag
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetRiding
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetRiding
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetRider
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetRider
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetMobSkin
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetMobSkin
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetRenderType
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetRenderType
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetCameraEntity
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetCameraEntity
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetUUID
* Signature: (J)[J
*/
JNIEXPORT jlongArray JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetUUID
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelAddParticle
* Signature: (Ljava/lang/String;FFFFFFI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelAddParticle
(JNIEnv *, jclass, jstring, jfloat, jfloat, jfloat, jfloat, jfloat, jfloat, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetData
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetData
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeHurtTo
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeHurtTo
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDestroyBlock
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDestroyBlock
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetTime
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetTime
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetTime
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetTime
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetGameType
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetGameType
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetGameType
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetGameType
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetOnFire
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetOnFire
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetSpawn
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetSpawn
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddItemChest
* Signature: (IIIIIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddItemChest
(JNIEnv *, jclass, jint, jint, jint, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemChest
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemChest
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemDataChest
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemDataChest
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemCountChest
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemCountChest
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemNameChest
* Signature: (IIII)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemNameChest
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetItemNameChest
* Signature: (IIIILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetItemNameChest
(JNIEnv *, jclass, jint, jint, jint, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDropItem
* Signature: (FFFFIII)J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDropItem
(JNIEnv *, jclass, jfloat, jfloat, jfloat, jfloat, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlaySound
* Signature: (FFFLjava/lang/String;FF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlaySound
(JNIEnv *, jclass, jfloat, jfloat, jfloat, jstring, jfloat, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeClearSlotInventory
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeClearSlotInventory
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetSlotInventory
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetSlotInventory
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddItemCreativeInv
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddItemCreativeInv
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeExtinguishFire
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeExtinguishFire
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobGetArmor
* Signature: (JII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobGetArmor
(JNIEnv *, jclass, jlong, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobSetArmor
* Signature: (JIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobSetArmor
(JNIEnv *, jclass, jlong, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetBrightness
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetBrightness
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddFurnaceRecipe
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddFurnaceRecipe
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeAddItemFurnace
* Signature: (IIIIIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeAddItemFurnace
(JNIEnv *, jclass, jint, jint, jint, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemFurnace
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemFurnace
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemDataFurnace
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemDataFurnace
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemCountFurnace
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemCountFurnace
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetItemMaxDamage
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetItemMaxDamage
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetBlockRenderShape
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetBlockRenderShape
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetBlockRenderShape
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetBlockRenderShape
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeIsBlockTextureAtlasLoaded
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeIsBlockTextureAtlasLoaded
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDefinePlaceholderBlocks
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDefinePlaceholderBlocks
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetPointedEntity
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetPointedEntity
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetPointedBlock
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetPointedBlock
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetPointedVec
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetPointedVec
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetBiome
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetBiome
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetBiomeName
* Signature: (II)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetBiomeName
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBiomeIdToName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBiomeIdToName
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetBiome
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetBiome
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetGrassColor
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetGrassColor
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetGrassColor
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetGrassColor
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerIsFlying
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerIsFlying
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetFlying
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetFlying
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerCanFly
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerCanFly
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetCanFly
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetCanFly
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetCollisionEnabled
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetCollisionEnabled
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntitySetSize
* Signature: (JFF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntitySetSize
(JNIEnv *, jclass, jlong, jfloat, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetCape
* Signature: (JLjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetCape
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeClearCapes
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeClearCapes
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetHandEquipped
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetHandEquipped
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSpawnerSetEntityType
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSpawnerSetEntityType
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSpawnerGetEntityType
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSpawnerGetEntityType
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDefineArmor
* Signature: (ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDefineArmor
(JNIEnv *, jclass, jint, jstring, jint, jstring, jstring, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeScreenChooserSetScreen
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeScreenChooserSetScreen
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeCloseScreen
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeCloseScreen
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeShowProgressScreen
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeShowProgressScreen
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobAddEffect
* Signature: (JIIIZZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobAddEffect
(JNIEnv *, jclass, jlong, jint, jint, jint, jboolean, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobRemoveEffect
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobRemoveEffect
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobRemoveAllEffects
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobRemoveAllEffects
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemEntityItem
* Signature: (JI)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemEntityItem
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeIsValidItem
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeIsValidItem
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeIsValidCommand
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeIsValidCommand
(JNIEnv *, jclass, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockGetSecondPart
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockGetSecondPart
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetDimension
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetDimension
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetLightningLevel
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetLightningLevel
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetLightningLevel
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetLightningLevel
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetRainLevel
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetRainLevel
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetRainLevel
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetRainLevel
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetHunger
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetHunger
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetHunger
* Signature: (JF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetHunger
(JNIEnv *, jclass, jlong, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetExhaustion
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetExhaustion
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetExhaustion
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetExhaustion
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetSaturation
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetSaturation
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetSaturation
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetSaturation
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetExperience
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetExperience
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetExperience
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetExperience
(JNIEnv *, jclass, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetLevel
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetLevel
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetLevel
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetLevel
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerAddExperience
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerAddExperience
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetMobMaxHealth
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetMobMaxHealth
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockGetDestroyTime
* Signature: (II)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockGetDestroyTime
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockGetFriction
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockGetFriction
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetFriction
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetFriction
(JNIEnv *, jclass, jint, jfloat);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeBlockSetRedstoneConsumer
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeBlockSetRedstoneConsumer
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelCanSeeSky
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelCanSeeSky
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemSetProperties
* Signature: (ILjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemSetProperties
(JNIEnv *, jclass, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetI18NString
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetI18NString
(JNIEnv *, jclass, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetLanguageName
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetLanguageName
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemGetUseAnimation
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemGetUseAnimation
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemSetUseAnimation
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemSetUseAnimation
(JNIEnv *, jclass, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemSetStackedByData
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemSetStackedByData
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerEnchant
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerEnchant
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetEnchantments
* Signature: (I)[I
*/
JNIEXPORT jintArray JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetEnchantments
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetItemCustomName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetItemCustomName
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerSetItemCustomName
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerSetItemCustomName
(JNIEnv *, jclass, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetAllowEnchantments
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetAllowEnchantments
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetDifficulty
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetDifficulty
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetDifficulty
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetDifficulty
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeArmorAddQueuedTextures
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeArmorAddQueuedTextures
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityHasCustomSkin
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityHasCustomSkin
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntitySetImmobile
* Signature: (JZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntitySetImmobile
(JNIEnv *, jclass, jlong, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeModPESetRenderDebug
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeModPESetRenderDebug
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetTarget
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetTarget
(JNIEnv *, jclass, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntitySetTarget
* Signature: (JJ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntitySetTarget
(JNIEnv *, jclass, jlong, jlong);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePlayerGetScore
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePlayerGetScore
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobGetArmorCustomName
* Signature: (JI)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobGetArmorCustomName
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeMobSetArmorCustomName
* Signature: (JILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeMobSetArmorCustomName
(JNIEnv *, jclass, jlong, jint, jstring);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemMaxDamage
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemMaxDamage
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeEntityGetCarriedItem
* Signature: (JI)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeEntityGetCarriedItem
(JNIEnv *, jclass, jlong, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemGetMaxStackSize
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemGetMaxStackSize
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDefineSnowballItem
* Signature: (ILjava/lang/String;ILjava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDefineSnowballItem
(JNIEnv *, jclass, jint, jstring, jint, jstring, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelSetExtraData
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelSetExtraData
(JNIEnv *, jclass, jint, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelGetExtraData
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelGetExtraData
(JNIEnv *, jclass, jint, jint, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeItemIsExtendedBlock
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeItemIsExtendedBlock
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelExecuteCommand
* Signature: (Ljava/lang/String;Z)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelExecuteCommand
(JNIEnv *, jclass, jstring, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetServerPlayers
* Signature: ()[J
*/
JNIEXPORT jlongArray JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetServerPlayers
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetupHooks
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetupHooks
(JNIEnv *, jclass, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeRemoveItemBackground
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeRemoveItemBackground
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetTextParseColorCodes
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetTextParseColorCodes
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativePrePatch
* Signature: (ZLcom/mojang/minecraftpe/MainActivity;Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativePrePatch
(JNIEnv *, jclass, jboolean, jobject, jboolean, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeLevelIsRemote
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeLevelIsRemote
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetIsRecording
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetIsRecording
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeForceCrash
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeForceCrash
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetArch
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetArch
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetUseController
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetUseController
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeDumpVtable
* Signature: (Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeDumpVtable
(JNIEnv *, jclass, jstring, jint);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeGetItemIdCount
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeGetItemIdCount
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeSetExitEnabled
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetExitEnabled
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeRecipeSetAnyAuxValue
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeRecipeSetAnyAuxValue
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeModPESetDesktopGui
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeModPESetDesktopGui
(JNIEnv *, jclass, jboolean);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeNewLevelCallbackStarted
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeNewLevelCallbackStarted
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeNewLevelCallbackEnded
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeNewLevelCallbackEnded
(JNIEnv *, jclass);
/*
* Class: net_zhuoweizhang_mcpelauncher_ScriptManager
* Method: nativeHasPreventedDefault
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeHasPreventedDefault
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_TextureRequests */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_TextureRequests
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_TextureRequests
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_AfterCapeDownloadAction */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_AfterCapeDownloadAction
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_AfterCapeDownloadAction
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_AfterSkinDownloadAction */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_AfterSkinDownloadAction
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_AfterSkinDownloadAction
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_JoinServerRequest */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_JoinServerRequest
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_JoinServerRequest
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_SelectLevelRequest */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_SelectLevelRequest
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_SelectLevelRequest
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeGuiApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeServerApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeBlockApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeItemApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeModPEApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeEntityApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_EnchantmentInstance */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_EnchantmentInstance
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_EnchantmentInstance
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePlayerApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativeLevelApi_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_NativePointer_INITIAL_SLOT_SIZE 4L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID 2829861078851942586LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_EMPTY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_EMPTY 0L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_READONLY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_READONLY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_DONTENUM
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_DONTENUM 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_PERMANENT
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_PERMANENT 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_UNINITIALIZED_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_UNINITIALIZED_CONST 8L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_CONST 13L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_QUERY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_QUERY 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY_CONST
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY_CONST 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY_GETTER_SETTER
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_MODIFY_GETTER_SETTER 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_CONVERT_ACCESSOR_TO_DATA
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_SLOT_CONVERT_ACCESSOR_TO_DATA 5L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_INITIAL_SLOT_SIZE
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_INITIAL_SLOT_SIZE 4L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID -4648046356662472260LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_serialVersionUID -9095380847465315412LL
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_constructor
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_constructor 1L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_importClass
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_importClass 2L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_importPackage
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_Id_importPackage 3L
#undef net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_MAX_PROTOTYPE_ID
#define net_zhuoweizhang_mcpelauncher_ScriptManager_BlockHostObject_MAX_PROTOTYPE_ID 3L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_ScriptState */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_ScriptState
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_ScriptState
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_MyMethodWatcher */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_MyMethodWatcher
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_MyMethodWatcher
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_SkinLoader */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_SkinLoader
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_SkinLoader
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
/* Header for class net_zhuoweizhang_mcpelauncher_ScriptManager_ParseThread */
#ifndef _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_ParseThread
#define _Included_net_zhuoweizhang_mcpelauncher_ScriptManager_ParseThread
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
| 33,538 |
372 | <filename>clients/google-api-services-sheets/v4/1.30.1/com/google/api/services/sheets/v4/model/UpdateBordersRequest.java
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.sheets.v4.model;
/**
* Updates the borders of a range. If a field is not set in the request, that means the border
* remains as-is. For example, with two subsequent UpdateBordersRequest:
*
* 1. range: A1:A5 `{ top: RED, bottom: WHITE }` 2. range: A1:A5 `{ left: BLUE }`
*
* That would result in A1:A5 having a borders of `{ top: RED, bottom: WHITE, left: BLUE }`. If you
* want to clear a border, explicitly set the style to NONE.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Sheets API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class UpdateBordersRequest extends com.google.api.client.json.GenericJson {
/**
* The border to put at the bottom of the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border bottom;
/**
* The horizontal border to put within the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border innerHorizontal;
/**
* The vertical border to put within the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border innerVertical;
/**
* The border to put at the left of the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border left;
/**
* The range whose borders should be updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GridRange range;
/**
* The border to put at the right of the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border right;
/**
* The border to put at the top of the range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Border top;
/**
* The border to put at the bottom of the range.
* @return value or {@code null} for none
*/
public Border getBottom() {
return bottom;
}
/**
* The border to put at the bottom of the range.
* @param bottom bottom or {@code null} for none
*/
public UpdateBordersRequest setBottom(Border bottom) {
this.bottom = bottom;
return this;
}
/**
* The horizontal border to put within the range.
* @return value or {@code null} for none
*/
public Border getInnerHorizontal() {
return innerHorizontal;
}
/**
* The horizontal border to put within the range.
* @param innerHorizontal innerHorizontal or {@code null} for none
*/
public UpdateBordersRequest setInnerHorizontal(Border innerHorizontal) {
this.innerHorizontal = innerHorizontal;
return this;
}
/**
* The vertical border to put within the range.
* @return value or {@code null} for none
*/
public Border getInnerVertical() {
return innerVertical;
}
/**
* The vertical border to put within the range.
* @param innerVertical innerVertical or {@code null} for none
*/
public UpdateBordersRequest setInnerVertical(Border innerVertical) {
this.innerVertical = innerVertical;
return this;
}
/**
* The border to put at the left of the range.
* @return value or {@code null} for none
*/
public Border getLeft() {
return left;
}
/**
* The border to put at the left of the range.
* @param left left or {@code null} for none
*/
public UpdateBordersRequest setLeft(Border left) {
this.left = left;
return this;
}
/**
* The range whose borders should be updated.
* @return value or {@code null} for none
*/
public GridRange getRange() {
return range;
}
/**
* The range whose borders should be updated.
* @param range range or {@code null} for none
*/
public UpdateBordersRequest setRange(GridRange range) {
this.range = range;
return this;
}
/**
* The border to put at the right of the range.
* @return value or {@code null} for none
*/
public Border getRight() {
return right;
}
/**
* The border to put at the right of the range.
* @param right right or {@code null} for none
*/
public UpdateBordersRequest setRight(Border right) {
this.right = right;
return this;
}
/**
* The border to put at the top of the range.
* @return value or {@code null} for none
*/
public Border getTop() {
return top;
}
/**
* The border to put at the top of the range.
* @param top top or {@code null} for none
*/
public UpdateBordersRequest setTop(Border top) {
this.top = top;
return this;
}
@Override
public UpdateBordersRequest set(String fieldName, Object value) {
return (UpdateBordersRequest) super.set(fieldName, value);
}
@Override
public UpdateBordersRequest clone() {
return (UpdateBordersRequest) super.clone();
}
}
| 1,914 |
1,015 | <gh_stars>1000+
#include <numeric>
#include <algorithm>
#include <cstdint>
#include <string>
#include <charconv>
namespace dxvk {
/**
* \brief Simplest ratio helper
*/
template <typename T>
class Ratio {
public:
Ratio(T num, T denom) {
set(num, denom);
}
Ratio(std::string_view view) {
set(0, 0);
size_t colon = view.find(":");
if (colon == std::string_view::npos)
return;
std::string_view numStr = view.substr(0, colon);
std::string_view denomStr = view.substr(colon + 1);
T num = 0, denom = 0;
std::from_chars(numStr.data(), numStr.data() + numStr.size(), num);
std::from_chars(denomStr.data(), denomStr.data() + denomStr.size(), denom);
set(num, denom);
}
inline T num() const { return m_num; }
inline T denom() const { return m_denom; }
inline bool undefined() const { return m_denom == 0; }
inline void set(T num, T denom) {
const T gcd = std::gcd(num, denom);
m_num = num / gcd;
m_denom = denom / gcd;
}
inline bool operator == (const Ratio& other) const {
return num() == other.num() && denom() == other.denom();
}
inline bool operator != (const Ratio& other) const {
return !(*this == other);
}
inline bool operator >= (const Ratio& other) const {
return num() * other.denom() >= other.num() * denom();
}
inline bool operator > (const Ratio& other) const {
return num() * other.denom() > other.num() * denom();
}
inline bool operator < (const Ratio& other) const {
return !(*this >= other);
}
inline bool operator <= (const Ratio& other) const {
return !(*this > other);
}
private:
T m_num, m_denom;
};
} | 740 |
12,718 | <reponame>Bhuvanesh1208/ruby2.6.1<gh_stars>1000+
/**
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER within this package.
*/
#ifndef _NLDEF_
#define _NLDEF_
#include <winapifamily.h>
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP) || _WIN32_WINNT >= 0x0A00
typedef enum {
NldsInvalid,
NldsTentative,
NldsDuplicate,
NldsDeprecated,
NldsPreferred,
IpDadStateInvalid = 0,
IpDadStateTentative,
IpDadStateDuplicate,
IpDadStateDeprecated,
IpDadStatePreferred,
} NL_DAD_STATE;
#define MAKE_ROUTE_PROTOCOL(N, V) MIB_IPPROTO_ ## N = V, PROTO_IP_ ## N = V
typedef enum {
RouteProtocolOther = 1,
RouteProtocolLocal = 2,
RouteProtocolNetMgmt = 3,
RouteProtocolIcmp = 4,
RouteProtocolEgp = 5,
RouteProtocolGgp = 6,
RouteProtocolHello = 7,
RouteProtocolRip = 8,
RouteProtocolIsIs = 9,
RouteProtocolEsIs = 10,
RouteProtocolCisco = 11,
RouteProtocolBbn = 12,
RouteProtocolOspf = 13,
RouteProtocolBgp = 14,
MAKE_ROUTE_PROTOCOL (OTHER, 1),
MAKE_ROUTE_PROTOCOL (LOCAL, 2),
MAKE_ROUTE_PROTOCOL (NETMGMT, 3),
MAKE_ROUTE_PROTOCOL (ICMP, 4),
MAKE_ROUTE_PROTOCOL (EGP, 5),
MAKE_ROUTE_PROTOCOL (GGP, 6),
MAKE_ROUTE_PROTOCOL (HELLO, 7),
MAKE_ROUTE_PROTOCOL (RIP, 8),
MAKE_ROUTE_PROTOCOL (IS_IS, 9),
MAKE_ROUTE_PROTOCOL (ES_IS, 10),
MAKE_ROUTE_PROTOCOL (CISCO, 11),
MAKE_ROUTE_PROTOCOL (BBN, 12),
MAKE_ROUTE_PROTOCOL (OSPF, 13),
MAKE_ROUTE_PROTOCOL (BGP, 14),
MAKE_ROUTE_PROTOCOL (NT_AUTOSTATIC, 10002),
MAKE_ROUTE_PROTOCOL (NT_STATIC, 10006),
MAKE_ROUTE_PROTOCOL (NT_STATIC_NON_DOD, 10007)
} NL_ROUTE_PROTOCOL,*PNL_ROUTE_PROTOCOL;
typedef enum {
IpPrefixOriginOther = 0,
IpPrefixOriginManual,
IpPrefixOriginWellKnown,
IpPrefixOriginDhcp,
IpPrefixOriginRouterAdvertisement,
IpPrefixOriginUnchanged = 16
} NL_PREFIX_ORIGIN;
typedef enum {
NlsoOther = 0,
NlsoManual,
NlsoWellKnown,
NlsoDhcp,
NlsoLinkLayerAddress,
NlsoRandom,
IpSuffixOriginOther = 0,
IpSuffixOriginManual,
IpSuffixOriginWellKnown,
IpSuffixOriginDhcp,
IpSuffixOriginLinkLayerAddress,
IpSuffixOriginRandom,
IpSuffixOriginUnchanged = 16
} NL_SUFFIX_ORIGIN;
typedef enum {
NlatUnspecified,
NlatUnicast,
NlatAnycast,
NlatMulticast,
NlatBroadcast,
NlatInvalid
} NL_ADDRESS_TYPE, *PNL_ADDRESS_TYPE;
typedef enum _NL_ROUTE_ORIGIN {
NlroManual,
NlroWellKnown,
NlroDHCP,
NlroRouterAdvertisement,
Nlro6to4,
} NL_ROUTE_ORIGIN, *PNL_ROUTE_ORIGIN;
typedef enum _NL_NEIGHBOR_STATE {
NlnsUnreachable,
NlnsIncomplete,
NlnsProbe,
NlnsDelay,
NlnsStale,
NlnsReachable,
NlnsPermanent,
NlnsMaximum,
} NL_NEIGHBOR_STATE, *PNL_NEIGHBOR_STATE;
typedef enum _NL_LINK_LOCAL_ADDRESS_BEHAVIOR {
LinkLocalAlwaysOff = 0,
LinkLocalDelayed,
LinkLocalAlwaysOn,
LinkLocalUnchanged = -1
} NL_LINK_LOCAL_ADDRESS_BEHAVIOR;
typedef enum _NL_ROUTER_DISCOVERY_BEHAVIOR {
RouterDiscoveryDisabled = 0,
RouterDiscoveryEnabled,
RouterDiscoveryDhcp,
RouterDiscoveryUnchanged = -1
} NL_ROUTER_DISCOVERY_BEHAVIOR;
typedef enum _NL_BANDWIDTH_FLAG {
NlbwDisabled = 0,
NlbwEnabled,
NlbwUnchanged = -1
} NL_BANDWIDTH_FLAG, *PNL_BANDWIDTH_FLAG;
typedef enum _NL_INTERFACE_NETWORK_CATEGORY_STATE {
NlincCategoryUnknown = 0,
NlincPublic = 1,
NlincPrivate = 2,
NlincDomainAuthenticated = 3,
NlincCategoryStateMax
} NL_INTERFACE_NETWORK_CATEGORY_STATE, *PNL_INTERFACE_NETWORK_CATEGORY_STATE;
typedef struct _NL_INTERFACE_OFFLOAD_ROD {
BOOLEAN NlChecksumSupported : 1;
BOOLEAN NlOptionsSupported : 1;
BOOLEAN TlDatagramChecksumSupported : 1;
BOOLEAN TlStreamChecksumSupported : 1;
BOOLEAN TlStreamOptionsSupported : 1;
BOOLEAN FastPathCompatible : 1;
BOOLEAN TlLargeSendOffloadSupported : 1;
BOOLEAN TlGiantSendOffloadSupported : 1;
} NL_INTERFACE_OFFLOAD_ROD, *PNL_INTERFACE_OFFLOAD_ROD;
typedef struct _NL_PATH_BANDWIDTH_ROD {
ULONG64 Bandwidth;
ULONG64 Instability;
BOOLEAN BandwidthPeaked;
} NL_PATH_BANDWIDTH_ROD, *PNL_PATH_BANDWIDTH_ROD;
typedef enum _NL_NETWORK_CATEGORY {
NetworkCategoryPublic,
NetworkCategoryPrivate,
NetworkCategoryDomainAuthenticated,
NetworkCategoryUnchanged = -1,
NetworkCategoryUnknown = -1
} NL_NETWORK_CATEGORY,*PNL_NETWORK_CATEGORY;
typedef struct _NL_BANDWIDTH_INFORMATION {
ULONG64 Bandwidth;
ULONG64 Instability;
BOOLEAN BandwidthPeaked;
} NL_BANDWIDTH_INFORMATION, *PNL_BANDWIDTH_INFORMATION;
#define NlpoOther IpPrefixOriginOther
#define NlpoManual IpPrefixOriginManual
#define NlpoWellKnown IpPrefixOriginWellKnown
#define NlpoDhcp IpPrefixOriginDhcp
#define NlpoRouterAdvertisement IpPrefixOriginRouterAdvertisement
#define NL_MAX_METRIC_COMPONENT ((((ULONG) 1) << 31) - 1)
#define NET_IF_CURRENT_SESSION ((ULONG)-1)
#endif
#endif
| 2,111 |
413 | <gh_stars>100-1000
#ifndef CAFFE_CUDNN_SIGMOID_LAYER_HPP_
#define CAFFE_CUDNN_SIGMOID_LAYER_HPP_
#include "./cudnn.hpp"
#include "../sigmoid_layer.hpp"
namespace caffe {
#ifdef USE_CUDNN
/**
* @brief CuDNN acceleration of SigmoidLayer.
*/
class CuDNNSigmoidLayer : public SigmoidLayer {
public:
explicit CuDNNSigmoidLayer(const LayerParameter& param)
: SigmoidLayer(param), handles_setup_(false) {}
virtual void LayerSetUp(const vector<Blob*>& bottom,
const vector<Blob*>& top);
virtual void Reshape(const vector<Blob*>& bottom,
const vector<Blob*>& top);
virtual ~CuDNNSigmoidLayer();
protected:
virtual void Forward_gpu(const vector<Blob*>& bottom,
const vector<Blob*>& top);
bool handles_setup_;
cudnnHandle_t handle_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnTensorDescriptor_t top_desc_;
cudnnActivationDescriptor_t activ_desc_;
};
#endif // USE_CUDNN
} // namespace caffe
#endif // CAFFE_CUDNN_SIGMOID_LAYER_HPP_
| 466 |
1,587 | import pytest
# we want to have pytest assert introspection in the helpers
pytest.register_assert_rewrite('tests.helpers')
| 35 |
3,428 | <filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-1/00645.2d95a6a89614625aafb7b333e799e111.json<gh_stars>1000+
{"id":"00645","group":"easy-ham-1","checksum":{"type":"MD5","value":"2d95a6a89614625aafb7b333e799e111"},"text":"From <EMAIL> Thu Sep 19 16:25:55 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>assass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id ADC1216F03\n\tfor <jm@localhost>; Thu, 19 Sep 2002 16:25:54 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 19 Sep 2002 16:25:54 +0100 (IST)\nReceived: from xent.com ([192.168.3.1136]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g8JDZqC21671 for <<EMAIL>>;\n Thu, 19 Sep 2002 14:35:52 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id D8CCB294159; Thu, 19 Sep 2002 06:32:05 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from hotmail.com (f174.law15.hotmail.com [64.4.23.174]) by\n xent.com (Postfix) with ESMTP id A7D9629410C for <<EMAIL>>;\n Thu, 19 Sep 2002 06:31:12 -0700 (PDT)\nReceived: from mail pickup service by hotmail.com with Microsoft SMTPSVC;\n Thu, 19 Sep 2002 06:34:36 -0700\nReceived: from 172.16.17.32 by lw15fd.law15.hotmail.msn.com with HTTP;\n Thu, 19 Sep 2002 13:34:36 GMT\nX-Originating-Ip: [216.30.74.2]\nFrom: \"<NAME>\" <<EMAIL>>\nTo: <EMAIL>\nSubject: Re: [VoID] a new low on the personals tip...\nMIME-Version: 1.0\nContent-Type: text/plain; format=flowed\nMessage-Id: <<EMAIL>>\nX-Originalarrivaltime: 19 Sep 2002 13:34:36.0926 (UTC) FILETIME=[4C2049E0:01C25FE1]\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Thu, 19 Sep 2002 13:34:36 +0000\n\nOwne Byrne:\n>Sure if you're willing to risk firing, lawsuits, etc. The last full time \n>job I had the sexual harassement seminar was pretty clear - yes you can \n>have relationships at the office, but its extremely difficult, and the \n>pitfalls are\n>horrendous.\n\nDespite that, this is how a lot of couples meet.\nPeople tease me about Carolyn, that I just hired\na lot of software engineering babes, and then\nchose the one I liked best. ;-)\n\n\n\n\n\n\n_________________________________________________________________\nSend and receive Hotmail on your mobile device: http://mobile.msn.com\n\n\n"} | 1,150 |
964 | [
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 2,
"filename": "positive1.json"
},
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 43,
"filename": "positive2.json"
},
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 44,
"filename": "positive3.json"
},
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 1,
"filename": "positive4.yaml"
},
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 25,
"filename": "positive5.yaml"
},
{
"queryName": "Field 'securityScheme' On Components Is Undefined",
"severity": "HIGH",
"line": 26,
"filename": "positive6.yaml"
}
]
| 373 |
852 | <filename>TrackingTools/PatternTools/interface/TransverseImpactPointExtrapolator.h<gh_stars>100-1000
#ifndef TransverseImpactPointExtrapolator_h_
#define TransverseImpactPointExtrapolator_h_
#include "TrackingTools/GeomPropagators/interface/Propagator.h"
#include "DataFormats/GeometryVector/interface/GlobalPoint.h"
#include "DataFormats/GeometryVector/interface/GlobalVector.h"
#include "DataFormats/GeometryCommonDetAlgo/interface/DeepCopyPointerByClone.h"
#include "MagneticField/Engine/interface/MagneticField.h"
class FreeTrajectoryState;
class TrajectoryStateOnSurface;
class Plane;
template <class T>
class ReferenceCountingPointer;
/** Extrapolate to impact point with respect to vtx,
* i.e. point of closest approach to vtx in 2D.
* The surface of the returned TrajectoryStateOnSurface
* is chosen centred on vtx;
* the axes of the local coordinate system (x_loc, y_loc, z_loc) are
* z_loc // trajectory direction in transverse plane at impact point;
* x_loc normal to trajectory and along impact vector (impact point - vtx);
* y_loc forms a right-handed system with the other axes.
*/
class TransverseImpactPointExtrapolator {
public:
/// constructor with default geometrical propagator
TransverseImpactPointExtrapolator();
/// constructor with default geometrical propagator
TransverseImpactPointExtrapolator(const MagneticField* field);
/// constructor with user-supplied propagator
TransverseImpactPointExtrapolator(const Propagator& u);
/// extrapolation with default (=geometrical) propagator
TrajectoryStateOnSurface extrapolate(const FreeTrajectoryState& fts, const GlobalPoint& vtx) const;
/// as above, but from TrajectoryStateOnSurface
TrajectoryStateOnSurface extrapolate(const TrajectoryStateOnSurface tsos, const GlobalPoint& vtx) const;
/// extrapolation with user-supplied propagator
TrajectoryStateOnSurface extrapolate(const FreeTrajectoryState& fts,
const GlobalPoint& vtx,
const Propagator& u) const;
/// as above, but from TrajectoryStateOnSurface
TrajectoryStateOnSurface extrapolate(const TrajectoryStateOnSurface tsos,
const GlobalPoint& vtx,
const Propagator& u) const;
private:
/// extrapolation of (multi) TSOS with (internal or user-supplied) propagator
TrajectoryStateOnSurface doExtrapolation(const TrajectoryStateOnSurface tsos,
const GlobalPoint& vtx,
const Propagator& u) const;
/// extrapolation of (single) FTS with (internal or user-supplied) propagator
TrajectoryStateOnSurface doExtrapolation(const FreeTrajectoryState& fts,
const GlobalPoint& vtx,
const Propagator& u) const;
/// computation of the TIP surface
ReferenceCountingPointer<Plane> tipSurface(const GlobalPoint& position,
const GlobalVector& momentum,
const double& signedTransverseRadius,
const GlobalPoint& vtx) const;
private:
DeepCopyPointerByClone<Propagator> thePropagator;
};
#endif
| 1,310 |
2,027 | <gh_stars>1000+
/*
* Copyright 2016-present Open Networking 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 io.atomix.core.multimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.atomix.core.AbstractPrimitiveTest;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests the {@link DistributedMultimap}.
*/
public class DistributedMultimapTest extends AbstractPrimitiveTest {
private final String one = "hello";
private final String two = "goodbye";
private final String three = "foo";
private final String four = "bar";
private final List<String> all = Lists.newArrayList(one, two, three, four);
/**
* Test that size behaves correctly (This includes testing of the empty check).
*/
@Test
public void testSize() throws Throwable {
DistributedMultimap<String, String> multimap = atomix().<String, String>multimapBuilder("testOneMap")
.withProtocol(protocol())
.build();
assertTrue(multimap.isEmpty());
assertEquals(0, multimap.size());
assertTrue(multimap.put(one, one));
assertFalse(multimap.isEmpty());
assertEquals(1, multimap.size());
assertTrue(multimap.put(one, two));
assertEquals(2, multimap.size());
assertFalse(multimap.put(one, one));
assertEquals(2, multimap.size());
assertTrue(multimap.put(two, one));
assertTrue(multimap.put(two, two));
assertEquals(4, multimap.size());
assertTrue(multimap.remove(one, one));
assertEquals(3, multimap.size());
assertFalse(multimap.remove(one, one));
assertEquals(3, multimap.size());
multimap.clear();
assertEquals(0, multimap.size());
assertTrue(multimap.isEmpty());
}
/**
* Contains tests for value, key and entry.
*/
@Test
public void containsTest() throws Throwable {
DistributedMultimap<String, String> multimap = atomix().<String, String>multimapBuilder("testTwoMap")
.withProtocol(protocol())
.build();
all.forEach(key -> assertTrue(multimap.putAll(key, all)));
assertEquals(16, multimap.size());
all.forEach(value -> assertTrue(multimap.containsValue(value)));
all.forEach(key -> all.forEach(value -> assertTrue(multimap.containsEntry(key, value))));
final String[] removedKey = new String[1];
all.forEach(value -> {
all.forEach(key -> {
assertTrue(multimap.remove(key, value));
assertFalse(multimap.containsEntry(key, value));
removedKey[0] = key;
});
});
assertFalse(multimap.containsKey(removedKey[0]));
all.forEach(value -> assertFalse(multimap.containsValue(value)));
}
/**
* Contains tests for put, putAll, remove, removeAll and replace.
*
* @throws Exception
*/
@Test
public void addAndRemoveTest() throws Exception {
DistributedMultimap<String, String> multimap = atomix().<String, String>multimapBuilder("testThreeMap")
.withProtocol(protocol())
.build();
all.forEach(key -> all.forEach(value -> {
assertTrue(multimap.put(key, value));
assertFalse(multimap.put(key, value));
}));
all.forEach(key -> all.forEach(value -> {
assertTrue(multimap.remove(key, value));
assertFalse(multimap.remove(key, value));
}));
assertTrue(multimap.isEmpty());
all.forEach(key -> {
assertTrue(multimap.putAll(key, Lists.newArrayList(all.subList(0, 2))));
assertFalse(multimap.putAll(key, Lists.newArrayList(all.subList(0, 2))));
assertTrue(multimap.putAll(key, Lists.newArrayList(all.subList(2, 4))));
assertFalse(multimap.putAll(key, Lists.newArrayList(all.subList(2, 4))));
});
multimap.clear();
all.forEach(key -> assertTrue(multimap.putAll(key, all)));
assertEquals(16, multimap.size());
all.forEach(key -> {
assertTrue(stringArrayCollectionIsEqual(all, multimap.removeAll(key)));
assertNotEquals(all, multimap.removeAll(key));
});
assertTrue(multimap.isEmpty());
all.forEach(key -> assertTrue(multimap.putAll(key, all)));
assertEquals(16, multimap.size());
all.forEach(key -> {
assertTrue(stringArrayCollectionIsEqual(all, multimap.replaceValues(key, all)));
assertTrue(stringArrayCollectionIsEqual(all, multimap.replaceValues(key, Lists.newArrayList())));
assertTrue(multimap.replaceValues(key, all).isEmpty());
});
assertEquals(16, multimap.size());
all.forEach(key -> {
assertTrue(multimap.remove(key, one));
assertTrue(stringArrayCollectionIsEqual(Lists.newArrayList(two, three, four), multimap.replaceValues(key, Lists.newArrayList())));
assertTrue(multimap.replaceValues(key, all).isEmpty());
});
}
/**
* Tests the get, keySet, keys, values, and entries implementations as well as a trivial test of the asMap
* functionality (throws error).
*
* @throws Exception
*/
@Test
public void testAccessors() throws Exception {
DistributedMultimap<String, String> multimap = atomix().<String, String>multimapBuilder("testFourMap")
.withProtocol(protocol())
.build();
all.forEach(key -> assertTrue(multimap.putAll(key, all)));
assertEquals(16, multimap.size());
all.forEach(key -> assertTrue(stringArrayCollectionIsEqual(all, multimap.get(key))));
multimap.clear();
all.forEach(key -> assertTrue(multimap.get(key).isEmpty()));
}
@Test
public void testMultimapViews() throws Exception {
DistributedMultimap<String, String> map = atomix().<String, String>multimapBuilder("testMultimapViews")
.withProtocol(protocol())
.build();
assertTrue(map.isEmpty());
assertTrue(map.keySet().isEmpty());
assertTrue(map.keys().isEmpty());
assertTrue(map.entries().isEmpty());
assertTrue(map.values().isEmpty());
for (int i = 0; i < 100; i++) {
map.put(String.valueOf(i), String.valueOf(i));
}
assertFalse(map.isEmpty());
assertFalse(map.keySet().isEmpty());
assertFalse(map.keys().isEmpty());
assertFalse(map.entries().isEmpty());
assertFalse(map.values().isEmpty());
assertEquals(100, map.keySet().stream().count());
assertEquals(100, map.keys().stream().count());
assertEquals(100, map.entries().stream().count());
assertEquals(100, map.values().stream().count());
for (int i = 0; i < 100; i++) {
map.put(String.valueOf(i), String.valueOf(i + 1));
}
assertEquals(100, map.keySet().size());
assertEquals(200, map.keys().size());
assertEquals(200, map.entries().size());
assertEquals(200, map.values().size());
String one = String.valueOf(1);
String two = String.valueOf(2);
String three = String.valueOf(3);
String four = String.valueOf(4);
assertTrue(map.keySet().contains(one));
assertTrue(map.keys().contains(one));
assertTrue(map.values().contains(one));
assertTrue(map.entries().contains(Maps.immutableEntry(one, one)));
assertTrue(map.keySet().containsAll(Arrays.asList(one, two, three, four)));
assertTrue(map.keys().containsAll(Arrays.asList(one, two, three, four)));
assertTrue(map.values().containsAll(Arrays.asList(one, two, three, four)));
assertTrue(map.keySet().remove(one));
assertFalse(map.keySet().contains(one));
assertFalse(map.containsKey(one));
assertTrue(map.keys().remove(two));
assertFalse(map.keys().contains(two));
assertFalse(map.containsKey(two));
assertTrue(map.entries().remove(Maps.immutableEntry(three, three)));
assertTrue(map.keySet().contains(three));
assertTrue(map.containsKey(three));
assertTrue(map.entries().remove(Maps.immutableEntry(three, four)));
assertFalse(map.keySet().contains(three));
assertFalse(map.containsKey(three));
assertFalse(map.entries().remove(Maps.immutableEntry(four, three)));
assertTrue(map.keySet().contains(four));
assertTrue(map.containsKey(four));
assertEquals(194, map.size());
assertEquals(97, map.keySet().size());
assertEquals(194, map.keys().size());
assertEquals(194, map.entries().size());
assertEquals(194, map.values().size());
assertEquals(97, map.keySet().stream().count());
assertEquals(194, map.keys().stream().count());
assertEquals(194, map.entries().stream().count());
assertEquals(194, map.values().stream().count());
assertEquals(97, map.keySet().toArray().length);
assertEquals(194, map.keys().toArray().length);
assertEquals(194, map.entries().toArray().length);
assertEquals(194, map.values().toArray().length);
assertEquals(97, map.keySet().toArray(new String[97]).length);
assertEquals(194, map.keys().toArray(new String[194]).length);
assertEquals(194, map.entries().toArray(new Map.Entry[194]).length);
assertEquals(194, map.values().toArray(new String[194]).length);
Iterator<String> iterator = map.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
iterator.next();
i += 1;
map.put(String.valueOf(100 * i), String.valueOf(100 * i));
}
}
/**
* Compares two collections of strings returns true if they contain the same strings, false otherwise.
*
* @param s1 string collection one
* @param s2 string collection two
* @return true if the two sets contain the same strings
*/
private boolean stringArrayCollectionIsEqual(
Collection<? extends String> s1, Collection<? extends String> s2) {
if (s1 == null || s2 == null || s1.size() != s2.size()) {
return false;
}
for (String string1 : s1) {
boolean matched = false;
for (String string2 : s2) {
if (string1.equals(string2)) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
return true;
}
}
| 3,892 |
965 | <gh_stars>100-1000
afxMemDF = allocMemDF | checkAlwaysMemDF; | 23 |
466 | package com.gykj.zhumulangma.listen.adapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.gykj.zhumulangma.common.util.ZhumulangmaUtil;
import com.gykj.zhumulangma.listen.R;
import com.ximalaya.ting.android.opensdk.model.track.Track;
/**
* Author: Thomas.
* <br/>Date: 2019/10/10 14:51
* <br/>Email: <EMAIL>
* <br/>Description:
*/
public class DownloadDeleteAdapter extends BaseQuickAdapter<Track, BaseViewHolder> {
public DownloadDeleteAdapter(int layoutResId) {
super(layoutResId);
}
@Override
protected void convert(BaseViewHolder helper, Track item) {
Glide.with(mContext).load(item.getCoverUrlMiddle()).into((ImageView) helper.getView(R.id.iv_cover));
helper.setText(R.id.tv_title,item.getTrackTitle());
helper.setText(R.id.tv_size, ZhumulangmaUtil.byte2FitMemorySize(item.getDownloadedSize()));
helper.setText(R.id.tv_duration, ZhumulangmaUtil.secondToTime(item.getDuration()));
CheckBox checkBox = helper.getView(R.id.cb);
checkBox.setChecked(item.isPaid());
}
}
| 480 |
1,085 | <gh_stars>1000+
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import javax.inject.Provider;
import org.junit.Test;
import com.dremio.service.Service;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
/**
* GuiceServiceModule tests
*/
public class TestGuiceServiceModule {
@Test
public void testSimpleChain() throws Exception {
final GuiceServiceModule guiceServiceHandler = new GuiceServiceModule();
final Injector injector = Guice.createInjector(guiceServiceHandler, new SimpleGraphModule());
// initially nothing should be created
assertEquals(0, guiceServiceHandler.getServiceList().size());
injector.getInstance(A.class);
assertEquals(0, guiceServiceHandler.getServiceList().size());
final BImpl bInstance = (BImpl) injector.getInstance(B.class);
assertEquals(2, guiceServiceHandler.getServiceList().size());
assertTrue(bInstance.isStarted());
assertFalse(bInstance.isClosed());
// singleton so size should not change
injector.getInstance(B.class);
assertEquals(2, guiceServiceHandler.getServiceList().size());
injector.getInstance(D.class);
assertEquals(3, guiceServiceHandler.getServiceList().size());
guiceServiceHandler.close(injector);
assertTrue(bInstance.isStarted());
assertTrue(bInstance.isClosed());
}
@Test
public void testMultiBind() throws Exception {
final GuiceServiceModule guiceServiceHandler = new GuiceServiceModule();
final Injector injector = Guice.createInjector(guiceServiceHandler, new MultiBindModule());
final MultiImpl bInstance = (MultiImpl) injector.getInstance(B.class);
final MultiImpl cInstance = (MultiImpl) injector.getInstance(C.class);
// B and C are bound to the same instance and Guice will only provision MultiImpl once, so it will
// only be started once.
assertEquals(bInstance, cInstance);
assertEquals(1, bInstance.getStarted());
guiceServiceHandler.close(injector);
assertEquals(1, bInstance.getClosed());
}
@Test(expected = ProvisionException.class)
public void testStartThrows() throws Exception {
final GuiceServiceModule guiceServiceHandler = new GuiceServiceModule();
final Injector injector = Guice.createInjector(guiceServiceHandler, new SimpleGraphModule());
// will throw a ProvisionException
injector.getInstance(ThrowsExceptionDuringStart.class);
}
private class SimpleGraphModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
A getA() {
return new A();
}
@Provides
@Singleton
B getB(Provider<A> aProvider, Provider<C> cProvider) {
aProvider.get();
cProvider.get();
return new BImpl();
}
@Provides
@Singleton
C getC(Provider<A> aProvider) {
aProvider.get();
return new CImpl();
}
@Provides
@Singleton
D getD(Provider<B> bProvider, Provider<C> cProvider, Provider<A> aProvider) {
bProvider.get();
aProvider.get();
cProvider.get();
return new D();
}
@Provides
@Singleton
ThrowsExceptionDuringStart getE(Provider<B> bProvider, Provider<C> cProvider, Provider<A> aProvider) {
return new ThrowsExceptionDuringStart();
}
}
private class MultiBindModule extends AbstractModule {
@Override
protected void configure() {
final MultiImpl multi = new MultiImpl();
bind(B.class).toInstance(multi);
bind(C.class).toInstance(multi);
}
}
private static class A {
}
private interface B {
}
private interface C extends B {
}
private static class Impl implements Service {
private boolean started = false;
private boolean closed = false;
@Override
public void start() throws Exception {
started = true;
}
@Override
public void close() throws Exception {
closed = true;
}
public boolean isStarted() {
return started;
}
public boolean isClosed() {
return closed;
}
}
private static class BImpl extends Impl implements B {
}
private static class CImpl extends Impl implements C {
}
private static class D extends Impl {
}
private static class MultiImpl extends BImpl implements C {
private int started = 0;
private int closed = 0;
@Override
public void start() throws Exception {
super.start();
started++;
}
@Override
public void close() throws Exception {
super.close();
closed++;
}
public int getStarted() {
return started;
}
public int getClosed() {
return closed;
}
}
private static class ThrowsExceptionDuringStart extends Impl {
@Override
public void start() throws Exception {
throw new IllegalArgumentException("evil");
}
}
}
| 1,880 |
1,346 | <reponame>duruyi/dal<filename>dal-client/src/main/java/com/ctrip/platform/dal/dao/task/DalSqlTaskRequest.java
package com.ctrip.platform.dal.dao.task;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import com.ctrip.platform.dal.common.enums.ImplicitAllShardsSwitch;
import com.ctrip.platform.dal.common.enums.ParameterDirection;
import com.ctrip.platform.dal.dao.*;
import com.ctrip.platform.dal.dao.client.DalLogger;
import com.ctrip.platform.dal.dao.client.LogContext;
import com.ctrip.platform.dal.dao.configure.dalproperties.DalPropertiesLocator;
import com.ctrip.platform.dal.dao.configure.dalproperties.DalPropertiesManager;
import com.ctrip.platform.dal.dao.helper.DalElementFactory;
import com.ctrip.platform.dal.dao.helper.DalRequestContext;
import com.ctrip.platform.dal.dao.helper.DalShardingHelper;
import com.ctrip.platform.dal.dao.helper.RequestContext;
import com.ctrip.platform.dal.dao.log.ILogger;
import com.ctrip.platform.dal.dao.sqlbuilder.AbstractFreeSqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.FreeSelectSqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.SelectSqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.SqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.TableSqlBuilder;
import com.ctrip.platform.dal.exceptions.DalException;
import org.apache.commons.lang.StringUtils;
public class DalSqlTaskRequest<T> implements DalRequest<T> {
private String caller;
private DalLogger logger;
private String logicDbName;
private SqlBuilder builder;
private StatementParameters parameters;
private DalHints hints;
private SqlTask<T> task;
private ResultMerger<T> merger;
private Set<String> shards;
private Map<String, List<?>> parametersByShard;
private DalTaskContext taskContext;
private ShardExecutionCallback<T> callback;
private static DalPropertiesLocator dalPropertiesLocator = DalPropertiesManager.getInstance().getDalPropertiesLocator();
public DalSqlTaskRequest(String logicDbName, SqlBuilder builder, DalHints hints, SqlTask<T> task,
ResultMerger<T> merger) throws SQLException {
this(logicDbName, builder, hints, task, merger, null);
}
public DalSqlTaskRequest(String logicDbName, SqlBuilder builder, DalHints hints, SqlTask<T> task,
ResultMerger<T> merger, ShardExecutionCallback<T> callback) throws SQLException {
this.logger = DalClientFactory.getDalLogger();
this.logicDbName = logicDbName;
this.builder = builder;
this.parameters = builder.buildParameters();
this.hints = hints != null ? hints.clone() : new DalHints();
this.task = task;
this.merger = merger;
this.caller = LogContext.getRequestCaller();
prepareRequestContext();
this.shards = getShards();
this.callback = callback;
}
@Override
public String getCaller() {
return caller;
}
@Override
public boolean isAsynExecution() {
return hints.isAsyncExecution();
}
@Override
public void validateAndPrepare() throws SQLException {
DalShardingHelper.detectDistributedTransaction(shards);
taskContext = task.createTaskContext();
}
private void prepareRequestContext() {
hints.setRequestContext(null);
if (task instanceof TaskAdapter) {
RequestContext ctx = new DalRequestContext().setLogicTableName(((TaskAdapter) task).rawTableName);
hints.setRequestContext(ctx);
} else if (builder instanceof AbstractFreeSqlBuilder) {
List<AbstractFreeSqlBuilder.Table> tables = ((AbstractFreeSqlBuilder) builder).getTables();
if (tables != null && tables.size() == 1) {
RequestContext ctx = new DalRequestContext().setLogicTableName(tables.get(0).getTableName());
hints.setRequestContext(ctx);
} else if (hints.getSpecifiedTableName() != null) {
RequestContext ctx = new DalRequestContext().setLogicTableName(hints.getSpecifiedTableName());
hints.setRequestContext(ctx);
}
} else if (hints.getSpecifiedTableName() != null) {
RequestContext ctx = new DalRequestContext().setLogicTableName(hints.getSpecifiedTableName());
hints.setRequestContext(ctx);
}
}
@Override
public String getLogicDbName() {
return logicDbName;
}
@Override
public boolean isCrossShard() {
return (shards != null && shards.size() > 1);
}
@Override
public TaskCallable<T> createTask() throws SQLException {
DalHints tmpHints = hints.clone();
if (shards != null && shards.size() == 1) {
tmpHints.inShard(shards.iterator().next());
}
return create(parameters, tmpHints, taskContext.fork(), tmpHints.getShardId());
}
@Override
public Map<String, TaskCallable<T>> createTasks() throws SQLException {
Map<String, TaskCallable<T>> tasks = new HashMap<>();
if (parametersByShard == null) {
// Create by given shards
for (String shard : shards) {
tasks.put(shard, create(parameters.duplicate(), hints.clone().inShard(shard), taskContext.fork(), shard));
}
} else {
// Create by sharded values
for (Map.Entry<String, ?> shard : parametersByShard.entrySet()) {
StatementParameters tempParameters =
parameters.duplicateWith(hints.getShardBy(), (List) shard.getValue());
tasks.put(shard.getKey(),
create(tempParameters, hints.clone().inShard(shard.getKey()), taskContext.fork(), shard.getKey()));
}
}
return tasks;
}
private TaskCallable<T> create(StatementParameters parameters, DalHints hints,
DalTaskContext taskContext, String dbShard) throws SQLException {
return new SqlTaskCallable<>(logicDbName, parameters, hints, task, taskContext, builder, merger,
logger, dbShard, callback);
}
@Override
public ResultMerger<T> getMerger() {
return merger;
}
@Override
public void endExecution() {
}
private Set<String> getShards() throws SQLException {
Set<String> shards = null;
if (!DalShardingHelper.isShardingEnabled(logicDbName))
return null;
if (hints.isAllShards()) {
shards = DalShardingHelper.getAllShards(logicDbName);
} else if (hints.isInShards()) {
shards = hints.getShards();
} else if (hints.isShardBy()) {
// The new code gen will set hints shardBy to indicate this is a potential cross shard operation
// Check parameters. It can only surpport DB shard at this level
StatementParameter parameter = parameters.get(hints.getShardBy(), ParameterDirection.Input);
parametersByShard = DalShardingHelper.shuffle(logicDbName, (List) parameter.getValue(), hints);
shards = parametersByShard.keySet();
} else if (dalPropertiesLocator.getImplicitAllShardsSwitch() == ImplicitAllShardsSwitch.ON) {
// implicit all shards if no shard can be located
if (!DalShardingHelper.locateShardId(logicDbName, hints.setParameters(parameters.duplicate()))) {
hints.inAllShards();
shards = DalShardingHelper.getAllShards(logicDbName);
}
}
if (shards != null && shards.size() > 1) {
logOnMultipleShards(shards, builder);
}
return shards;
}
private void logOnMultipleShards(Set<String> shards, SqlBuilder builder) {
String dbShards = StringUtils.join(shards, ",");
if (builder instanceof AbstractFreeSqlBuilder) {
AbstractFreeSqlBuilder freeSqlBuilder = (AbstractFreeSqlBuilder) builder;
logger.warn(
String.format("Execute on multiple shards %s detected: %s", dbShards, freeSqlBuilder.build(" "))); // space
// used
// for
// placeholder
} else {
logger.warn(String.format("Execute on multiple shards %s detected: %s", dbShards, builder.build()));
}
}
protected static class SqlTaskCallable<T> implements TaskCallable<T> {
private ILogger iLogger = DalElementFactory.DEFAULT.getILogger();
private static final String SQL_CROSSSHARD = "SQL.crossShard";
private static final String IMPLICIT_IN_ALL_TABLE_SHARDS = "implicitInAllTableShards";
private DalClient client;
private StatementParameters parameters;
private DalHints hints;
private SqlTask<T> task;
private DalTaskContext dalTaskContext;
private String dbShard;
private ShardExecutionCallback<T> callback;
private boolean isTableShardingEnabled;
private String logicDbName;
private String rawTableName;
private SqlBuilder builder;
private Set<String> tableShards;
private Map<String, List<?>> parametersByTableShard;
private ResultMerger<T> merger;
private DalLogger logger;
public SqlTaskCallable(String logicDbName, StatementParameters parameters, DalHints hints, SqlTask<T> task,
DalTaskContext dalTaskContext, SqlBuilder builder, ResultMerger<T> merger,
DalLogger logger, String dbShard, ShardExecutionCallback<T> callback)
throws SQLException {
this.logicDbName = logicDbName;
this.client = DalClientFactory.getClient(logicDbName);
this.hints = hints;
this.task = task;
this.parameters = parameters;
this.dalTaskContext = dalTaskContext;
this.dbShard = dbShard;
this.callback = callback;
// for table sharding
this.builder = builder;
this.logger = logger;
String tableName = getTableName();
this.rawTableName = tableName;
this.isTableShardingEnabled = DalShardingHelper.isTableShardingEnabled(logicDbName, tableName);
this.tableShards = getTableShards();
// we should create new ResultMerger here if table sharding is enabled
this.merger = createResultMerger(isTableShardingEnabled, merger, builder, hints);
}
public StatementParameters getParameters() {
return parameters;
}
private String getTableName() {
String tableName = "";
if (builder == null)
return tableName;
if (builder instanceof TableSqlBuilder) {
TableSqlBuilder tableSqlBuilder = (TableSqlBuilder) builder;
tableName = tableSqlBuilder.getTableName();
} else if (builder instanceof AbstractFreeSqlBuilder) {
AbstractFreeSqlBuilder freeSqlBuilder = (AbstractFreeSqlBuilder) builder;
tableName = getTableNameFromAbstractFreeSqlBuilder(freeSqlBuilder);
}
return tableName;
}
private String getTableNameFromAbstractFreeSqlBuilder(AbstractFreeSqlBuilder freeSqlBuilder) {
List<AbstractFreeSqlBuilder.Table> tables = freeSqlBuilder.getTables();
if (tables == null || tables.isEmpty())
return "";
if (tables.size() == 1)
return tables.get(0).getTableName();
return "";
}
private Set<String> getTableShards() throws SQLException {
Set<String> tableShards = null;
if (!isTableShardingEnabled)
return null;
if (hints.isAllTableShards()) {
tableShards = DalShardingHelper.getAllTableShards(logicDbName, rawTableName);
} else if (hints.isInTableShards()) {
tableShards = hints.getTableShards();
} else if (hints.isTableShardBy()) {
StatementParameter parameter = parameters.get(hints.getTableShardBy(), ParameterDirection.Input);
parametersByTableShard =
DalShardingHelper.shuffleByTable(logicDbName, rawTableName, null, (List) parameter.getValue());
tableShards = parametersByTableShard.keySet();
} else if (dalPropertiesLocator.getImplicitAllShardsSwitch() == ImplicitAllShardsSwitch.ON) {
// implicit all table shards if no table shard can be located
try {
DalShardingHelper.locateTableShardId(logicDbName, rawTableName, hints, compileParameters(parameters.duplicate()), null);
} catch (SQLException e) {
hints.inAllTableShards();
tableShards = DalShardingHelper.getAllTableShards(logicDbName, rawTableName);
}
}
if (tableShards != null && tableShards.size() > 1) {
logOnMultipleTableShards(tableShards, builder);
}
return tableShards;
}
private void logOnMultipleTableShards(Set<String> tableShards, SqlBuilder builder) throws SQLException {
if (builder instanceof AbstractFreeSqlBuilder) {
if (rawTableName == null || rawTableName.isEmpty()) {
throw new DalException(
"Cannot execute on muliple table shards by AbstractFreeSqlBuilder without a table name.");
}
AbstractFreeSqlBuilder freeSqlBuilder = (AbstractFreeSqlBuilder) builder;
for (String tableShard : tableShards) {
String tableShardStr = getTableShardString(tableShard, rawTableName, null, null);
logger.warn("Execute on multiple table shards detected: " + freeSqlBuilder.build(tableShardStr));
}
} else {
logger.warn("Execute on multiple table shards detected: " + builder.build());
}
}
@Override
public T call() throws Exception {
if (isTableShardingEnabled) {
return executeByTableSharding(tableShards, client, parameters, hints, dalTaskContext, builder, merger);
}
return execute(null, client, parameters, hints, dalTaskContext, builder, merger, tableShards);
}
private T executeByTableSharding(Set<String> tableShards, DalClient client, StatementParameters parameters,
DalHints hints, DalTaskContext taskContext, SqlBuilder builder, ResultMerger<T> merger)
throws SQLException {
T result = null;
if (parametersByTableShard == null) {
// Not cross table shards, table id can be inferred.
if (tableShards == null || tableShards.size() == 0) {
return execute(null, client, parameters, hints, taskContext, builder, merger, tableShards);
}
// By given table shards
result = executeByGivenTableShards(tableShards, client, parameters, hints, taskContext, builder,
merger);
} else {
// By table sharded values
result = executeByShardedParameterValues(parametersByTableShard, client, parameters, hints, taskContext,
builder, merger, tableShards);
}
return result;
}
private T executeByGivenTableShards(Set<String> tableShards, DalClient client, StatementParameters parameters,
DalHints hints, DalTaskContext taskContext, SqlBuilder builder, ResultMerger<T> merger)
throws SQLException {
for (String tableShard : tableShards) {
Throwable error = null;
ShardExecutionResult<T> executionResult;
try {
T partial = execute(tableShard, client, parameters, hints, taskContext, builder, merger, tableShards);
merger.addPartial(tableShard, partial);
// TODO: dbShard may be inaccurate
executionResult = new ShardExecutionResultImpl<>(dbShard, tableShard, partial);
} catch (Throwable e) {
error = e;
executionResult = new ShardExecutionResultImpl<>(dbShard, tableShard, e);
}
hints.handleError("Error when execute table shard operation", error, callback, executionResult);
}
return merger.merge();
}
private T executeByShardedParameterValues(Map<String, List<?>> parametersByTableShard, DalClient client,
StatementParameters parameters, DalHints hints, DalTaskContext taskContext, SqlBuilder builder,
ResultMerger<T> merger, Set<String> tableShards) throws SQLException {
for (Map.Entry<String, ?> tableShard : parametersByTableShard.entrySet()) {
Throwable error = null;
ShardExecutionResult<T> executionResult;
try {
T partial = execute(tableShard.getKey(), client,
parameters.duplicateWith(hints.getTableShardBy(), (List) tableShard.getValue()), hints,
taskContext, builder, merger, tableShards);
merger.addPartial(tableShard.getKey(), partial);
// TODO: dbShard may be inaccurate
executionResult = new ShardExecutionResultImpl<>(dbShard, tableShard.getKey(), partial);
} catch (Throwable e) {
error = e;
executionResult = new ShardExecutionResultImpl<>(dbShard, tableShard.getKey(), e);
}
hints.handleError("Error when execute table shard operation", error, callback, executionResult);
}
return merger.merge();
}
private T execute(String tableShardId, DalClient client, StatementParameters parameters, DalHints hints,
DalTaskContext taskContext, SqlBuilder builder, ResultMerger<T> merger, Set<String> tableShards)
throws SQLException {
String tableName = "";
StatementParameters originalParameters = parameters.duplicate();
StatementParameters compiledParameters = compileParameters(parameters.duplicate());
if (builder instanceof TableSqlBuilder || builder instanceof AbstractFreeSqlBuilder) {
tableName = rawTableName;
if (isTableShardingEnabled) {
return executeWithSqlBuilder(tableShardId, tableName, client, originalParameters,
compiledParameters, hints, taskContext, builder, merger, tableShards);
}
}
if (!tableName.isEmpty())
if (taskContext instanceof DalContextConfigure)
((DalContextConfigure) taskContext).addTables(tableName);
String compiledSql = compileSql(builder.build(), originalParameters);
return task.execute(client, compiledSql, compiledParameters, hints.clone(), taskContext);
}
private T executeWithSqlBuilder(String tableShardId, String tableName, DalClient client,
StatementParameters originalParameters, StatementParameters compiledParameters, DalHints hints,
DalTaskContext taskContext, SqlBuilder builder, ResultMerger<T> merger, Set<String> tableShards)
throws SQLException {
String tempTableName = tableName;
String tableShardStr = null;
try {
tableShardStr = getTableShardStr(tableShardId, tempTableName, hints, originalParameters); // compiledParameters
} catch (Exception e) {
if (tableShardStr == null || tableShardStr.isEmpty()) {
if (hints.isImplicitInAllTableShards()) {
return executeOnImplicitInAllTableShards(tempTableName, client, originalParameters, hints,
taskContext, builder, merger);
} else {
if (builder instanceof TableSqlBuilder) {
throw new DalException("Can not locate table shard for " + logicDbName, e);
} else if (builder instanceof AbstractFreeSqlBuilder) {
AbstractFreeSqlBuilder freeSqlBuilder = (AbstractFreeSqlBuilder) builder;
String compiledSql = compileSql(freeSqlBuilder.build(), originalParameters);
return task.execute(client, compiledSql, compiledParameters, hints.clone(),
taskContext);
}
}
}
}
tempTableName = tempTableName + tableShardStr;
String sql = null;
if (builder instanceof TableSqlBuilder) {
TableSqlBuilder tableBuilder = (TableSqlBuilder) builder;
sql = tableBuilder.build(tableShardStr);
} else if (builder instanceof AbstractFreeSqlBuilder) {
AbstractFreeSqlBuilder freeSqlBuilder = (AbstractFreeSqlBuilder) builder;
if (tableShards == null || tableShards.isEmpty()) { // non-cross table sharding
sql = freeSqlBuilder.build();
} else {
sql = freeSqlBuilder.build(tableShardStr);
}
}
return executeTask(taskContext, tempTableName, client, sql, originalParameters, compiledParameters, hints);
}
private T executeOnImplicitInAllTableShards(String tempTableName, DalClient client,
StatementParameters originalParameters, DalHints hints, DalTaskContext taskContext, SqlBuilder builder,
ResultMerger<T> merger) throws SQLException {
logger.warn("Try to execute on all table shards due to implicit inAllTableShards hints.");
iLogger.logEvent(SQL_CROSSSHARD, IMPLICIT_IN_ALL_TABLE_SHARDS,
String.format("LogicDbName:%s, TableName:%s", logicDbName, tempTableName));
// implicit execute in all table shards
Set<String> allTableShards = DalShardingHelper.getAllTableShards(logicDbName, rawTableName);
return executeByGivenTableShards(allTableShards, client, originalParameters, hints, taskContext, builder,
merger);
}
private String getTableShardStr(String tableShardId, String tableName, DalHints hints,
StatementParameters compiledParameters) throws SQLException {
String tempTableName = tableName;
String tableShardStr = getTableShardString(tableShardId, tempTableName, hints, compiledParameters);
return tableShardStr;
}
private T executeTask(DalTaskContext taskContext, String tempTableName, DalClient client, String sql,
StatementParameters originalParameters, StatementParameters compiledParameters, DalHints hints)
throws SQLException {
if (taskContext instanceof DalContextConfigure)
((DalContextConfigure) taskContext).addTables(tempTableName);
String compiledSql = compileSql(sql, originalParameters);
return task.execute(client, compiledSql, compiledParameters, hints.clone(), taskContext);
}
private String compileSql(String sql, StatementParameters parameters) throws SQLException {
if (!parameters.containsInParameter())
return sql;
return SQLCompiler.compile(sql, parameters.getAllInParameters());
}
private StatementParameters compileParameters(StatementParameters parameters) {
if (!parameters.containsInParameter())
return parameters;
parameters.compile();
return parameters;
}
private String getTableShardString(String tableShardId, String tableName, DalHints hints,
StatementParameters parameters) throws SQLException {
String tempTableShardId = null;
if (tableShardId != null) {
tempTableShardId = tableShardId;
} else {
tempTableShardId =
DalShardingHelper.locateTableShardId(logicDbName, tableName, hints, parameters, null);
}
return DalShardingHelper.buildShardStr(logicDbName, tableName, tempTableShardId);
}
private ResultMerger createResultMerger(boolean isTableShardingEnabled, ResultMerger<T> merger,
SqlBuilder builder, DalHints hints) {
if (merger == null)
return null;
if (!isTableShardingEnabled)
return merger;
ResultMerger rm = createResultMergerByMergerType(merger);
if (rm == null) {
rm = createResultMergerByBuilderType(builder, hints);
}
return rm;
}
private ResultMerger createResultMergerByMergerType(ResultMerger<T> merger) {
return ResultMergerHelper.createResultMerger(merger);
}
private ResultMerger createResultMergerByBuilderType(SqlBuilder builder, DalHints hints) {
if (builder instanceof SelectSqlBuilder) {
SelectSqlBuilder selectSqlBuilder = (SelectSqlBuilder) builder;
return selectSqlBuilder.createNewResultMerger(hints);
}
if (builder instanceof FreeSelectSqlBuilder) {
FreeSelectSqlBuilder freeSelectSqlBuilder = (FreeSelectSqlBuilder) builder;
return freeSelectSqlBuilder.createNewResultMerger(hints);
}
return null;
}
protected Set<String> tableShards(){
return this.tableShards;
}
@Override
public DalTaskContext getDalTaskContext() {
return this.dalTaskContext;
}
@Override
public String getPreparedDbShard() {
return dbShard != null ? dbShard : hints.getShardId();
}
}
}
| 11,733 |
1,350 | <reponame>ppartarr/azure-sdk-for-java
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.batch.protocol.models;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The set of changes to be made to a Pool.
*/
public class PoolPatchParameter {
/**
* A Task to run on each Compute Node as it joins the Pool. The Task runs
* when the Compute Node is added to the Pool or when the Compute Node is
* restarted.
* If this element is present, it overwrites any existing StartTask. If
* omitted, any existing StartTask is left unchanged.
*/
@JsonProperty(value = "startTask")
private StartTask startTask;
/**
* A list of Certificates to be installed on each Compute Node in the Pool.
* If this element is present, it replaces any existing Certificate
* references configured on the Pool. If omitted, any existing Certificate
* references are left unchanged. For Windows Nodes, the Batch service
* installs the Certificates to the specified Certificate store and
* location. For Linux Compute Nodes, the Certificates are stored in a
* directory inside the Task working directory and an environment variable
* AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this
* location. For Certificates with visibility of 'remoteUser', a 'certs'
* directory is created in the user's home directory (e.g.,
* /home/{user-name}/certs) and Certificates are placed in that directory.
*/
@JsonProperty(value = "certificateReferences")
private List<CertificateReference> certificateReferences;
/**
* A list of Packages to be installed on each Compute Node in the Pool.
* Changes to Package references affect all new Nodes joining the Pool, but
* do not affect Compute Nodes that are already in the Pool until they are
* rebooted or reimaged. If this element is present, it replaces any
* existing Package references. If you specify an empty collection, then
* all Package references are removed from the Pool. If omitted, any
* existing Package references are left unchanged.
*/
@JsonProperty(value = "applicationPackageReferences")
private List<ApplicationPackageReference> applicationPackageReferences;
/**
* A list of name-value pairs associated with the Pool as metadata.
* If this element is present, it replaces any existing metadata configured
* on the Pool. If you specify an empty collection, any metadata is removed
* from the Pool. If omitted, any existing metadata is left unchanged.
*/
@JsonProperty(value = "metadata")
private List<MetadataItem> metadata;
/**
* Get if this element is present, it overwrites any existing StartTask. If omitted, any existing StartTask is left unchanged.
*
* @return the startTask value
*/
public StartTask startTask() {
return this.startTask;
}
/**
* Set if this element is present, it overwrites any existing StartTask. If omitted, any existing StartTask is left unchanged.
*
* @param startTask the startTask value to set
* @return the PoolPatchParameter object itself.
*/
public PoolPatchParameter withStartTask(StartTask startTask) {
this.startTask = startTask;
return this;
}
/**
* Get if this element is present, it replaces any existing Certificate references configured on the Pool. If omitted, any existing Certificate references are left unchanged. For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and Certificates are placed in that directory.
*
* @return the certificateReferences value
*/
public List<CertificateReference> certificateReferences() {
return this.certificateReferences;
}
/**
* Set if this element is present, it replaces any existing Certificate references configured on the Pool. If omitted, any existing Certificate references are left unchanged. For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and Certificates are placed in that directory.
*
* @param certificateReferences the certificateReferences value to set
* @return the PoolPatchParameter object itself.
*/
public PoolPatchParameter withCertificateReferences(List<CertificateReference> certificateReferences) {
this.certificateReferences = certificateReferences;
return this;
}
/**
* Get changes to Package references affect all new Nodes joining the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or reimaged. If this element is present, it replaces any existing Package references. If you specify an empty collection, then all Package references are removed from the Pool. If omitted, any existing Package references are left unchanged.
*
* @return the applicationPackageReferences value
*/
public List<ApplicationPackageReference> applicationPackageReferences() {
return this.applicationPackageReferences;
}
/**
* Set changes to Package references affect all new Nodes joining the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or reimaged. If this element is present, it replaces any existing Package references. If you specify an empty collection, then all Package references are removed from the Pool. If omitted, any existing Package references are left unchanged.
*
* @param applicationPackageReferences the applicationPackageReferences value to set
* @return the PoolPatchParameter object itself.
*/
public PoolPatchParameter withApplicationPackageReferences(List<ApplicationPackageReference> applicationPackageReferences) {
this.applicationPackageReferences = applicationPackageReferences;
return this;
}
/**
* Get if this element is present, it replaces any existing metadata configured on the Pool. If you specify an empty collection, any metadata is removed from the Pool. If omitted, any existing metadata is left unchanged.
*
* @return the metadata value
*/
public List<MetadataItem> metadata() {
return this.metadata;
}
/**
* Set if this element is present, it replaces any existing metadata configured on the Pool. If you specify an empty collection, any metadata is removed from the Pool. If omitted, any existing metadata is left unchanged.
*
* @param metadata the metadata value to set
* @return the PoolPatchParameter object itself.
*/
public PoolPatchParameter withMetadata(List<MetadataItem> metadata) {
this.metadata = metadata;
return this;
}
}
| 2,140 |
3,200 | <reponame>PowerOlive/mindspore
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License == 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.
matmul
"""
from __future__ import absolute_import
from impl.matmul_vector import matmul_vector_cce
from mindspore.ops.op_info_register import op_info_register, TBERegOp, DataType
from mindspore.ops._op_impl._custom_op._basic import _shape_check, _get_bias, _get_input_shape
import te.lang.cce
import te.platform.cce_params as cce
from te import tvm
from topi import generic
from topi.cce import util
# General limitation of the size for input shape: 2**31
SHAPE_SIZE_LIMIT = 2147483648
NoneType = type(None)
matmul_cube_op_info = TBERegOp("CusMatMulCube") \
.fusion_type("OPAQUE") \
.async_flag(False) \
.binfile_name("matmulcube.so") \
.compute_cost(10) \
.kernel_name("cus_matmul_cube") \
.partial_flag(True) \
.attr("transpose_a", "required", "bool", "all") \
.attr("transpose_b", "required", "bool", "all") \
.input(0, "x1", False, "required", "all") \
.input(1, "x2", False, "required", "all") \
.input(2, "x3", False, "optional", "all") \
.output(0, "y", False, "required", "all") \
.dtype_format(DataType.F16_FracNZ, DataType.F16_FracNZ, DataType.F16_Default, DataType.F32_FracNZ) \
.get_op_info()
@op_info_register(matmul_cube_op_info)
def cus_matmul_cube(input_x1, input_x2, bias=None, output_y=None, trans_a=False, trans_b=False,
kernel_name="cus_matmul_cube"):
"""
calculating matrix multiplication with bias, C = A*B + bias, support input
data with fractal format.
Parameters:
shape_a: list or tuple
Shape of the first tensor a with rank > 1
shape_b: list or tuple
Shape of the second tensor b with the same type with a,
and shape_a, shape_b must be 2 dims
src_dtype: str
The data type of input, support "float32", "float16"
dst_dtype: str
The data type of output, support "float32", "float16"
trans_a: bool
If True, shape_a == transposed before multiplication
trans_b: bool
If True, shape_b == transposed before multiplication
is_fractal: bool
If True, the input data format of a and b must be fractal format
shape_bias: list or tuple
Shape of bias, only support the input data format with ND
Returns
-------
None
"""
util.check_kernel_name(kernel_name)
shape_a, shape_b, trans_a, trans_b = _get_shape_a_b(input_x1, input_x2, trans_a, trans_b)
shape_bias = ()
if bias is not None and bool(bias):
shape_bias = bias.get("shape")
shape_bias = list(shape_bias)
shape_bias = _get_bias(shape_bias)
src_dtype = input_x1.get("dtype").lower()
dst_dtype = output_y.get("dtype").lower()
if src_dtype in ("float32", "int32"):
matmul_vector_cce(shape_a, shape_b, src_dtype, trans_a, trans_b, shape_bias, kernel_name)
return
_shape_check(shape_a, shape_b, shape_bias, src_dtype, trans_a, trans_b)
block_in, block_out = _get_block(shape_a, shape_b, trans_a, trans_b)
shape_a_temp, shape_b_temp, format_a, format_b = _get_format(input_x1, input_x2, trans_a, trans_b,
block_in, block_out, shape_a, shape_b)
tensor_bias = None
tensor_a = tvm.placeholder(shape_a_temp, name='tensor_a',
dtype=src_dtype)
tensor_b = tvm.placeholder(shape_b_temp, name='tensor_b',
dtype=src_dtype)
if shape_bias:
tensor_bias = tvm.placeholder(shape_bias, name='tensor_bias',
dtype=dst_dtype)
result = te.lang.cce.matmul(tensor_a, tensor_b, trans_a, trans_b, format_a=format_a,
format_b=format_b, dst_dtype=dst_dtype, tensor_bias=tensor_bias)
tensor_list = [tensor_a, tensor_b, result]
if shape_bias:
tensor_list = [tensor_a, tensor_b, tensor_bias, result]
with tvm.target.cce():
schedule = generic.auto_schedule(result)
config = {"print_ir": False,
"name": kernel_name,
"tensor_list": tensor_list}
te.lang.cce.cce_build_code(schedule, config)
def _get_shape_a_b(input_x1, input_x2, trans_a, trans_b):
"""_get_shape_a_b"""
shape_a = input_x1.get("ori_shape")
shape_b = input_x2.get("ori_shape")
if shape_a and len(shape_a) < 2:
shape_a = input_x1.get("shape")
if shape_b and len(shape_b) < 2:
shape_b = input_x2.get("shape")
shape_a = list(shape_a)
shape_b = list(shape_b)
if input_x1.get("format") == "FRACTAL_NZ":
shape_a = _get_input_shape(shape_a)
shape_b = _get_input_shape(shape_b)
util.check_shape_rule(shape_a)
util.check_shape_rule(shape_b)
util.check_shape_size(shape_a, SHAPE_SIZE_LIMIT)
util.check_shape_size(shape_b, SHAPE_SIZE_LIMIT)
if input_x1.get("format") == "FRACTAL_NZ":
shape_a = [shape_a[1], shape_a[0]]
trans_a = bool(1 - trans_a)
if input_x2.get("format") == "FRACTAL_NZ":
shape_b = [shape_b[1], shape_b[0]]
trans_b = bool(1 - trans_b)
return shape_a, shape_b, trans_a, trans_b
def _get_block(shape_a, shape_b, trans_a, trans_b):
"""_get_block"""
m_shape = shape_a[len(shape_a) - 2]
km_shape = shape_a[len(shape_a) - 1]
kn_shape = shape_b[len(shape_a) - 2]
n_shape = shape_b[len(shape_a) - 1]
block_out = cce.BLOCK_OUT
block_in = cce.BLOCK_IN
if trans_b and kn_shape == 1:
block_out = cce.BLOCK_VECTOR
if not trans_b and n_shape == 1:
block_out = cce.BLOCK_VECTOR
if trans_a and km_shape == 1:
block_in = cce.BLOCK_VECTOR
if not trans_a and m_shape == 1:
block_in = cce.BLOCK_VECTOR
return block_in, block_out
def _get_format(input_x1, input_x2, trans_a, trans_b, block_in, block_out, shape_a, shape_b):
"""_get_block"""
m_shape = shape_a[len(shape_a) - 2]
km_shape = shape_a[len(shape_a) - 1]
kn_shape = shape_b[len(shape_a) - 2]
n_shape = shape_b[len(shape_a) - 1]
if input_x1.get("dtype").lower() == "float16":
block_reduce = cce.BLOCK_REDUCE
if trans_a:
shape_a_temp = (m_shape // block_reduce, km_shape // block_in, block_reduce, block_in)
else:
shape_a_temp = (m_shape // block_in, km_shape // block_reduce, block_in, block_reduce)
if trans_b:
shape_b_temp = (kn_shape // block_out, n_shape // block_reduce, block_reduce, block_out)
else:
shape_b_temp = (kn_shape // block_reduce, n_shape // block_out, block_out, block_reduce)
if input_x1.get("format") == "FORMAT_FRACTAL_Z":
shape_a_temp = (shape_a_temp[0], shape_a_temp[1], shape_a_temp[2], shape_a_temp[3])
format_a = "fractal"
elif input_x1.get("format") == "FRACTAL_NZ":
shape_a_temp = (shape_a_temp[0], shape_a_temp[1], shape_a_temp[2], shape_a_temp[3])
format_a = "FRACTAL_NZ"
else:
shape_a_temp = (shape_a[len(shape_a) - 2], shape_a[len(shape_a) - 1])
format_a = "ND"
if input_x2.get("format") == "FORMAT_FRACTAL_Z":
shape_b_temp = (shape_b_temp[0], shape_b_temp[1], shape_b_temp[2], shape_b_temp[3])
format_b = "fractal"
elif input_x2.get("format") == "FRACTAL_NZ":
shape_b_temp = (shape_b_temp[0], shape_b_temp[1], shape_b_temp[2], shape_b_temp[3])
format_b = "FRACTAL_NZ"
else:
shape_b_temp = (shape_b[len(shape_b) - 2], shape_b[len(shape_b) - 1])
format_b = "ND"
return shape_a_temp, shape_b_temp, format_a, format_b
| 3,783 |
743 | <filename>extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/JDBCAuthenticationProviderService.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.guacamole.auth.jdbc;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.auth.jdbc.security.PasswordPolicyService;
import org.apache.guacamole.auth.jdbc.sharing.user.SharedAuthenticatedUser;
import org.apache.guacamole.auth.jdbc.user.ModeledAuthenticatedUser;
import org.apache.guacamole.auth.jdbc.user.ModeledUser;
import org.apache.guacamole.auth.jdbc.user.ModeledUserContext;
import org.apache.guacamole.auth.jdbc.user.PrivilegedModeledAuthenticatedUser;
import org.apache.guacamole.auth.jdbc.user.UserService;
import org.apache.guacamole.language.TranslatableGuacamoleClientException;
import org.apache.guacamole.net.auth.AuthenticatedUser;
import org.apache.guacamole.net.auth.AuthenticationProvider;
import org.apache.guacamole.net.auth.Credentials;
import org.apache.guacamole.net.auth.UserContext;
import org.apache.guacamole.net.auth.credentials.CredentialsInfo;
import org.apache.guacamole.net.auth.credentials.GuacamoleInvalidCredentialsException;
/**
* AuthenticationProviderService implementation which authenticates users with
* a username/password pair, producing new UserContext objects which are backed
* by an underlying, arbitrary database.
*/
public class JDBCAuthenticationProviderService implements AuthenticationProviderService {
/**
* The environment of the Guacamole server.
*/
@Inject
private JDBCEnvironment environment;
/**
* Service for accessing users.
*/
@Inject
private UserService userService;
/**
* Service for enforcing password complexity policies.
*/
@Inject
private PasswordPolicyService passwordPolicyService;
/**
* Provider for retrieving UserContext instances.
*/
@Inject
private Provider<ModeledUserContext> userContextProvider;
@Override
public AuthenticatedUser authenticateUser(AuthenticationProvider authenticationProvider,
Credentials credentials) throws GuacamoleException {
// Authenticate user
AuthenticatedUser user = userService.retrieveAuthenticatedUser(authenticationProvider, credentials);
if (user != null)
return user;
// Otherwise, unauthorized
throw new GuacamoleInvalidCredentialsException("Invalid login", CredentialsInfo.USERNAME_PASSWORD);
}
@Override
public ModeledUserContext getUserContext(AuthenticationProvider authenticationProvider,
AuthenticatedUser authenticatedUser) throws GuacamoleException {
// Always allow but provide no data for users authenticated via our own
// connection sharing links
if (authenticatedUser instanceof SharedAuthenticatedUser)
return null;
// Set semantic flags based on context
boolean databaseCredentialsUsed = (authenticatedUser instanceof ModeledAuthenticatedUser);
boolean databaseRestrictionsApplicable = (databaseCredentialsUsed || environment.isUserRequired());
// Retrieve user account for already-authenticated user
ModeledUser user = userService.retrieveUser(authenticationProvider, authenticatedUser);
ModeledUserContext context = userContextProvider.get();
if (user != null && !user.isDisabled()) {
// Enforce applicable account restrictions
if (databaseRestrictionsApplicable) {
// Verify user account is still valid as of today
if (!user.isAccountValid())
throw new TranslatableGuacamoleClientException("User "
+ "account is no longer valid.",
"LOGIN.ERROR_NOT_VALID");
// Verify user account is allowed to be used at the current time
if (!user.isAccountAccessible())
throw new TranslatableGuacamoleClientException("User "
+ "account may not be used at this time.",
"LOGIN.ERROR_NOT_ACCESSIBLE");
}
// Update password if password is expired AND the password was
// actually involved in the authentication process
if (databaseCredentialsUsed) {
if (user.isExpired() || passwordPolicyService.isPasswordExpired(user))
userService.resetExpiredPassword(user, authenticatedUser.getCredentials());
}
}
// If no user account is found, and database-specific account
// restrictions do not apply, get a skeleton user.
else if (!databaseRestrictionsApplicable) {
user = userService.retrieveSkeletonUser(authenticationProvider, authenticatedUser);
// If auto account creation is enabled, add user to DB.
if (environment.autoCreateAbsentAccounts()) {
ModeledUser createdUser = userService.createObject(new PrivilegedModeledAuthenticatedUser(user.getCurrentUser()), user);
user.setModel(createdUser.getModel());
}
}
// Veto authentication result only if database-specific account
// restrictions apply in this situation
else
throw new GuacamoleInvalidCredentialsException("Invalid login",
CredentialsInfo.USERNAME_PASSWORD);
// Initialize the UserContext with the user account and return it.
context.init(user.getCurrentUser());
context.recordUserLogin();
return context;
}
@Override
public UserContext updateUserContext(AuthenticationProvider authenticationProvider,
UserContext context, AuthenticatedUser authenticatedUser,
Credentials credentials) throws GuacamoleException {
// No need to update the context
return context;
}
}
| 2,413 |
385 | import tensorflow as tf
import numpy as np
from utils import data_handler as dh
import src.OPTICS as OPTICS
import scipy.misc
import matplotlib.pyplot as plt
from sklearn.metrics import average_precision_score as aps
FLAGS = tf.app.flags.FLAGS
from time import time
import config
import os
import pickle
import csv
class Statistic():
def __init__(self, logits, total_loss, loss_list, input_ph, ground_truths_ph, multi_loss_class, processed_ground_truths):
self.labelsID_outpot = logits[0]
self.InstanceID_outpot = logits[1]
self.Disparity_outpot = logits[2]
self.total_loss = total_loss
self.loss_list = loss_list
self.input_ph = input_ph
self.ground_truths_ph = ground_truths_ph
self.multi_loss_class = multi_loss_class
self.processed_ground_truths = processed_ground_truths
self.epoch_num = 0
# lists for saving statistic over time
self.eval_keys = ['total_loss', 'labelsID_acc', 'InstanceID_per_pixel_rms', 'InstanceID_total_rms',
'Label_ap_acc', 'Disparity_per_pixel_rms', 'Disparity_total_rms']
self.statistics = dict((k, {'val': [], 'train': []}) for k in self.eval_keys)
self.statistics['loss_lists'] = {'val': [[] for i in range(len(loss_list))], 'train': [[] for i in range(len(loss_list))]}
self.statistics['sigmas_list'] = [[] for i in range(len(loss_list))]
self.statistics['weights_list'] = [[] for i in range(len(loss_list))]
self.statistics['label_scores'] = {}
self.statistics['label_scores']['acc'] = {'val': [], 'train': []}
self.statistics['label_scores']['cl_acc_mean'] = {'val': [], 'train': []}
self.statistics['label_scores']['iu_mean'] = {'val': [], 'train': []}
self.statistics['label_scores']['cl_acc'] = {'val': [], 'train': []}
self.statistics['label_scores']['iu'] = {'val': [], 'train': []}
self.statistics['label_scores']['iu_no_void_mean'] = {'val': [], 'train': []}
# self.label_scores['label_ap_score'] = {'val': [], 'train': []}
# self.label_scores['instance_ap_score'] = {'val': [], 'train': []}
# make plot dirs
self.make_dirs()
def make_dirs(self):
if not os.path.exists(FLAGS.stat_dump_path):
os.makedirs(FLAGS.stat_dump_path)
if not os.path.exists(FLAGS.stat_dump_path):
os.makedirs(FLAGS.stat_csv_path)
if not os.path.exists(FLAGS.plots_path):
os.makedirs(FLAGS.plots_path)
if not os.path.exists(FLAGS.example_preds):
os.makedirs(FLAGS.example_preds)
if not os.path.exists(os.path.join(FLAGS.example_preds, 'label')):
os.makedirs(os.path.join(FLAGS.example_preds, 'label'))
if not os.path.exists(os.path.join(FLAGS.example_preds, 'disp')):
os.makedirs(os.path.join(FLAGS.example_preds, 'disp'))
if not os.path.exists(os.path.join(FLAGS.example_preds, 'instance', "y_reg")):
os.makedirs(os.path.join(FLAGS.example_preds, 'instance', "y_reg"))
if not os.path.exists(os.path.join(FLAGS.example_preds, 'instance', "x_reg")):
os.makedirs(os.path.join(FLAGS.example_preds, 'instance', "x_reg"))
def arange_eval_lists(self, val_eval_dict, train_eval_dict):
[self.statistics[key]['val'].append(val_eval_dict[key]) for key in self.eval_keys if
key not in ['Label_ap_acc', 'loss_lists']] # Those are updated differently
[self.statistics[key]['train'].append(train_eval_dict[key]) for key in self.eval_keys if
key not in ['Label_ap_acc', 'loss_lists']]
if (self.epoch_num + 1) % FLAGS.calc_ap_epoch_num == 0:
self.statistics['Label_ap_acc']['val'].append(val_eval_dict['Label_ap'])
self.statistics['Label_ap_acc']['train'].append(train_eval_dict['Label_ap'])
for loss_num in range(len(val_eval_dict['loss_list'])):
self.statistics['loss_lists']['val'][loss_num].append(val_eval_dict['loss_list'][loss_num])
self.statistics['loss_lists']['train'][loss_num].append(train_eval_dict['loss_list'][loss_num])
def handle_statistic(self, epoch, logits, sess, train_input_imgs=None, train_gts=None,
val_input_imgs=None, val_gts=None, verbose=1):
self.epoch_num = epoch
if epoch % FLAGS.val_epoch == 0:
start = time()
val_eval_dict = self.run_evaluation('val', logits, sess, input_imgs=val_input_imgs, gts=val_gts)
middle = time()
print('time for val eval: %.2f' %(middle-start))
train_eval_dict = self.run_evaluation('train', logits, sess, input_imgs=train_input_imgs, gts=train_gts)
end = time()
print('time for train eval: %.2f' % (end - middle))
self.set_sigmas_and_wights()
self.arange_eval_lists(val_eval_dict, train_eval_dict)
self.save_plots()
# self.save_cvss()
if verbose:
self.print_end_epoch_stats(train_eval_dict, val_eval_dict)
if epoch % FLAGS.example_epoch == 0:
start = time()
self.calc_and_save_examples(logits, sess)
end = time()
print('calc example time: %.2f' % (end - start))
# def save_csv(self):
# with open(os.path.join(FLAGS.stat_csv_path, 'stat.csv'), 'wb') as myfile:
# wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
# wr.writerow(mylist)
#
def print_end_epoch_stats(self, train_eval_dict, val_eval_dict):
print('train - label accuracy: %.2f' % (train_eval_dict['labelsID_acc'])
+ ', label IoU: %.2f' % (self.statistics['label_scores']['iu_mean']['train'][-1])
+ ', best IoU: %.2f' % (np.max(self.statistics['label_scores']['iu_mean']['train'])))
print('val - label accuracy: %.2f' % (val_eval_dict['labelsID_acc'])
+ ', label IoU: %.2f' % (self.statistics['label_scores']['iu_mean']['val'][-1])
+ ', best IoU: %.2f' % (np.max(self.statistics['label_scores']['iu_mean']['val'])))
print('train - Instance RMS per pixel: %.4f' % (train_eval_dict['InstanceID_per_pixel_rms'])
+ ', Instance total RMS: %.4f' % (train_eval_dict['InstanceID_total_rms']))
print('val - Instance RMS per pixel: %.4f' % (val_eval_dict['InstanceID_per_pixel_rms'])
+ ', Instance total RMS: %.4f' % (val_eval_dict['InstanceID_total_rms']))
print('train - disp RMS per pixel: %.4f' % (train_eval_dict['Disparity_per_pixel_rms'])
+ ', disp total RMS: %.4f' % (train_eval_dict['Disparity_total_rms']))
print('val - disp RMS per pixel: %.4f' % (val_eval_dict['Disparity_per_pixel_rms'])
+ ', disp total RMS: %.4f' % (val_eval_dict['Disparity_total_rms']))
def run_evaluation(self, set_name, logits, sess, input_imgs=None, gts=None):
labelsID_acc_sum = 0
InstanceID_per_pixel_rms_sum = 0
InstanceID_total_rms_sum = 0
disp_per_pixel_rms_sum = 0
disp_total_rms_sum = 0
total_loss_sum = 0
Label_ap = 0 # average precision
loss_list_sum = [0]*len(self.loss_list)
n = len(config.colors[config.working_dataset])
label_id_hist = np.zeros((n, n)) # n = 34 (num of classes)
num_per_set = {'train': FLAGS.num_of_train_imgs,
'val': FLAGS.num_of_val_imgs}
set_images_number = num_per_set[set_name]
input_len = 0
for ind in range(set_images_number):
if input_imgs is not None:
image, gt = input_imgs[ind], gts[ind]
else:
image, gt = dh.get_data(ind, set_name)
processed_gts = [None] * 3
if FLAGS.need_resize:
processed_gts[0] = scipy.misc.imresize(gt[0].squeeze(), (FLAGS.output_height, FLAGS.output_width))
processed_gts[1] = scipy.misc.imresize(gt[1].squeeze(), (FLAGS.output_height, FLAGS.output_width))
processed_gts[2] = scipy.misc.imresize(gt[2].squeeze(), (FLAGS.output_height, FLAGS.output_width))
else:
processed_gts[0] = gt[0].squeeze()
processed_gts[1] = gt[1].squeeze()
processed_gts[2] = gt[2].squeeze()
full_feed_dict = self.get_feed_dict(image, gt)
run_list = self.get_run_list(logits)
pred_list = sess.run(run_list, feed_dict=full_feed_dict)
labelsID_acc_sum += self.calc_labelsID_acc(pred_list[0], pred_list[4])
label_id_hist += self.fast_hist(pred_list[0], pred_list[4], n)
per_pixel_rms, total_rms = self.calc_InstanceID_rms(pred_list[1], processed_gts[1])
InstanceID_per_pixel_rms_sum += per_pixel_rms
InstanceID_total_rms_sum += total_rms
per_pixel_rms_disp, total_rms_disp = self.calc_Disparity_rms(pred_list[2], processed_gts[2])
disp_per_pixel_rms_sum += per_pixel_rms_disp
disp_total_rms_sum += total_rms_disp
total_loss_sum += pred_list[3]
for loss_num in range(len(loss_list_sum)):
loss_list_sum[loss_num] += pred_list[5 + loss_num]
input_len = input_len + 1
#if self.epoch_num + 1 == FLAGS.num_of_epchs:
# self.Instance_img(set_name, ind, pred_list[1], processed_gts[1])
if (self.epoch_num+1) % FLAGS.calc_ap_epoch_num == 0:
Label_ap += self.calc_LabelId_ap(pred_list[0], pred_list[4])
self.calc_and_set_label_scores(label_id_hist, set_name)
for loss_num in range(len(loss_list_sum)):
loss_list_sum[loss_num] = loss_list_sum[loss_num] / input_len
return_dict = {'labelsID_acc': labelsID_acc_sum / input_len,
'InstanceID_per_pixel_rms': InstanceID_per_pixel_rms_sum / input_len,
'InstanceID_total_rms': InstanceID_total_rms_sum / input_len,
'Disparity_per_pixel_rms': disp_per_pixel_rms_sum / input_len,
'Disparity_total_rms': disp_total_rms_sum / input_len,
'total_loss': total_loss_sum / input_len,
'loss_list': loss_list_sum}
if (self.epoch_num + 1) % FLAGS.calc_ap_epoch_num == 0:
return_dict['Label_ap'] = Label_ap / input_len
return return_dict
def set_sigmas_and_wights(self):
if FLAGS.use_multi_loss:
for i, sigma_sq_tn in zip(range(len(self.multi_loss_class._sigmas_sq)), self.multi_loss_class._sigmas_sq):
sigma_sq = sigma_sq_tn.eval()
wight = 1 / (2 * sigma_sq)
self.statistics['sigmas_list'][i].append(sigma_sq)
self.statistics['weights_list'][i].append(wight)
def get_run_list(self, logits):
run_list = [logits[0], logits[1], logits[2], self.total_loss, self.processed_ground_truths[0]]
for loss in self.loss_list:
run_list.append(loss)
return run_list
def calc_and_save_examples(self, logits, sess):
example_inputs, example_ground_truths_many = dh.get_all_data('example')
for ind, example_input, example_ground_truths in zip(range(len(example_inputs)), example_inputs, example_ground_truths_many):
example_preds = (sess.run([logits[0], logits[1], logits[2]], feed_dict={self.input_ph: example_input}))
example_labelsID = self.calc_labelsID_rgb_img(example_preds[0])
mask = example_ground_truths[1][:, :, :, 2].squeeze(0)
if FLAGS.need_resize:
mask = scipy.misc.imresize(mask, (FLAGS.output_height, FLAGS.output_width))
mask = np.expand_dims(mask, 2)
example_InstanceID = self.calc_InstanceID_example(example_preds[1].squeeze(0), mask)
example_Disparity = example_preds[2]
scipy.misc.imsave(os.path.join(FLAGS.example_preds, 'label', "example_%08d_epoch_%08d.png" % (ind, self.epoch_num)), example_labelsID)
scipy.misc.imsave(os.path.join(FLAGS.example_preds, 'disp', "example_%08d_epoch_%08d.png" % (ind, self.epoch_num)), example_Disparity.squeeze())
if (self.epoch_num + 1) % FLAGS.example_OPTICS_epoch == 0:
scipy.misc.imsave(os.path.join(FLAGS.example_preds, 'instance', "example_%08d_epoch_%08d.png" % (ind, self.epoch_num)), example_InstanceID[0])
scipy.misc.imsave(os.path.join(FLAGS.example_preds, 'instance', "y_reg", "example_%08d_epoch_%08d.png" % (ind, self.epoch_num)), example_InstanceID[1])
scipy.misc.imsave(os.path.join(FLAGS.example_preds, 'instance', "x_reg", "example_%08d_epoch_%08d.png" % (ind, self.epoch_num)), example_InstanceID[2])
self.save_latest_example(ind, example_labelsID, example_Disparity, example_InstanceID)
return None
def save_latest_example(self, ind, example_labelsID, example_Disparity, example_InstanceID):
scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_label.png" % (ind)), example_labelsID)
scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_disp.png" % (ind)), example_Disparity.squeeze())
if (self.epoch_num + 1) % FLAGS.example_OPTICS_epoch == 0:
scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_instance.png" % (ind)), example_InstanceID[0])
plt.clf()
plt.pcolormesh(example_InstanceID[3], cmap='jet')
plt.gca().invert_yaxis()
plt.savefig(os.path.join(FLAGS.example_preds, 'instance', "y_reg", "example_%08d_latest.png" % (ind)))
plt.clf()
plt.pcolormesh(example_InstanceID[4], cmap='jet')
plt.gca().invert_yaxis()
plt.savefig(os.path.join(FLAGS.example_preds, 'instance', "x_reg", "example_%08d_latest.png" % (ind)))
np.save(os.path.join(FLAGS.example_preds, 'instance', "y_reg", "example_%08d_latest" % (ind)), example_InstanceID[3])
np.save(os.path.join(FLAGS.example_preds, 'instance', "x_reg", "example_%08d_latest" % (ind)), example_InstanceID[4])
def calc_InstanceID_example(self, xy_image, mask):
raw_image = np.concatenate([xy_image, mask], axis=2)
cmap = plt.get_cmap('jet')
y_image = np.delete(cmap(xy_image[:, :, 0]), 3, 2)
x_image = np.delete(cmap(xy_image[:, :, 1]), 3, 2)
opt = None
if (self.epoch_num + 1) % FLAGS.example_OPTICS_epoch == 0:
opt = OPTICS.calc_clusters_img(raw_image)
return [opt, y_image, x_image, xy_image[:, :, 0].squeeze(), xy_image[:, :, 1].squeeze()]
def calc_labelsID_rgb_img(self, label_pred):
labeled_img = label_pred.squeeze().argmax(axis=2)
#conc_labeled_img = np.concatenate([np.expand_dims(labeled_img, 2), np.expand_dims(labeled_img, 2)], 2)
#conc_labeled_img = np.concatenate([conc_labeled_img, np.expand_dims(labeled_img, 2)], 2)
size = [label_pred.shape[1], label_pred.shape[2]]
size.append(3)
rgb_img = np.zeros(size)
for ind, color in zip(range(len(config.colors[config.working_dataset])), config.colors[config.working_dataset]):
rgb_img[labeled_img == ind] = color
return rgb_img
def calc_labelsID_acc(self, pred, GT):
gt_labeled_img = GT.squeeze().argmax(axis=2)
labeled_img = pred.squeeze().argmax(axis=2)
return np.sum(gt_labeled_img == labeled_img) / (gt_labeled_img.size)
def calc_InstanceID_rms(self, pred, GT):
mask = np.expand_dims(GT[:, :, 2], axis=-1)
num_of_valid_pixels = np.sum(mask)
mask = np.concatenate([mask, mask], axis=2)
r_sq_matrix = np.sum(np.square(pred.squeeze()*mask - GT[:, :, 0:2]*mask), axis=-1)
if num_of_valid_pixels > 0:
per_pixel_rms = np.sum(np.sqrt(r_sq_matrix))/num_of_valid_pixels
total_rms = np.sqrt(np.sum(r_sq_matrix)/num_of_valid_pixels)
return per_pixel_rms, total_rms
else:
return 0, 0
def calc_LabelId_ap(self, pred, GT):
'''
Calculating Average Precision (without invalid classes (0-3))
'''
return aps(GT[:, :, :, 4:].reshape(-1), pred[:,:,:,4:].reshape(-1))
def calc_Disparity_rms(self, pred, GT):
mask = GT[:, :, 1]
num_of_valid_pixels = np.sum(mask)
r_sq_matrix = np.sum(np.square(pred.squeeze() * mask - GT[:, :, 0:1].squeeze() * mask), axis=-1)
if num_of_valid_pixels > 0:
per_pixel_rms = np.sum(np.sqrt(r_sq_matrix))/num_of_valid_pixels
total_rms = np.sqrt(np.sum(r_sq_matrix)/num_of_valid_pixels)
return per_pixel_rms, total_rms
else:
return 0, 0
def get_feed_dict(self, input, outputs):
feed_dict = {self.input_ph: input}
feed_dict[self.ground_truths_ph[0]] = outputs[0]
feed_dict[self.ground_truths_ph[1]] = outputs[1]
feed_dict[self.ground_truths_ph[2]] = outputs[2]
return feed_dict
def save_dict(self, dict_to_save, name):
f = open(os.path.join(FLAGS.stat_dump_path, name + '.pkl'), "wb")
pickle.dump(dict_to_save, f)
f.close()
def save_plots(self):
self.save_single_plots([self.statistics['total_loss']['val'], self.statistics['total_loss']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'total_loss'), title='total_loss',
ylabel='Total Loss', xlabel='Epoch')
self.save_single_plots([self.statistics['labelsID_acc']['val'], self.statistics['labelsID_acc']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'labelsID_acc'), title='Labels ID Accuracy',
ylabel='Accuracy', xlabel='Epoch')
self.save_single_plots([self.statistics['InstanceID_per_pixel_rms']['val'], self.statistics['InstanceID_per_pixel_rms']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'InstanceID_per_pixel_rms'), title='Instance ID per pixel RMS',
ylabel='RMS', xlabel='epoch')
self.save_single_plots([self.statistics['InstanceID_total_rms']['val'], self.statistics['InstanceID_total_rms']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'InstanceID_total_rms'),
title='Instance total RMS',
ylabel='RMS', xlabel='epoch')
self.save_single_plots([self.statistics['Disparity_per_pixel_rms']['val'], self.statistics['Disparity_per_pixel_rms']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'Disparity_per_pixel_rms'),
title='Disparity ID per pixel RMS',
ylabel='RMS', xlabel='epoch')
self.save_single_plots([self.statistics['Disparity_total_rms']['val'], self.statistics['Disparity_total_rms']['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'Disparity_total_rms'),
title='Disparity total RMS',
ylabel='RMS', xlabel='epoch')
self.save_dict(self.statistics, 'Statistics_dictionary')
#----- ap -----
if (self.epoch_num + 1) % FLAGS.calc_ap_epoch_num == 0:
# self.save_single_plots([self.Instance_ap_acc_eval['val'],
# self.Instance_ap_acc_eval['train']],
# ['val', 'train'], FLAGS.plots_path + '/InstanceID_ap',
# title='Instance ID Average Precision', ylabel='Average Percision', xlabel='Epoch')
self.save_single_plots([self.Label_ap_acc_eval['val'],
self.Label_ap_acc_eval['train']],
['val', 'train'], os.path.join(FLAGS.plots_path, 'labelsID_ap'), title='Labels ID Average Precision',
ylabel='Average Precision', xlabel='Epoch')
#--------------
for loss_num in range(len(self.loss_list)):
plot_path = os.path.join(FLAGS.plots_path, 'loss_' + str(loss_num)) #+ '_' + str(self.epoch_num)
self.save_single_plots([self.statistics['loss_lists']['val'][loss_num], self.statistics['loss_lists']['train'][loss_num]],
['val', 'train'], plot_path,
title='Loss num: ' + str(loss_num), ylabel='loss', xlabel='epoch')
legend = []
for i in range(len(self.statistics['sigmas_list'])):
legend.append('sigma ' + str(i))
self.save_single_plots(self.statistics['sigmas_list'], legend, os.path.join(FLAGS.plots_path, 'sigmas'), title='Sigmas Sq',
ylabel='sigma Sq value', xlabel='epoch')
legend = []
list_to_plot = []
if FLAGS.use_multi_loss:
for i in range(len(self.statistics['sigmas_list'])):
legend.append('TU ' + str(i))
list_to_plot.append(np.array(self.statistics['weights_list'][i])*np.array(self.statistics['loss_lists']['train'][i]+np.log(np.array(self.statistics['sigmas_list'][i]))))
self.save_single_plots(self.statistics['sigmas_list'], legend, os.path.join(FLAGS.plots_path, 'Task_uncertainty'), title='Task uncertainty',
ylabel='TU', xlabel='epoch')
legend = []
for i in range(len(self.statistics['weights_list'])):
legend.append('weight ' + str(i))
self.save_single_plots(self.statistics['weights_list'], legend, os.path.join(FLAGS.plots_path, 'weights'), title='Wights',
ylabel='wight value', xlabel='epoch')
scores_name_list = list(self.statistics['label_scores'].keys())
for name in scores_name_list:
if name in ['iu', 'cl_acc']:
continue
plot_path = os.path.join(FLAGS.plots_path, 'label_acc_' + name) # + str(self.epoch_num)
self.save_single_plots([self.statistics['label_scores'][name]['val'], self.statistics['label_scores'][name]['train']],
['val', 'train'], plot_path, title=name, ylabel=name, xlabel='epoch')
self.save_dict(self.statistics['label_scores'], 'label_scores')
def save_single_plots(self, results, legend, plot_path, title='model accuracy', ylabel='accuracy', xlabel='epoch'):
plt.clf()
epochs = range(len(results[0]))
for result in results:
plt.plot(epochs, result)
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.legend(legend, loc='upper right')
plt.savefig(plot_path + '.png')
def calc_and_set_label_scores(self, hist_2d, set_name):
acc, cl_acc_mean, iu_mean, cl_acc, iu = self.get_label_score(hist_2d)
iu_no_void_mean = self.calc_iu_no_void(iu)
self.statistics['label_scores']['acc'][set_name].append(acc)
self.statistics['label_scores']['cl_acc_mean'][set_name].append(cl_acc_mean)
self.statistics['label_scores']['iu_mean'][set_name].append(iu_mean)
self.statistics['label_scores']['iu_no_void_mean'][set_name].append(iu_no_void_mean)
self.statistics['label_scores']['cl_acc'][set_name].append(cl_acc)
self.statistics['label_scores']['iu'][set_name].append(iu)
def calc_iu_no_void(self, iu): #TODO: need to fix
index_list = []
for i in range(28):
if i not in [0, 1, 2, 3, 4, 5, 6, 9, 10, 14, 15, 16, 18, 12, 29, 30]: #TODO: move to config
index_list.append(i)
return np.nanmean(iu[index_list])
def get_label_score(self, hist):
# Mean pixel accuracy
acc = np.diag(hist).sum() / (hist.sum() + 1e-12)
# Per class accuracy
cl_acc = np.diag(hist) / (hist.sum(1) + 1e-12)
# Per class IoU
iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist) + 1e-12)
return acc, np.nanmean(cl_acc), np.nanmean(iu), cl_acc, iu
def fast_hist(self, a, b, n):
n = len(config.colors[config.working_dataset])
a = a.squeeze().argmax(axis=2).flatten()
b = b.squeeze().argmax(axis=2).flatten()
k = np.where((a >= 0) & (a < n))[0]
bc = np.bincount(n * a[k].astype(int) + b[k], minlength=n ** 2)
if len(bc) != n ** 2:
# ignore this example if dimension mismatch
return 0
return bc.reshape(n, n)
| 12,308 |
679 | <gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef SW_UNDO_OVERWRITE_HXX
#define SW_UNDO_OVERWRITE_HXX
#include <undobj.hxx>
#include <com/sun/star/uno/Sequence.h>
class SwRedlineSaveDatas;
class SwTxtNode;
namespace utl {
class TransliterationWrapper;
}
class SwUndoOverwrite: public SwUndo, private SwUndoSaveCntnt
{
String aDelStr, aInsStr;
SwRedlineSaveDatas* pRedlSaveData;
sal_uLong nSttNode;
xub_StrLen nSttCntnt;
sal_Bool bInsChar : 1; // no Overwrite, but Insert
sal_Bool bGroup : 1; // TRUE: is already grouped; evaluated in CanGrouping()
public:
SwUndoOverwrite( SwDoc*, SwPosition&, sal_Unicode cIns );
virtual ~SwUndoOverwrite();
virtual void UndoImpl( ::sw::UndoRedoContext & );
virtual void RedoImpl( ::sw::UndoRedoContext & );
virtual void RepeatImpl( ::sw::RepeatContext & );
// #111827#
/**
Returns the rewriter of this undo object.
The rewriter contains the following rule:
$1 -> '<overwritten text>'
<overwritten text> is shortened to nUndoStringLength characters.
@return the rewriter of this undo object
*/
virtual SwRewriter GetRewriter() const;
sal_Bool CanGrouping( SwDoc*, SwPosition&, sal_Unicode cIns );
};
//--------------------------------------------------------------------
struct _UndoTransliterate_Data;
class SwUndoTransliterate : public SwUndo, public SwUndRng
{
std::vector< _UndoTransliterate_Data * > aChanges;
sal_uInt32 nType;
void DoTransliterate(SwDoc & rDoc, SwPaM & rPam);
public:
SwUndoTransliterate( const SwPaM& rPam,
const utl::TransliterationWrapper& rTrans );
virtual ~SwUndoTransliterate();
virtual void UndoImpl( ::sw::UndoRedoContext & );
virtual void RedoImpl( ::sw::UndoRedoContext & );
virtual void RepeatImpl( ::sw::RepeatContext & );
void AddChanges( SwTxtNode& rTNd, xub_StrLen nStart, xub_StrLen nLen,
::com::sun::star::uno::Sequence <sal_Int32>& rOffsets );
sal_Bool HasData() const { return aChanges.size() > 0; }
};
#endif // SW_UNDO_OVERWRITE_HXX
| 1,052 |
1,350 | <filename>sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePage.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.util.paging;
import com.azure.core.util.IterableStream;
/**
* Represents a page returned, this page may contain a reference to additional pages known as a continuation token.
*
* @param <C> Type of the continuation token.
* @param <T> Type of the elements in the page.
* @see ContinuablePagedFlux
*/
public interface ContinuablePage<C, T> {
/**
* Gets an {@link IterableStream} of elements in the page.
*
* @return An {@link IterableStream} containing the elements in the page.
*/
IterableStream<T> getElements();
/**
* Gets the reference to the next page.
*
* @return The next page reference or {@code null} if there isn't a next page.
*/
C getContinuationToken();
}
| 313 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.