max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
583 | <gh_stars>100-1000
#ifndef FLOWCLIPTREEMODEL_H
#define FLOWCLIPTREEMODEL_H
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include "flowclip.h"
class FlowClipTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
FlowClipTreeModel(const QList<QGraphicsItem*> &roots, QObject *parent = 0);
~FlowClipTreeModel();
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
void addItem(QGraphicsItem *item);
void removeItem(QGraphicsItem *item);
void setItemParent(QGraphicsItem *item, QGraphicsItem *parent);
void itemDataChanged(QGraphicsItem *item, int column);
private:
QModelIndex findItemPath(QGraphicsItem *item, int column = 0) const;
QGraphicsItem *getItem(const QModelIndex &index) const;
QList<QGraphicsItem*> roots;
};
#endif // FLOWCLIPTREEMODEL_H
| 519 |
1,338 | <filename>junction/extra/impl/MapAdapter_Crude.h<gh_stars>1000+
/*------------------------------------------------------------------------
Junction: Concurrent data structures in C++
Copyright (c) 2016 <NAME>
Distributed under the Simplified BSD License.
Original location: https://github.com/preshing/junction
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the LICENSE file for more information.
------------------------------------------------------------------------*/
#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_CRUDE_H
#define JUNCTION_EXTRA_IMPL_MAPADAPTER_CRUDE_H
#include <junction/Core.h>
#include <junction/ConcurrentMap_Crude.h>
#include <turf/Util.h>
namespace junction {
namespace extra {
class MapAdapter {
public:
static TURF_CONSTEXPR const char* getMapName() { return "Junction Crude map"; }
MapAdapter(ureg) {
}
class ThreadContext {
public:
ThreadContext(MapAdapter&, ureg) {
}
void registerThread() {
}
void unregisterThread() {
}
void update() {
}
};
typedef ConcurrentMap_Crude<u32, void*> Map;
static ureg getInitialCapacity(ureg maxPopulation) {
return turf::util::roundUpPowerOf2(ureg(maxPopulation * 1.25f));
}
};
} // namespace extra
} // namespace junction
#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_CRUDE_H
| 508 |
775 | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework 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.
import webbrowser
import wx
from wx import html, Colour
from ..preferences.settings import RideSettings
#TODO: Make this colour configurable
# HTML_BACKGROUND = (240, 242, 80) # (200, 222, 40)
_settings = RideSettings()
general_settings = _settings['General']
HTML_BACKGROUND = general_settings['background help']
class HtmlWindow(html.HtmlWindow):
def __init__(self, parent, size=wx.DefaultSize, text=None):
html.HtmlWindow.__init__(self, parent, size=size)
self.SetBorders(2)
self.SetStandardFonts(size=9)
self.SetBackgroundColour(Colour(200, 222, 40))
self.SetOwnBackgroundColour(Colour(200, 222, 40))
self.SetOwnForegroundColour(Colour(7, 0, 70))
if text:
self.set_content(text)
self.SetHTMLBackgroundColour(Colour(general_settings['background help']))
self.SetForegroundColour(Colour(general_settings['foreground help']))
self.font = self.GetFont()
self.font.SetFaceName(general_settings['font face'])
self.font.SetPointSize(general_settings['font size'])
self.SetFont(self.font)
self.Refresh(True)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
def set_content(self, content):
color = ''.join(hex(item)[2:] for item in general_settings['background help'])
_content = '<body bgcolor=#%s>%s</body>' % (color, content)
self.SetPage(_content)
def OnKeyDown(self, event):
if self._is_copy(event):
self._add_selection_to_clipboard()
self.Parent.OnKey(event)
event.Skip()
def _is_copy(self, event):
return event.GetKeyCode() == ord('C') and event.CmdDown()
def _add_selection_to_clipboard(self):
wx.TheClipboard.Open()
wx.TheClipboard.SetData(wx.TextDataObject(self.SelectionToText()))
wx.TheClipboard.Close()
def OnLinkClicked(self, link):
webbrowser.open(link.Href)
def close(self):
self.Show(False)
def clear(self):
self.SetPage('')
| 1,030 |
575 | // 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 "chrome/browser/ui/webui/tab_strip/tab_strip_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_embedder.h"
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.h"
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_layout.h"
#include "chrome/browser/ui/webui/theme_handler.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/tab_strip_resources.h"
#include "chrome/grit/tab_strip_resources_map.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "content/public/common/url_constants.h"
#include "ui/base/theme_provider.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/color_utils.h"
#include "ui/resources/grit/webui_resources.h"
// These data types must be in all lowercase.
const char kWebUITabIdDataType[] = "application/vnd.chromium.tab";
const char kWebUITabGroupIdDataType[] = "application/vnd.chromium.tabgroup";
TabStripUI::TabStripUI(content::WebUI* web_ui)
: content::WebUIController(web_ui) {
content::HostZoomMap::Get(web_ui->GetWebContents()->GetSiteInstance())
->SetZoomLevelForHostAndScheme(content::kChromeUIScheme,
chrome::kChromeUITabStripHost, 0);
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(chrome::kChromeUITabStripHost);
webui::SetupWebUIDataSource(
html_source, base::make_span(kTabStripResources, kTabStripResourcesSize),
IDR_TAB_STRIP_TAB_STRIP_HTML);
html_source->AddString("tabIdDataType", kWebUITabIdDataType);
html_source->AddString("tabGroupIdDataType", kWebUITabGroupIdDataType);
// Add a load time string for the frame color to allow the tab strip to paint
// a background color that matches the frame before any content loads
const ui::ThemeProvider& tp =
ThemeService::GetThemeProviderForProfile(profile);
html_source->AddString("frameColor",
color_utils::SkColorToRgbaString(
tp.GetColor(ThemeProperties::COLOR_FRAME_ACTIVE)));
static constexpr webui::LocalizedString kStrings[] = {
{"newTab", IDS_TOOLTIP_NEW_TAB},
{"tabListTitle", IDS_ACCNAME_TAB_LIST},
{"closeTab", IDS_ACCNAME_CLOSE},
{"defaultTabTitle", IDS_DEFAULT_TAB_TITLE},
{"loadingTab", IDS_TAB_LOADING_TITLE},
{"tabCrashed", IDS_TAB_AX_LABEL_CRASHED_FORMAT},
{"tabNetworkError", IDS_TAB_AX_LABEL_NETWORK_ERROR_FORMAT},
{"audioPlaying", IDS_TAB_AX_LABEL_AUDIO_PLAYING_FORMAT},
{"usbConnected", IDS_TAB_AX_LABEL_USB_CONNECTED_FORMAT},
{"bluetoothConnected", IDS_TAB_AX_LABEL_BLUETOOTH_CONNECTED_FORMAT},
{"hidConnected", IDS_TAB_AX_LABEL_HID_CONNECTED_FORMAT},
{"serialConnected", IDS_TAB_AX_LABEL_SERIAL_CONNECTED_FORMAT},
{"mediaRecording", IDS_TAB_AX_LABEL_MEDIA_RECORDING_FORMAT},
{"audioMuting", IDS_TAB_AX_LABEL_AUDIO_MUTING_FORMAT},
{"tabCapturing", IDS_TAB_AX_LABEL_DESKTOP_CAPTURING_FORMAT},
{"pipPlaying", IDS_TAB_AX_LABEL_PIP_PLAYING_FORMAT},
{"desktopCapturing", IDS_TAB_AX_LABEL_DESKTOP_CAPTURING_FORMAT},
{"vrPresenting", IDS_TAB_AX_LABEL_VR_PRESENTING},
{"unnamedGroupLabel", IDS_GROUP_AX_LABEL_UNNAMED_GROUP_FORMAT},
{"namedGroupLabel", IDS_GROUP_AX_LABEL_NAMED_GROUP_FORMAT},
};
html_source->AddLocalizedStrings(kStrings);
content::WebUIDataSource::Add(profile, html_source);
content::URLDataSource::Add(
profile, std::make_unique<FaviconSource>(
profile, chrome::FaviconUrlFormat::kFavicon2));
web_ui->AddMessageHandler(std::make_unique<ThemeHandler>());
}
TabStripUI::~TabStripUI() = default;
WEB_UI_CONTROLLER_TYPE_IMPL(TabStripUI)
void TabStripUI::Initialize(Browser* browser, TabStripUIEmbedder* embedder) {
content::WebUI* const web_ui = TabStripUI::web_ui();
DCHECK_EQ(Profile::FromWebUI(web_ui), browser->profile());
auto handler = std::make_unique<TabStripUIHandler>(browser, embedder);
handler_ = handler.get();
web_ui->AddMessageHandler(std::move(handler));
}
void TabStripUI::LayoutChanged() {
handler_->NotifyLayoutChanged();
}
void TabStripUI::ReceivedKeyboardFocus() {
handler_->NotifyReceivedKeyboardFocus();
}
| 2,046 |
2,231 | <gh_stars>1000+
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 DM_PARTICLE_H
#define DM_PARTICLE_H
#include <dmsdk/vectormath/cpp/vectormath_aos.h>
#include <dlib/configfile.h>
#include <dlib/hash.h>
#include <ddf/ddf.h>
#include "particle/particle_ddf.h"
/*extern "C"
{
#include <lua/lua.h>
#include <lua/lauxlib.h>
}*/
/**
* System to handle particle systems
*/
namespace dmParticle
{
using namespace Vectormath::Aos;
/**
* Context handle
*/
typedef struct Context* HParticleContext;
/**
* Prototype handle
*/
typedef struct Prototype* HPrototype;
/**
* Instance handle
*/
typedef uint32_t HInstance;
/**
* Invalid context handle
*/
const HParticleContext INVALID_CONTEXT = 0;
/**
* Invalid prototype handle
*/
const HPrototype INVALID_PROTOTYPE = 0;
/**
* Invalid instance handle
*/
const HInstance INVALID_INSTANCE = 0;
/// Config key to use for tweaking maximum number of instances in a context.
extern const char* MAX_INSTANCE_COUNT_KEY;
/// Config key to use for tweaking the total maximum number of particles in a context.
extern const char* MAX_PARTICLE_COUNT_KEY;
/**
* Render constants supplied to the render callback.
*/
struct RenderConstant
{
dmhash_t m_NameHash;
Vector4 m_Value;
};
/**
* Callback to handle rendering of emitters
*/
typedef void (*RenderEmitterCallback)(void* usercontext, void* material, void* texture, const Vectormath::Aos::Matrix4& world_transform, dmParticleDDF::BlendMode blend_mode, uint32_t vertex_index, uint32_t vertex_count, RenderConstant* constants, uint32_t constant_count);
/**
* Callback to handle rendering of lines for debug purposes
*/
typedef void (*RenderLineCallback)(void* usercontext, const Vectormath::Aos::Point3& start, const Vectormath::Aos::Point3& end, const Vectormath::Aos::Vector4& color);
enum AnimPlayback
{
ANIM_PLAYBACK_NONE = 0,
ANIM_PLAYBACK_ONCE_FORWARD = 1,
ANIM_PLAYBACK_ONCE_BACKWARD = 2,
ANIM_PLAYBACK_LOOP_FORWARD = 3,
ANIM_PLAYBACK_LOOP_BACKWARD = 4,
ANIM_PLAYBACK_LOOP_PINGPONG = 5,
ANIM_PLAYBACK_ONCE_PINGPONG = 6,
};
struct AnimationData
{
AnimationData();
void* m_Texture;
float* m_TexCoords;
float* m_TexDims;
AnimPlayback m_Playback;
uint32_t m_TileWidth;
uint32_t m_TileHeight;
uint32_t m_StartTile;
uint32_t m_EndTile;
uint32_t m_FPS;
uint32_t m_HFlip;
uint32_t m_VFlip;
/// Clients are responsible for setting this to the size of the AnimationData (e.g. in ParticleLibrary.java)
uint32_t m_StructSize;
};
enum FetchAnimationResult
{
FETCH_ANIMATION_OK = 0,
FETCH_ANIMATION_NOT_FOUND = -1,
FETCH_ANIMATION_UNKNOWN_ERROR = -1000
};
enum EmitterState
{
EMITTER_STATE_SLEEPING = 0,
EMITTER_STATE_PRESPAWN = 1,
EMITTER_STATE_SPAWNING = 2,
EMITTER_STATE_POSTSPAWN = 3,
};
enum ParticleVertexFormat
{
PARTICLE_GO = 0,
PARTICLE_GUI = 1,
};
struct EmitterRenderData
{
EmitterRenderData()
{
memset(this, 0x0, sizeof(EmitterRenderData));
}
Matrix4 m_Transform;
void* m_Material; // dmRender::HMaterial
dmParticleDDF::BlendMode m_BlendMode;
void* m_Texture; // dmGraphics::HTexture
RenderConstant* m_RenderConstants;
uint32_t m_RenderConstantsSize;
HInstance m_Instance; // Particle instance handle
uint32_t m_EmitterIndex;
uint32_t m_MixedHash;
uint32_t m_MixedHashNoMaterial;
};
/**
* Callback for emitter state changed
*/
typedef void (*EmitterStateChanged)(uint32_t num_awake_emitters, dmhash_t emitter_id, EmitterState emitter_state, void* user_data);
/**
* Data for emitter state change callback
*/
struct EmitterStateChangedData
{
EmitterStateChangedData()
{
m_UserData = 0x0;
}
EmitterStateChanged m_StateChangedCallback;
void* m_UserData;
};
/**
* Callback to fetch the animation from a tile source
*/
typedef FetchAnimationResult (*FetchAnimationCallback)(void* tile_source, dmhash_t animation, AnimationData* out_data);
/**
* Particle statistics
*/
struct Stats
{
Stats()
{
m_StructSize = sizeof(*this);
}
uint32_t m_Particles;
uint32_t m_MaxParticles;
uint32_t m_StructSize;
};
/**
* Particle instance statistics
*/
struct InstanceStats
{
InstanceStats()
{
m_StructSize = sizeof(*this);
}
float m_Time;
uint32_t m_StructSize;
};
/**
* Particle vertex format
*/
struct Vertex
{
// Offset 0
float m_X, m_Y, m_Z;
// Offset 12
float m_Red, m_Green, m_Blue, m_Alpha;
// Offset 28
float m_U, m_V;
// Offset 36
};
/**
* Particle gui vertex format (must match dmGui::ParticleGuiVertex)
*/
struct ParticleGuiVertex
{
// Offset 0
float m_Position[3];
// Offset 12
float m_UV[2];
// Offset 20
float m_Color[4];
// Offset 36
};
// For tests
Vector3 GetPosition(HParticleContext context, HInstance instance);
#define DM_PARTICLE_PROTO(ret, name, ...) \
\
ret name(__VA_ARGS__);\
extern "C" DM_DLLEXPORT ret Particle_##name(__VA_ARGS__)
/**
* Create a context.
* @param max_instance_count Max number of instances
* @param max_particle_count Max number of particles
* @return Context handle, or INVALID_CONTEXT when out of memory.
*/
DM_PARTICLE_PROTO(HParticleContext, CreateContext, uint32_t max_instance_count, uint32_t max_particle_count);
/**
* Destroy a context.
* @param context Context to destroy. This will also destroy any remaining instances.
*/
DM_PARTICLE_PROTO(void, DestroyContext, HParticleContext context);
/**
* Retrieve max particle count for the context.
* @param context Context to update.
* @return Max number of particles
*/
DM_PARTICLE_PROTO(uint32_t, GetContextMaxParticleCount, HParticleContext context);
/**
* Set new max particle count for the context.
* @param context Context to update.
* @param max_particle_count Max number of particles
*/
DM_PARTICLE_PROTO(void, SetContextMaxParticleCount, HParticleContext context, uint32_t max_particle_count);
/**
* Create an instance from the supplied path and fetch resources using the supplied factory.
* @param context Context in which to create the instance, must be valid.
* @param prototype Prototype of the instance to be created
* @param Pointer to data for emitter state change callback
* @param fetch_animation_callback Callback to set animation data.
* @return Instance handle, or INVALID_INSTANCE when the resource is broken or the context is full.
*/
DM_PARTICLE_PROTO(HInstance, CreateInstance, HParticleContext context, HPrototype prototype, EmitterStateChangedData* data);
/**
* Destroy instance in the specified context.
* @param context Context handle, must be valid.
* @param instance Instance to destroy, can be invalid.
*/
DM_PARTICLE_PROTO(void, DestroyInstance, HParticleContext context, HInstance instance);
/**
* Reload instance in the specified context based on its prototype.
* @param context Context handle, must be valid.
* @param instance Instance to reload, can be invalid.
* @param replay if emitters should be replayed
*/
DM_PARTICLE_PROTO(void, ReloadInstance, HParticleContext context, HInstance instance, bool replay);
/**
* Start the specified instance, which means it will start spawning particles.
* @param context Context in which the instance exists.
* @param instance Instance to start, can be invalid.
*/
DM_PARTICLE_PROTO(void, StartInstance, HParticleContext context, HInstance instance);
/**
* Stop the specified instance, which means it will stop spawning particles.
* Any spawned particles will still be simulated until they die.
* @param context Context in which the instance exists.
* @param instance Instance to start, can be invalid.
*/
DM_PARTICLE_PROTO(void, StopInstance, HParticleContext context, HInstance instance);
/**
* Retire the specified instance, which means it will stop spawning particles at the closest convenient time.
* In practice this means that looping emitters will continue for the current life cycle and then stop, like a once emitter.
* Any spawned particles will still be simulated until they die.
* @param context Context in which the instance exists.
* @param instance Instance to start, can be invalid.
*/
DM_PARTICLE_PROTO(void, RetireInstance, HParticleContext context, HInstance instance);
/**
* Reset the specified instance, which means its state will be like when first created.
* Any already living particles will be annihilated.
* @param context Context in which the instance exists.
* @param instance Instance to reset, can be invalid.
*/
DM_PARTICLE_PROTO(void, ResetInstance, HParticleContext context, HInstance instance);
/**
* Set the position of the specified instance.
* @param context Context in which the instance exists.
* @param instance Instance to set position for.
* @param position Position in world space.
*/
DM_PARTICLE_PROTO(void, SetPosition, HParticleContext context, HInstance instance, const Point3& position);
/**
* Set the rotation of the specified instance.
* @param context Context in which the instance exists.
* @param instance Instance to set rotation for.
* @param rotation Rotation in world space.
*/
DM_PARTICLE_PROTO(void, SetRotation, HParticleContext context, HInstance instance, const Quat& rotation);
/**
* Set the scale of the specified instance.
* @param context Context in which the instance exists.
* @param instance Instance to set scale for.
* @param scale Scale in world space.
*/
DM_PARTICLE_PROTO(void, SetScale, HParticleContext context, HInstance instance, float scale);
/**
* Set if the scale should be used along Z or not.
* @param context Context in which the instance exists.
* @param instance Instance to set the property for.
* @param scale_along_z Whether the scale should be used along Z.
*/
DM_PARTICLE_PROTO(void, SetScaleAlongZ, HParticleContext context, HInstance instance, bool scale_along_z);
/**
* Returns if the specified instance is spawning particles or not.
* Instances are sleeping when they are not spawning and have no remaining living particles.
*/
DM_PARTICLE_PROTO(bool, IsSleeping, HParticleContext context, HInstance instance);
/**
* Update the instances within the specified context.
* @param context Context of the instances to update.
* @param dt Time step.
*/
DM_PARTICLE_PROTO(void, Update, HParticleContext context, float dt, FetchAnimationCallback fetch_animation_callback);
/**
* Gets the vertex count for rendering the emitter at a given emitter index
* @param context Particle context
* @param instance Particle instance handle
* @param emitter_index Emitter index for which to get the vertex count
* @return vertex count needed to render the emitter
*/
DM_PARTICLE_PROTO(uint32_t, GetEmitterVertexCount, HParticleContext context, HInstance instance, uint32_t emitter_index);
/**
* Generates vertex data for an emitter
* @param context Particle context
* @param dt Time step.
* @param instance Particle instance handle
* @param emitter_index Emitter index for which to generate vertex data for
* @param vertex_buffer Vertex buffer into which to store the particle vertex data. If this is 0x0, no data will be generated.
* @param vertex_buffer_size Size in bytes of the supplied vertex buffer.
* @param out_vertex_buffer_size Size in bytes of the total data written to vertex buffer.
* @param vertex_format Which vertex format to use
*/
DM_PARTICLE_PROTO(void, GenerateVertexData, HParticleContext context, float dt, HInstance instance, uint32_t emitter_index, const Vector4& color, void* vertex_buffer, uint32_t vertex_buffer_size, uint32_t* out_vertex_buffer_size, ParticleVertexFormat vertex_format);
/**
* Debug render the status of the instances within the specified context.
* @param context Context of the instances to render.
* @param RenderLine Function pointer to use to render the lines.
*/
DM_PARTICLE_PROTO(void, DebugRender, HParticleContext context, void* user_context, RenderLineCallback render_line_callback);
/**
* Create a new prototype from ddf data.
* @param buffer Buffer of ddf data
* @param buffer_size Size of ddf data
* @return prototype handle
*/
DM_PARTICLE_PROTO(HPrototype, NewPrototype, const void* buffer, uint32_t buffer_size);
/**
* Create a new prototype from ddf message data.
* Ownership of message data is transferred to the particle system.
* @param message pointer to ParticleDDF message
* @return prototype handle
*/
DM_PARTICLE_PROTO(HPrototype, NewPrototypeFromDDF, dmParticleDDF::ParticleFX* message);
/**
* Delete a prototype
* @param prototype Prototype to delete
*/
DM_PARTICLE_PROTO(void, DeletePrototype, HPrototype prototype);
/**
* Reload a prototype. This does not update any dependant instances which should be recreated.
* @param prototype Prototype to reload
* @param buffer Buffer of ddf data
* @param buffer_size Size of ddf data
*/
DM_PARTICLE_PROTO(bool, ReloadPrototype, HPrototype prototype, const void* buffer, uint32_t buffer_size);
/**
* Retrieve number of emitters in the supplied prototype
* @param prototype Prototype
*/
DM_PARTICLE_PROTO(uint32_t, GetEmitterCount, HPrototype prototype);
/**
* Retrieve number of emitters on the supplied instance
* @param context Context of the instance
* @param instance The instance of which to get emitter count from
* @return The number of emitters on the instance
*/
DM_PARTICLE_PROTO(uint32_t, GetInstanceEmitterCount, HParticleContext context, HInstance instance);
/**
* Render the specified emitter
* @param context Context of the emitter to render.
* @param instance Instance of the emitter to render.
* @param emitter_index Index of the emitter to render.
* @param user_context Context to pass to the callback.
* @param render_instance_callback Callback function that will be called with emitter data for actual rendering
* @see Render
*/
DM_PARTICLE_PROTO(void, RenderEmitter, HParticleContext context, HInstance instance, uint32_t emitter_index, void* user_context, RenderEmitterCallback render_instance_callback);
/**
* Retrieve data needed to render emitter
* @param context Context of the instance
* @param instance Instance which holds the emitter
* @param emitter_index The index of the emitter for which to get render data for
* @param data Out data for emitter render data.
*/
DM_PARTICLE_PROTO(void, GetEmitterRenderData, HParticleContext context, HInstance instance, uint32_t emitter_index, EmitterRenderData** data);
/**
* Retrieve material path from the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
*/
DM_PARTICLE_PROTO(const char*, GetMaterialPath, HPrototype prototype, uint32_t emitter_index);
/**
* Retrieve tile source path from the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
*/
DM_PARTICLE_PROTO(const char*, GetTileSourcePath, HPrototype prototype, uint32_t emitter_index);
/**
* Retrieve material from the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
* @return pointer to the material
*/
DM_PARTICLE_PROTO(void*, GetMaterial, HPrototype prototype, uint32_t emitter_index);
/**
* Retrieve tile source from the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
* @return pointer to the tile source
*/
DM_PARTICLE_PROTO(void*, GetTileSource, HPrototype prototype, uint32_t emitter_index);
/**
* Set material in the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
* @param material Material to set
*/
DM_PARTICLE_PROTO(void, SetMaterial, HPrototype prototype, uint32_t emitter_index, void* material);
/**
* Set tile source in the emitter in the supplied prototype
* @param prototype Prototype
* @param emitter_index Index of the emitter in question
* @param tile_source Tile source to set
*/
DM_PARTICLE_PROTO(void, SetTileSource, HPrototype prototype, uint32_t emitter_index, void* tile_source);
/**
* Set a render constant for the emitter with the specified id
* @param context Particle context
* @param instance Instance containing the emitter
* @param emitter_id Id of the emitter
* @param name_hash Hashed name of the constant to set
* @param value Value to set the constant to
*/
DM_PARTICLE_PROTO(void, SetRenderConstant, HParticleContext context, HInstance instance, dmhash_t emitter_id, dmhash_t name_hash, Vector4 value);
/**
* Reset a render constant for the emitter with the specified id
* @param context Particle context
* @param instance Instance containing the emitter
* @param emitter_id Id of the emitter
* @param name_hash Hashed name of the constant to reset
*/
DM_PARTICLE_PROTO(void, ResetRenderConstant, HParticleContext context, HInstance instance, dmhash_t emitter_id, dmhash_t name_hash);
/**
* Get statistics
* @param context Particle context
* @param stats Pointer to stats structure
*/
DM_PARTICLE_PROTO(void, GetStats, HParticleContext context, Stats* stats);
/**
* Get instance statistics
* @param context Particle context
* @param instance Instance to get stats for
* @param stats Pointer to instance stats structure
*/
DM_PARTICLE_PROTO(void, GetInstanceStats, HParticleContext context, HInstance instance, InstanceStats* stats);
/**
* Get required vertex buffer size
* @param particle_count number of particles in vertex buffer
* @param vertex_format Which vertex format to use
* @return Required vertex buffer size in bytes
*/
DM_PARTICLE_PROTO(uint32_t, GetVertexBufferSize, uint32_t particle_count, ParticleVertexFormat vertex_format);
/**
* Get the required vertex buffer size for a context
* @param context Particle context
* @param vertex_format Which vertex format to use
* @return Required vertex buffer size in bytes
*/
DM_PARTICLE_PROTO(uint32_t, GetMaxVertexBufferSize, HParticleContext context, ParticleVertexFormat vertex_format);
/**
* Rehash all emitters on an instance
* @param context Particle context
* @param instance Instance containing the emitters to be rehashed
*/
DM_PARTICLE_PROTO(void, ReHash, HParticleContext context, HInstance instance);
/**
* Wrapper for dmHashString64
* @param value string to hash
* @return hashed string
*/
extern "C" DM_DLLEXPORT dmhash_t Particle_Hash(const char* value);
#undef DM_PARTICLE_PROTO
}
#endif // DM_PARTICLE_H
| 7,517 |
683 |
# coding: utf-8
# In[1]:
import gym
import numpy as np
import sys
import matplotlib
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.blackjack import BlackjackEnv
from lib import plotting
from collections import defaultdict
matplotlib.style.use('ggplot')
# In[2]:
env = BlackjackEnv()
# In[3]:
def mc_prediction(policy, env, num_episodes, discount_factor=1.0):
"""
Monte Carlo First-Visit prediction algorithm. Calculates the value function
for a given policy using sampling.
Args:
policy: A function that maps an observation to action probabilities.
env: OpenAI gym environment.
num_episodes: Number of episodes to sample.
discount_factor: Gamma discount factor.
Returns:
A dictionary that maps from state -> value.
The state is a tuple and the value is a float.
"""
# store the number of times each state is visited
returns_num = defaultdict(float)
# value function to be returned
V = defaultdict(float)
# termination condition
for episode in range(num_episodes):
# store the eligibility trace corresponding to each state for each episode
eligibility_traces = defaultdict(float)
# store the reward corresponding to each state for each episode
episode_rewards = defaultdict(float)
terminated = False
state = env.reset()
# termination condition
while not terminated:
# update the eligibility trace for the states already visited in the episode
for _state in eligibility_traces:
eligibility_traces[_state] *= discount_factor
# add a new state to the dictionary if it's not been visited before
if state not in eligibility_traces:
eligibility_traces[state] = 1.0
returns_num[state] += 1
# get the action following the policy
action = np.argmax(policy(state))
# perform the action in the environment
next_state, reward, terminated, _ = env.step(action)
# update the reward for each state
for _state in eligibility_traces:
episode_rewards[_state] += eligibility_traces[_state] * reward
# update the current state
state = next_state
# update the value function using incremental mean method
for state in episode_rewards:
V[state] += (episode_rewards[state] - V[state]) / returns_num[state]
return V
# In[4]:
def sample_policy(observation):
"""
A policy that sticks if the player score is > 20 and hits otherwise.
"""
player_score, dealer_score, usable_ace = observation
return np.array([1.0, 0.0]) if player_score >= 20 else np.array([0.0, 1.0])
# In[5]:
V_10k = mc_prediction(sample_policy, env, num_episodes=10000)
plotting.plot_value_function(V_10k, title="10,000 Steps")
# In[18]:
V_500k = mc_prediction(sample_policy, env, num_episodes=500000)
plotting.plot_value_function(V_500k, title="500,000 Steps")
| 1,392 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_RENDERER_DOM_HOOKS_DELEGATE_H_
#define EXTENSIONS_RENDERER_DOM_HOOKS_DELEGATE_H_
#include <string>
#include "extensions/renderer/bindings/api_binding_hooks_delegate.h"
#include "v8/include/v8-forward.h"
namespace extensions {
class ScriptContext;
// The custom hooks for the chrome.dom API.
class DOMHooksDelegate : public APIBindingHooksDelegate {
public:
DOMHooksDelegate();
~DOMHooksDelegate() override;
DOMHooksDelegate(const DOMHooksDelegate&) = delete;
DOMHooksDelegate& operator=(const DOMHooksDelegate&) = delete;
// APIBindingHooksDelegate:
APIBindingHooks::RequestResult HandleRequest(
const std::string& method_name,
const APISignature* signature,
v8::Local<v8::Context> context,
std::vector<v8::Local<v8::Value>>* arguments,
const APITypeReferenceMap& refs) override;
private:
v8::Local<v8::Value> OpenOrClosedShadowRoot(
ScriptContext* script_context,
const std::vector<v8::Local<v8::Value>>& parsed_arguments);
};
} // namespace extensions
#endif // EXTENSIONS_RENDERER_DOM_HOOKS_DELEGATE_H_
| 457 |
1,062 | <gh_stars>1000+
/**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/file.h>
#include <log4cxx/logger.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/helpers/fileinputstream.h>
#include <log4cxx/helpers/properties.h>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <mutex>
#include "util/util_api.h"
using log4cxx::AppenderPtr;
using log4cxx::BasicConfigurator;
using log4cxx::File;
using log4cxx::FileAppender;
using log4cxx::Logger;
using log4cxx::LoggerPtr;
using log4cxx::LogManager;
using log4cxx::PropertyConfigurator;
using log4cxx::helpers::FileInputStream;
using log4cxx::helpers::FileInputStreamPtr;
namespace MR4C {
class MR4CLoggingImpl {
friend class MR4CLogging;
private:
std::string FRAMEWORK_ROOT;
std::string ALGO_ROOT;
std::string CONF;
std::string PROP;
bool m_init;
bool m_defaultInit;
bool m_defaultInitMR4C;
bool m_initMR4C;
std::string m_file;
std::mutex m_mutex;
static MR4CLoggingImpl& instance() {
static MR4CLoggingImpl s_instance;
return s_instance;
}
MR4CLoggingImpl() {
// C++ makes declaring string constants really painful!
FRAMEWORK_ROOT = "mr4c.native";
ALGO_ROOT = "mr4c.algo";
CONF = "/etc/mr4c";
PROP = "mr4c.logger.config";
m_init=false;
m_defaultInit=false;
m_defaultInitMR4C=false;
m_initMR4C=false;
}
LoggerPtr getLogger(const std::string& name) {
initLogging();
return getLoggerHelper(name);
}
LoggerPtr getLoggerHelper(const std::string& name) {
std::ostringstream ss;
ss << FRAMEWORK_ROOT << '.' << name;
return Logger::getLogger(ss.str());
}
LoggerPtr getAlgorithmLogger(const std::string& name) {
initLogging();
std::ostringstream ss;
ss << ALGO_ROOT << '.' << name;
return Logger::getLogger(ss.str());
}
void initLogging() {
std::unique_lock<std::mutex> lock(m_mutex);
if ( m_init ) {
return;
}
checkLog4cxxInitialized();
checkMR4CInitialized();
loadMR4CIfNecessary();
loadBasicConfIfNecessary();
logResult();
m_init=true;
lock.unlock();
}
void checkLog4cxxInitialized() {
// If log4cxx has been initialized correctly, there will be at least one root appender
// Note that init won't happen until the first attempt to log is made
m_defaultInit = Logger::getRootLogger()->getAllAppenders().size()>0;
}
void checkMR4CInitialized() {
m_defaultInitMR4C= LogManager::exists(FRAMEWORK_ROOT);
m_initMR4C = m_defaultInitMR4C;
}
void loadMR4CIfNecessary() {
if ( m_initMR4C ) {
return;
}
if (tryLoadFromEnv()) {
m_initMR4C=true;
return;
}
if (tryLoadFromLocalFile()) {
m_initMR4C=true;
return;
}
if (tryLoadFromInstalled()) {
m_initMR4C=true;
return;
}
}
void loadBasicConfIfNecessary() {
if ( !m_initMR4C && !m_defaultInit ) {
BasicConfigurator::configure();
}
}
void logResult() {
LoggerPtr m_logger = getLoggerHelper("util.MR4CLogging");
if ( m_defaultInit ) {
if ( m_defaultInitMR4C ) {
LOG4CXX_INFO(m_logger, "Log4cxx initialization loaded MR4C logging config");
} else {
if ( m_initMR4C ) {
LOG4CXX_INFO(m_logger, "Added MR4C logging config from file " << m_file);
} else {
LOG4CXX_WARN(m_logger, "Log4cxx initialized, but MR4C logging config not found");
}
}
} else {
if ( m_initMR4C ) {
LOG4CXX_INFO(m_logger, "Loaded MR4C logging config only from file " << m_file);
} else {
LOG4CXX_WARN(m_logger, "No logging config found, defaulted to BasicConfigurator");
}
}
logAppenders();
}
void logAppenders() {
std::map<std::string,std::set<std::string> > fileMap = extractAppenderMap();
std::map<std::string,std::set<std::string> >::const_iterator iter=fileMap.begin();
for ( ; iter!=fileMap.end(); iter++ ) {
logFileAppenders(iter->first, iter->second);
}
}
void logFileAppenders(const std::string& name, const std::set<std::string> files) {
std::set<std::string>::const_iterator iter = files.begin();
LoggerPtr logger = getLoggerHelper("util.MR4CLogging");
for ( ; iter!=files.end(); iter++ ) {
LOG4CXX_INFO(logger, "Logger " << name << " is going to " << *iter);
}
if ( files.empty() ) {
LOG4CXX_WARN(logger, "No file appenders found for logger " << name);
}
}
std::set<std::string> extractLogFiles() {
std::set<std::string> result;
std::map<std::string,std::set<std::string> > fileMap = extractAppenderMap();
std::map<std::string,std::set<std::string> >::const_iterator iter=fileMap.begin();
for ( ; iter!=fileMap.end(); iter++ ) {
std::set<std::string> files = iter->second;
result.insert(files.begin(), files.end());
}
return result;
}
std::map<std::string,std::set<std::string> > extractAppenderMap() {
std::map<std::string,std::set<std::string> > result;
std::vector<LoggerPtr> list = LogManager::getCurrentLoggers();
std::vector<LoggerPtr>::iterator iter = list.begin();
for ( ; iter!=list.end(); iter++ ) {
LoggerPtr logger = *iter;
result[logger->getName()] = extractAppenderFiles(logger);
}
return result;
}
std::set<std::string> extractAppenderFiles(LoggerPtr logger) {
std::set<std::string> result;
std::vector<AppenderPtr> list = logger->getAllAppenders();
std::vector<AppenderPtr>::iterator iter = list.begin();
for ( ; iter!=list.end(); iter++ ) {
AppenderPtr app = *iter;
std::string file = extractAppenderFile(app);
if ( !file.empty() ) {
result.insert(file);
}
}
return result;
}
std::string extractAppenderFile(AppenderPtr app) {
FileAppender* fileAppPtr = dynamic_cast<FileAppender*>(&(*app)); // extracting from a smart pointer here
return fileAppPtr!=NULL ?
fileAppPtr->getFile() :
"";
}
bool tryLoadFromEnv() {
char* path = getenv("MR4C_LOG4CXX_CONFIG");
if ( path==NULL ) {
return false;
}
return tryLoadFromFile(path);
}
bool tryLoadFromLocalFile() {
if (tryLoadFromFile("log4cxx.properties") ) {
return true;
}
return false;
}
bool tryLoadFromInstalled() {
if (tryLoadFromFile("/etc/mr4c/log4cxx.properties") ) {
return true;
}
return false;
}
bool tryLoadFromFile(const char* file) {
if ( !fileExists(file) ) {
return false;
}
FileInputStreamPtr fis = FileInputStreamPtr(new FileInputStream(file));
log4cxx::helpers::Properties props;
props.load(fis);
fis->close();
if ( props.get(PROP)!="true" ) {
return false;
}
if ( m_defaultInit ) {
// get rid of root, don't want it twice
props.setProperty("log4j.rootLogger", "");
}
PropertyConfigurator::configure(props);
m_file = file;
return true;
}
bool fileExists(const std::string& name) {
FILE* file = fopen(name.c_str(), "r");
if ( file==NULL ) {
return false;
} else {
fclose(file);
return true;
}
}
};
LoggerPtr MR4CLogging::getLogger(const std::string& name) {
return MR4CLoggingImpl::instance().getLogger(name);
}
LoggerPtr MR4CLogging::getAlgorithmLogger(const std::string& name) {
return MR4CLoggingImpl::instance().getAlgorithmLogger(name);
}
std::set<std::string> MR4CLogging::extractLogFiles() {
return MR4CLoggingImpl::instance().extractLogFiles();
}
}
| 3,332 |
625 | <gh_stars>100-1000
package java.security;
public interface DomainCombiner {
ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains);
}
| 48 |
917 | package dev.ahamed.mva.sample.view.nested;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import dev.ahamed.mva.sample.R;
import mva2.adapter.MultiViewAdapter;
import mva2.adapter.decorator.Decorator;
public class DividerDecorator extends Decorator {
private Paint dividerPaint = new Paint();
private Rect bounds = new Rect();
DividerDecorator(MultiViewAdapter adapter, Context context) {
super(adapter);
dividerPaint.setColor(ContextCompat.getColor(context, R.color.grey_300));
}
@Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state, int adapterPosition) {
// No-op
}
@Override public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state, View child, int adapterPosition) {
//if(isLast(getPositionType(adapterPosition, parent))) {
// return;
//}
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (null == layoutManager) {
return;
}
canvas.save();
int decoratedWidth = layoutManager.getLeftDecorationWidth(child);
parent.getDecoratedBoundsWithMargins(child, bounds);
canvas.drawRect(decoratedWidth, bounds.bottom - 2, bounds.right, bounds.bottom, dividerPaint);
canvas.restore();
}
}
| 532 |
913 | <filename>library/src/main/java/com/oubowu/slideback/widget/CacheDrawView.java
package com.oubowu.slideback.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.view.View;
/**
* Created by Oubowu on 2016/9/20 0020 11:19.
*/
public class CacheDrawView extends View {
private View mCacheView;
public CacheDrawView(Context context) {
super(context);
}
public void drawCacheView(View cacheView) {
mCacheView = cacheView;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (mCacheView != null) {
// canvas.drawColor(Color.YELLOW);
mCacheView.draw(canvas);
// Log.e("TAG", "绘制上个Activity的内容视图...");
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Log.e("TAG", "CacheDrawView-37行-onDetachedFromWindow(): ");
mCacheView = null;
}
}
| 426 |
1,227 | <reponame>Clusks/alibi-detect
from .aegmm import OutlierAEGMM
from .isolationforest import IForest
from .mahalanobis import Mahalanobis
from .ae import OutlierAE
from .vae import OutlierVAE
from .vaegmm import OutlierVAEGMM
from .prophet import PROPHET_INSTALLED, OutlierProphet
from .seq2seq import OutlierSeq2Seq
from .sr import SpectralResidual
from .llr import LLR
__all__ = [
"OutlierAEGMM",
"IForest",
"Mahalanobis",
"OutlierAE",
"OutlierVAE",
"OutlierVAEGMM",
"OutlierSeq2Seq",
"SpectralResidual",
"LLR"
]
if PROPHET_INSTALLED:
__all__ += ["OutlierProphet"]
| 255 |
499 | <gh_stars>100-1000
import unittest
from SetSimilaritySearch import SearchIndex
class TestSearchIndex(unittest.TestCase):
def test_jaccard(self):
sets = [[1,2,3], [3,4,5], [2,3,4], [5,6,7]]
index = SearchIndex(sets, similarity_func_name="jaccard",
similarity_threshold=0.1)
results = index.query([3,5,4])
correct_results = set([(1, 1.0), (0, 0.2), (2, 0.5), (3, 0.2)])
self.assertEqual(set(results), correct_results)
def test_containment(self):
sets = [[1,2,3], [3,4,5], [2,3,4], [5,6,7]]
# Threshold 0.1
index = SearchIndex(sets, similarity_func_name="containment",
similarity_threshold=0.1)
results = index.query([3,5,4])
correct_results = set([(1, 1.0), (0, 1.0/3.0), (2, 2.0/3.0),
(3, 1.0/3.0)])
self.assertEqual(set(results), correct_results)
# Threshold 0.5
index = SearchIndex(sets, similarity_func_name="containment",
similarity_threshold=0.5)
results = index.query([3,5,4])
correct_results = set([(1, 1.0), (2, 2.0/3.0)])
self.assertEqual(set(results), correct_results)
if __name__ == "__main__":
unittest.main()
| 606 |
1,383 | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
#ifndef CHARCHIVEBINARY_H
#define CHARCHIVEBINARY_H
#include "chrono/serialization/ChArchive.h"
#include "chrono/core/ChLog.h"
namespace chrono {
///
/// This is a class for serializing to binary archives
///
class ChArchiveOutBinary : public ChArchiveOut {
public:
ChArchiveOutBinary( ChStreamOutBinary& mostream) {
ostream = &mostream;
};
virtual ~ChArchiveOutBinary() {};
virtual void out (ChNameValue<bool> bVal) {
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<int> bVal) {
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<double> bVal) {
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<float> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<char> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<unsigned int> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<const char*> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<std::string> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<unsigned long> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<unsigned long long> bVal){
(*ostream) << bVal.value();
}
virtual void out (ChNameValue<ChEnumMapperBase> bVal) {
(*ostream) << bVal.value().GetValueAsInt();
}
virtual void out_array_pre (ChValue& bVal, size_t msize) {
(*ostream) << msize;
}
virtual void out_array_between (ChValue& bVal, size_t msize) {}
virtual void out_array_end (ChValue& bVal, size_t msize) {}
// for custom c++ objects:
virtual void out (ChValue& bVal, bool tracked, size_t obj_ID) {
bVal.CallArchiveOut(*this);
}
virtual void out_ref (ChValue& bVal, bool already_inserted, size_t obj_ID, size_t ext_ID)
{
const char* classname = bVal.GetClassRegisteredName().c_str();
if (!already_inserted) {
// New Object, we have to full serialize it
std::string str(classname);
(*ostream) << str;
bVal.CallArchiveOutConstructor(*this);
bVal.CallArchiveOut(*this);
} else {
if (obj_ID || bVal.IsNull() ) {
// Object already in list. Only store obj_ID as ID
std::string str("oID");
(*ostream) << str; // serialize 'this was already saved' info as "oID" string
(*ostream) << obj_ID; // serialize obj_ID in pointers vector as ID
}
if (ext_ID) {
// Object is external. Only store ref_ID as ID
std::string str("eID");
(*ostream) << str; // serialize info as "eID" string
(*ostream) << ext_ID; // serialize ext_ID in pointers vector as ID
}
}
}
protected:
ChStreamOutBinary* ostream;
};
///
/// This is a class for serializing from binary archives
///
class ChArchiveInBinary : public ChArchiveIn {
public:
ChArchiveInBinary( ChStreamInBinary& mistream) {
istream = &mistream;
};
virtual ~ChArchiveInBinary() {};
virtual void in (ChNameValue<bool> bVal) {
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<int> bVal) {
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<double> bVal) {
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<float> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<char> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<unsigned int> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<std::string> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<unsigned long> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<unsigned long long> bVal){
(*istream) >> bVal.value();
}
virtual void in (ChNameValue<ChEnumMapperBase> bVal) {
int foo;
(*istream) >> foo;
bVal.value().SetValueAsInt(foo);
}
// for wrapping arrays and lists
virtual void in_array_pre (const char* name, size_t& msize) {
(*istream) >> msize;
}
virtual void in_array_between (const char* name) {}
virtual void in_array_end (const char* name) {}
// for custom c++ objects:
virtual void in (ChNameValue<ChFunctorArchiveIn> bVal) {
if (bVal.flags() & NVP_TRACK_OBJECT){
bool already_stored; size_t obj_ID;
PutPointer(bVal.value().GetRawPtr(), already_stored, obj_ID);
}
bVal.value().CallArchiveIn(*this);
}
virtual void* in_ref (ChNameValue<ChFunctorArchiveIn> bVal)
{
void* new_ptr = nullptr;
std::string cls_name;
(*istream) >> cls_name;
if (cls_name == "oID") {
size_t obj_ID = 0;
// Was a shared object: just get the pointer to already-retrieved
(*istream) >> obj_ID;
if (this->internal_id_ptr.find(obj_ID) == this->internal_id_ptr.end())
throw (ChExceptionArchive( "In object '" + std::string(bVal.name()) +"' the reference ID " + std::to_string((int)obj_ID) +" is not a valid number." ));
bVal.value().SetRawPtr(internal_id_ptr[obj_ID]);
}
else if (cls_name == "eID") {
size_t ext_ID = 0;
// Was an external object: just get the pointer to external
(*istream) >> ext_ID;
if (this->external_id_ptr.find(ext_ID) == this->external_id_ptr.end())
throw (ChExceptionArchive( "In object '" + std::string(bVal.name()) +"' the external reference ID " + std::to_string((int)ext_ID) +" cannot be rebuilt." ));
bVal.value().SetRawPtr(external_id_ptr[ext_ID]);
}
else {
// Dynamically create (no class factory will be invoked for non-polymorphic obj):
// call new(), or deserialize constructor params+call new():
bVal.value().CallArchiveInConstructor(*this, cls_name.c_str());
if (bVal.value().GetRawPtr()) {
bool already_stored; size_t obj_ID;
PutPointer(bVal.value().GetRawPtr(), already_stored, obj_ID);
// 3) Deserialize
bVal.value().CallArchiveIn(*this);
} else {
throw(ChExceptionArchive("Archive cannot create object" + cls_name + "\n"));
}
new_ptr = bVal.value().GetRawPtr();
}
return new_ptr;
}
protected:
ChStreamInBinary* istream;
};
} // end namespace chrono
#endif
| 3,607 |
678 | <reponame>bzxy/cydia
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/AirPortAssistant.framework/AirPortAssistant
*/
#import <AirPortAssistant/StepByStepUIViewController.h>
#import <AirPortAssistant/TableViewManagerDelegate.h>
@class UILabel, UIView;
__attribute__((visibility("hidden")))
@interface StepByStepUIViewController_ReplaceChoice : StepByStepUIViewController <TableViewManagerDelegate> {
UIView *tableHeaderContainerView; // 220 = 0xdc
UIView *justTextContainerView; // 224 = 0xe0
UILabel *justTextLabel; // 228 = 0xe4
}
@property(retain, nonatomic) UILabel *justTextLabel; // G=0x18e1d; S=0x18e2d; @synthesize
@property(retain, nonatomic) UIView *justTextContainerView; // G=0x18de9; S=0x18df9; @synthesize
@property(retain, nonatomic) UIView *tableHeaderContainerView; // G=0x18db5; S=0x18dc5; @synthesize
// declared property setter: - (void)setJustTextLabel:(id)label; // 0x18e2d
// declared property getter: - (id)justTextLabel; // 0x18e1d
// declared property setter: - (void)setJustTextContainerView:(id)view; // 0x18df9
// declared property getter: - (id)justTextContainerView; // 0x18de9
// declared property setter: - (void)setTableHeaderContainerView:(id)view; // 0x18dc5
// declared property getter: - (id)tableHeaderContainerView; // 0x18db5
- (void)touchInCellAtIndexPath:(id)indexPath; // 0x18cf9
- (void)viewWillAppear:(BOOL)view; // 0x18c79
- (void)viewDidLoad; // 0x18b8d
- (void)setupTable; // 0x18895
@end
| 561 |
389 | /*
* Copyright 2014 <NAME>, Inc.
*/
package gw.internal.gosu.ir.compiler.bytecode.expression;
import gw.internal.gosu.ir.compiler.bytecode.AbstractBytecodeCompiler;
import gw.internal.gosu.ir.compiler.bytecode.IRBytecodeContext;
import gw.internal.gosu.ir.compiler.bytecode.IRBytecodeCompiler;
import gw.lang.ir.expression.IRCompositeExpression;
import gw.lang.ir.IRElement;
public class IRCompositeExpressionCompiler extends AbstractBytecodeCompiler {
public static void compile( IRCompositeExpression expression, IRBytecodeContext context) {
// Composite expressions can create temp variables, but should never result in something like
// an assignment to a non-temp variable, so it's safe to push and pop scopes during
// their compilation
context.pushScope();
try {
for (IRElement element : expression.getElements()) {
IRBytecodeCompiler.compileIRElement( element, context );
}
} finally {
context.popScope();
}
}
}
| 324 |
341 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from enum import IntEnum
from xdrlib import Packer, Unpacker
from ..__version__ import __issues__
from ..exceptions import ValueError
__all__ = ["ManageDataResultCode"]
class ManageDataResultCode(IntEnum):
"""
XDR Source Code
----------------------------------------------------------------
enum ManageDataResultCode
{
// codes considered as "success" for the operation
MANAGE_DATA_SUCCESS = 0,
// codes considered as "failure" for the operation
MANAGE_DATA_NOT_SUPPORTED_YET =
-1, // The network hasn't moved to this protocol change yet
MANAGE_DATA_NAME_NOT_FOUND =
-2, // Trying to remove a Data Entry that isn't there
MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry
MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string
};
----------------------------------------------------------------
"""
MANAGE_DATA_SUCCESS = 0
MANAGE_DATA_NOT_SUPPORTED_YET = -1
MANAGE_DATA_NAME_NOT_FOUND = -2
MANAGE_DATA_LOW_RESERVE = -3
MANAGE_DATA_INVALID_NAME = -4
def pack(self, packer: Packer) -> None:
packer.pack_int(self.value)
@classmethod
def unpack(cls, unpacker: Unpacker) -> "ManageDataResultCode":
value = unpacker.unpack_int()
return cls(value)
def to_xdr_bytes(self) -> bytes:
packer = Packer()
self.pack(packer)
return packer.get_buffer()
@classmethod
def from_xdr_bytes(cls, xdr: bytes) -> "ManageDataResultCode":
unpacker = Unpacker(xdr)
return cls.unpack(unpacker)
def to_xdr(self) -> str:
xdr_bytes = self.to_xdr_bytes()
return base64.b64encode(xdr_bytes).decode()
@classmethod
def from_xdr(cls, xdr: str) -> "ManageDataResultCode":
xdr_bytes = base64.b64decode(xdr.encode())
return cls.from_xdr_bytes(xdr_bytes)
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please upgrade the SDK or submit an issue here: {__issues__}."
)
| 905 |
446 | package indi.liyi.viewer.dragger;
public final class DragMode {
// 简单拖拽模式
public final static int MODE_SIMPLE = 1;
// 灵巧的拖拽模式
public final static int MODE_AGILE = 2;
}
| 99 |
1,971 | package org.openbot.env;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.json.JSONObject;
import org.openbot.R;
import org.openbot.customview.AutoFitSurfaceGlView;
import org.openbot.customview.WebRTCSurfaceView;
import org.openbot.utils.CameraUtils;
import timber.log.Timber;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class PhoneController {
private static final String TAG = "PhoneController";
private static PhoneController _phoneController;
private ConnectionSelector connectionSelector;
private IVideoServer videoServer;
private View view = null;
public static PhoneController getInstance(Context context) {
if (_phoneController == null) { // Check for the first time
synchronized (PhoneController.class) { // Check for the second time.
// if there is no instance available... create new one
if (_phoneController == null) _phoneController = new PhoneController();
_phoneController.init(context);
}
}
return _phoneController;
}
class DataReceived implements IDataReceived {
@Override
public void dataReceived(String commandStr) {
ControllerToBotEventBus.emitEvent(commandStr);
}
}
private void init(Context context) {
ControllerConfig.getInstance().init(context);
videoServer =
"RTSP".equals(ControllerConfig.getInstance().getVideoServerType())
? new RtspServer()
: new WebRtcServer();
videoServer.init(context);
videoServer.setCanStart(true);
this.connectionSelector = ConnectionSelector.getInstance(context);
connectionSelector.getConnection().setDataCallback(new DataReceived());
android.util.Size resolution =
CameraUtils.getClosestCameraResolution(context, new android.util.Size(640, 360));
videoServer.setResolution(resolution.getWidth(), resolution.getHeight());
handleBotEvents();
createAndSetView(context);
monitorConnection();
}
private void createAndSetView(Context context) {
if (videoServer instanceof WebRtcServer) {
view = new org.openbot.customview.WebRTCSurfaceView(context);
} else if (videoServer instanceof RtspServer) {
view = new org.openbot.customview.AutoFitSurfaceGlView(context);
}
if (view != null) {
addVideoView(view, context);
}
}
private void addVideoView(View videoView, Context context) {
ViewGroup viewGroup = (ViewGroup) ((Activity) context).getWindow().getDecorView();
ViewGroup.LayoutParams layoutParams =
new ViewGroup.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
videoView.setLayoutParams(layoutParams);
videoView.setId(R.id.video_window);
videoView.setAlpha(0f);
viewGroup.addView(videoView, 0); // send to back
if (videoView instanceof WebRTCSurfaceView) {
videoServer.setView((WebRTCSurfaceView) videoView);
} else if (videoView instanceof AutoFitSurfaceGlView) {
videoServer.setView((AutoFitSurfaceGlView) videoView);
}
}
public void connect(Context context) {
ILocalConnection connection = connectionSelector.getConnection();
if (!connection.isConnected()) {
connection.init(context);
connection.connect(context);
} else {
connection.start();
}
}
public void disconnect() {
connectionSelector.getConnection().stop();
}
public void send(JSONObject info) {
connectionSelector.getConnection().sendMessage(info.toString());
}
public boolean isConnected() {
return connectionSelector.getConnection().isConnected();
}
private void handleBotEvents() {
BotToControllerEventBus.subscribe(
this::send, error -> Timber.d("Error occurred in BotToControllerEventBus: %s", error));
}
private void monitorConnection() {
ControllerToBotEventBus.subscribe(
this.getClass().getSimpleName(),
event -> {
switch (event.getString("command")) {
case "CONNECTED":
videoServer.setConnected(true);
break;
case "DISCONNECTED":
videoServer.setConnected(false);
break;
}
},
error -> {
Log.d(null, "Error occurred in monitorConnection: " + error);
},
event ->
event.has("command")
&& ("CONNECTED".equals(event.getString("command"))
|| "DISCONNECTED".equals(event.getString("command"))) // filter everything else
);
}
private PhoneController() {
if (_phoneController != null) {
throw new RuntimeException(
"Use getInstance() method to get the single instance of this class.");
}
}
}
| 1,715 |
348 | {"nom":"Leymen","circ":"3ème circonscription","dpt":"Haut-Rhin","inscrits":622,"abs":357,"votants":265,"blancs":13,"nuls":5,"exp":247,"res":[{"nuance":"LR","nom":"<NAME>","voix":151},{"nuance":"REM","nom":"<NAME>","voix":96}]} | 92 |
576 | #pragma once
#include "riff.h"
#include "structs.h"
#include "soundfont.h"
#include "wave.h"
#include <vector>
namespace Dx8 {
class DlsCollection final {
public:
DlsCollection(Riff &input);
struct RgnRange final {
uint16_t usLow =0;
uint16_t usHigh=0;
};
struct RegionHeader final {
RgnRange RangeKey;
RgnRange RangeVelocity;
uint16_t fusOptions=0;
uint16_t usKeyGroup=0;
};
struct WaveLink final {
uint16_t fusOptions =0;
uint16_t usPhaseGroup=0;
uint32_t ulChannel =0;
uint32_t ulTableIndex=0;
};
struct WaveSample final {
uint32_t cbSize =0;
uint16_t usUnityNote =0;
int16_t sFineTune =0;
int32_t lAttenuation=0;
uint32_t fulOptions =0;
uint32_t cSampleLoops=0;
};
struct WaveSampleLoop final {
uint32_t cbSize =0;
uint32_t ulLoopType =0;
uint32_t ulLoopStart =0;
uint32_t ulLoopLength=0;
};
class Region final {
public:
Region(Riff& c);
RegionHeader head;
WaveLink wlink;
WaveSample waveSample;
std::vector<WaveSampleLoop> loop;
private:
void implRead(Riff &input);
};
struct ConnectionBlock final {
uint16_t usSource=0;
uint16_t usControl=0;
uint16_t usDestination=0;
uint16_t usTransform=0;
int32_t lScale=0;
};
class Articulator final {
public:
Articulator(Riff& c);
std::vector<ConnectionBlock> connectionBlocks;
};
struct MidiLocale final {
uint32_t ulBank =0;
uint32_t ulInstrument=0;
};
struct InstrumentHeader final {
uint32_t cRegions=0;
MidiLocale Locale;
};
class Instrument final {
public:
Instrument(Riff& c);
Info info;
InstrumentHeader header;
std::vector<Region> regions;
std::vector<Articulator> articulators;
private:
void implRead(Riff &input);
};
uint64_t version=0;
GUID dlid;
std::vector<Instrument> instrument;
void dbgDump() const;
SoundFont toSoundfont(uint32_t dwPatch) const;
void save(std::ostream& fout) const;
const Wave* findWave(uint8_t note) const;
private:
void implRead(Riff &input);
std::vector<Wave> wave;
mutable std::shared_ptr<SoundFont::Data> shData; //FIXME: mutable
};
}
| 1,322 |
1,436 | <filename>NIMKit/NIMKit/Classes/Sections/Team/View/NIMTeamCardHeaderView.h<gh_stars>1000+
//
// NIMTeamCardHeaderView.h
// NIMKit
//
// Created by Netease on 2019/6/10.
// Copyright © 2019 NetEase. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <NIMSDK/NIMSDK.h>
NS_ASSUME_NONNULL_BEGIN
@protocol NIMTeamCardHeaderViewDelegate <NSObject>
- (void)onTouchAvatar:(id)sender;
@end
@interface NIMTeamCardHeaderView : UIView
@property (nonatomic, weak) id<NIMTeamCardHeaderViewDelegate> delegate;
@property (nonatomic, strong) NIMTeam *team;
@end
NS_ASSUME_NONNULL_END
| 238 |
575 | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from page_sets.rendering import rendering_shared_state as shared_state
from page_sets.rendering import rendering_story
from page_sets.rendering import story_tags
from page_sets.system_health import platforms
from telemetry import story
from py_utils import discover
class RenderingStorySet(story.StorySet):
"""Stories related to rendering."""
def __init__(self, platform, scroll_forever=False):
super(RenderingStorySet, self).__init__(
archive_data_file=('../data/rendering_%s.json' % platform),
cloud_storage_bucket=story.PARTNER_BUCKET)
assert platform in platforms.ALL_PLATFORMS
self._platform = platform
if platform == platforms.MOBILE:
shared_page_state_class = shared_state.MobileRenderingSharedState
elif platform == platforms.DESKTOP:
shared_page_state_class = shared_state.DesktopRenderingSharedState
else:
shared_page_state_class = shared_state.RenderingSharedState
self.scroll_forever = scroll_forever
# For pinch zoom page sets, set default to desktop scale factor
self.target_scale_factor = 4.0
for story_class in _IterAllRenderingStoryClasses():
if (story_class.ABSTRACT_STORY or
platform not in story_class.SUPPORTED_PLATFORMS):
continue
required_args = []
name_suffix = ''
if (story_class.TAGS and
story_tags.USE_FAKE_CAMERA_DEVICE in story_class.TAGS):
required_args += [
# Use a fake camera showing a placeholder video.
'--use-fake-device-for-media-stream',
# Don't prompt for camera access. (Conveniently,
# this takes precedent over --deny-permission-prompts.)
'--use-fake-ui-for-media-stream',
]
if story_class.TAGS and story_tags.BACKDROP_FILTER in story_class.TAGS:
# Experimental web platform features must be enabled in order for the
# 'backdrop-filter' CSS property to work.
required_args.append('--enable-experimental-web-platform-features')
# TODO(crbug.com/968125): We must run without out-of-process rasterization
# until that branch is implemented for YUV decoding.
if (story_class.TAGS and
story_tags.IMAGE_DECODING in story_class.TAGS and
story_tags.GPU_RASTERIZATION in story_class.TAGS):
required_args += ['--enable-gpu-rasterization']
# Run RGB decoding with GPU rasterization (to be most comparable to YUV)
self.AddStory(story_class(
page_set=self,
extra_browser_args=required_args +
['--disable-yuv-image-decoding'],
shared_page_state_class=shared_page_state_class,
name_suffix='_rgb_and_gpu_rasterization'))
# Also run YUV decoding story with GPU rasterization.
name_suffix = '_yuv_and_gpu_rasterization'
self.AddStory(story_class(
page_set=self,
extra_browser_args=required_args,
shared_page_state_class=shared_page_state_class,
name_suffix=name_suffix))
def GetAbridgedStorySetTagFilter(self):
if self._platform == platforms.DESKTOP:
if os.name == 'nt':
return 'representative_win_desktop'
else:
# There is no specific tag for linux, cros, etc,
# so just use mac's.
return 'representative_mac_desktop'
elif self._platform == platforms.MOBILE:
return 'representative_mobile'
raise RuntimeError('Platform {} is not in the list of expected platforms.')
class DesktopRenderingStorySet(RenderingStorySet):
"""Desktop stories related to rendering.
Note: This story set is only intended to be used for recording stories via
tools/perf/record_wpr. If you would like to use it in a benchmark, please use
the generic RenderingStorySet class instead (you'll need to override the
CreateStorySet method of your benchmark).
"""
def __init__(self):
super(DesktopRenderingStorySet, self).__init__(platform='desktop')
def _IterAllRenderingStoryClasses():
start_dir = os.path.dirname(os.path.abspath(__file__))
# Sort the classes by their names so that their order is stable and
# deterministic.
for _, cls in sorted(discover.DiscoverClasses(
start_dir=start_dir,
top_level_dir=os.path.dirname(start_dir),
base_class=rendering_story.RenderingStory).iteritems()):
yield cls
| 1,695 |
697 | <filename>leyou-comments/leyou-comments-service/src/main/java/com/leyou/comments/client/OrderClient.java
package com.leyou.comments.client;
import com.leyou.order.api.OrderApi;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @Author: 98050
* @Time: 2018-11-12 15:19
* @Feature: 订单接口
*/
@FeignClient(value = "order-service")
public interface OrderClient extends OrderApi {
}
| 144 |
1,165 | <reponame>Diffblue-benchmarks/pacbot
/*******************************************************************************
* Copyright 2018 T Mobile, 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. 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.tmobile.pacman.api.statistics.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;
import com.tmobile.pacman.api.statistics.repository.StatisticsRepositoryImpl;
import feign.RequestInterceptor;
import feign.RequestTemplate;
/**
* Sample SpringSecurty Configuration.
* HTTP Security is overridden to permit AL.
*
* @author NidhishKrishnan
*
*/
@Order(1)
@Configuration("WebSecurityConfig")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringSecurityConfig.class);
@Value("${swagger.auth.whitelist:}")
private String[] AUTH_WHITELIST;
/**
* Constructor disables the default security settings
**/
public SpringSecurityConfig() {
super(true);
}
/**
* Allow url encoded slash http firewall.
*
* @return the http firewall
*/
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
LOGGER.info("SecurityContextHolder.getContext() ============== {}",SecurityContextHolder.getContext());
LOGGER.info("SecurityContextHolder.getContext() =============="+SecurityContextHolder.getContext());
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
}
};
}
@Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
web.ignoring().antMatchers(AUTH_WHITELIST);
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous().and().antMatcher("/user").authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll().
antMatchers(AUTH_WHITELIST).permitAll().
anyRequest().authenticated()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
| 1,466 |
3,084 | <reponame>ixjf/Windows-driver-samples<filename>network/trans/WFPSampler/syslib/HelperFunctions_WorkItems.h
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014 Microsoft Corporation. All Rights Reserved.
//
// Module Name:
// HelperFunctions_WorkItems.h
//
// Abstract:
// This module contains prototypes for kernel helper functions that assist with IO_WORKITEM
// routines.
//
// Author:
// <NAME> (DHarper)
//
// Revision History:
//
// [ Month ][Day] [Year] - [Revision]-[ Comments ]
// May 01, 2010 - 1.0 - Creation
// December 13, 2013 - 1.1 - Add support for pending at
// FWPM_LAYER_ALE_ENDPOINT_CLOSURE.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef HELPERFUNCTIONS_WORKITEMS_H
#define HELPERFUNCTIONS_WORKITEMS_H
typedef struct WORKITEM_DATA_
{
PIO_WORKITEM pIOWorkItem;
union
{
CLASSIFY_DATA* pClassifyData;
NOTIFY_DATA* pNotifyData;
};
union
{
INJECTION_DATA* pInjectionData;
REDIRECT_DATA* pRedirectData;
PEND_DATA* pPendData;
};
VOID* pContext;
}WORKITEM_DATA, *PWORKITEM_DATA;
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPurge(_Inout_ WORKITEM_DATA* pWorkItemData);
_At_(*ppWorkItemData, _Pre_ _Notnull_)
_At_(*ppWorkItemData, _Post_ _Null_ __drv_freesMem(Pool))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Success_(*ppWorkItemData == 0)
inline VOID KrnlHlprWorkItemDataDestroy(_Inout_ WORKITEM_DATA** ppWorkItemData);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPopulate(_Inout_ WORKITEM_DATA* pWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_opt_ INJECTION_DATA* pInjectionData = 0,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPopulate(_Inout_ WORKITEM_DATA* pWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ PEND_DATA* pPendData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPopulate(_Inout_ WORKITEM_DATA* pWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ REDIRECT_DATA* pRedirectData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID** pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPopulate(_Inout_ WORKITEM_DATA* pWorkItemData,
_In_ NOTIFY_DATA* pNotifyData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
inline VOID KrnlHlprWorkItemDataPopulate(_Inout_ WORKITEM_DATA* pWorkItemData,
_In_ PEND_DATA* pPendData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_At_(*ppWorkItemData, _Pre_ _Null_)
_When_(return != STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Null_))
_When_(return == STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Notnull_ __drv_allocatesMem(Pool)))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemDataCreate(_Outptr_ WORKITEM_DATA** ppWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_opt_ INJECTION_DATA* pInjectionData = 0,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_At_(*ppWorkItemData, _Pre_ _Null_)
_When_(return != STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Null_))
_When_(return == STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Notnull_ __drv_allocatesMem(Pool)))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemDataCreate(_Outptr_ WORKITEM_DATA** ppWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ PEND_DATA* pPendData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_At_(*ppWorkItemData, _Pre_ _Null_)
_When_(return != STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Null_))
_When_(return == STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Notnull_ __drv_allocatesMem(Pool)))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemDataCreate(_Outptr_ WORKITEM_DATA** ppWorkItemData,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ REDIRECT_DATA* pRedirectData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_At_(*ppWorkItemData, _Pre_ _Null_)
_When_(return != STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Null_))
_When_(return == STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Notnull_ __drv_allocatesMem(Pool)))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemDataCreate(_Outptr_ WORKITEM_DATA** ppWorkItemData,
_In_ NOTIFY_DATA* pNotifyData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_At_(*ppWorkItemData, _Pre_ _Null_)
_When_(return != STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Null_))
_When_(return == STATUS_SUCCESS, _At_(*ppWorkItemData, _Post_ _Notnull_ __drv_allocatesMem(Pool)))
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemDataCreate(_Outptr_ WORKITEM_DATA** ppWorkItemData,
_In_ PEND_DATA* pPendData,
_In_opt_ PIO_WORKITEM pIOWorkItem = 0,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn,
_In_ CLASSIFY_DATA* pClassifyData,
_In_opt_ INJECTION_DATA* pInjectionData = 0,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ PEND_DATA* pPendData,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn,
_In_ CLASSIFY_DATA* pClassifyData,
_In_ REDIRECT_DATA* pRedirectData,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn,
_In_ NOTIFY_DATA* pNotifyData,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Check_return_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemQueue(_In_ PDEVICE_OBJECT pWDMDevice,
_In_ IO_WORKITEM_ROUTINE* pWorkItemFn,
_In_ PEND_DATA* pPendData,
_In_opt_ VOID* pContext = 0);
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_same_
_Success_(return == STATUS_SUCCESS)
NTSTATUS KrnlHlprWorkItemSleep(_In_ UINT32 numMS);
#endif /// HELPERFUNCTIONS_WORKITEMS_H
| 5,602 |
1,184 | #include <stdio.h>
int gcd_division(int a, int b){
while( b != 0 ){
int tmp = a;
a = b;
b = tmp % b;
}
return a;
}
int gcd_substraction(int a, int b){
while( a != b){
if( a > b ){
a = a -b;
}else{
b = b -a;
}
}
return a;
}
int gcd_recursive(int a, int b){
return (b == 0) ? a : gcd_recursive(b, a % b);
}
int main(){
/*
* Some kind of test :)
* 1 = Pass
* 0 = Failure
*/
// GCD with division
printf("%d", gcd_division(210, 45) == 15);
printf("%d", gcd_division(0, 0) == 0);
printf("%d", gcd_division(20, 77) == 1);
// GCD with substraction
printf("%d", gcd_substraction(210, 45) == 15);
printf("%d", gcd_substraction(0, 0) == 0);
printf("%d", gcd_substraction(20, 77) == 1);
// GCD with recursive
printf("%d", gcd_recursive(210, 45) == 15);
printf("%d", gcd_recursive(0, 0) == 0);
printf("%d", gcd_recursive(20, 77) == 1);
return 0;
}
| 538 |
13,885 | <filename>third_party/astcenc/include/astcenc.h<gh_stars>1000+
// -------------------------------------------------------------------------------------------------
// This file declares the minimum amount of constants, enums, structs, and functions that are needed
// when interfacing with astcenc, which has no public-facing header files. To see how to use this
// interface, see astc_toplevel.cpp
// -------------------------------------------------------------------------------------------------
#pragma once
#include <stdint.h>
#define MAX_TEXELS_PER_BLOCK 216
#define PARTITION_BITS 10
#define PARTITION_COUNT (1 << PARTITION_BITS)
enum astc_decode_mode {
DECODE_LDR_SRGB,
DECODE_LDR,
DECODE_HDR
};
struct astc_codec_image {
uint8_t*** imagedata8;
uint16_t*** imagedata16;
int xsize;
int ysize;
int zsize;
int padding;
};
struct error_weighting_params {
float rgb_power;
float rgb_base_weight;
float rgb_mean_weight;
float rgb_stdev_weight;
float alpha_power;
float alpha_base_weight;
float alpha_mean_weight;
float alpha_stdev_weight;
float rgb_mean_and_stdev_mixing;
int mean_stdev_radius;
int enable_rgb_scale_with_alpha;
int alpha_radius;
int ra_normal_angular_scale;
float block_artifact_suppression;
float rgba_weights[4];
float block_artifact_suppression_expanded[MAX_TEXELS_PER_BLOCK];
int partition_search_limit;
float block_mode_cutoff;
float texel_avg_error_limit;
float partition_1_to_2_limit;
float lowest_correlation_cutoff;
int max_refinement_iters;
};
struct swizzlepattern {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
typedef uint16_t sf16;
typedef uint32_t sf32;
enum roundmode {
SF_UP = 0,
SF_DOWN = 1,
SF_TOZERO = 2,
SF_NEARESTEVEN = 3,
SF_NEARESTAWAY = 4
};
extern void encode_astc_image(
const astc_codec_image* input_image,
astc_codec_image* output_image,
int xdim,
int ydim,
int zdim,
const error_weighting_params* ewp,
astc_decode_mode decode_mode,
swizzlepattern swz_encode,
swizzlepattern swz_decode,
uint8_t* buffer,
int pack_and_unpack,
int threadcount);
extern void expand_block_artifact_suppression(
int xdim,
int ydim,
int zdim,
error_weighting_params* ewp);
extern void find_closest_blockdim_2d(
float target_bitrate,
int *x,
int *y,
int consider_illegal);
extern void find_closest_blockdim_3d(
float target_bitrate,
int *x,
int *y,
int *z,
int consider_illegal);
extern void destroy_image(astc_codec_image* img);
extern astc_codec_image* allocate_image(int bitness, int xsize, int ysize, int zsize, int padding);
extern void test_inappropriate_extended_precision();
extern void prepare_angular_tables();
extern void build_quantization_mode_table();
extern "C" {
sf16 float_to_sf16(float, roundmode);
}
| 1,152 |
857 | # Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
def prefix(prefix_str):
def wrapper(function):
function.prefix = prefix_str
return function
return wrapper
def api_v0(path):
return 'http://localhost:8080/api/v0/%s' % path | 117 |
763 | <reponame>zabrewer/batfish
package org.batfish.question.referencedstructures;
import com.google.auto.service.AutoService;
import org.batfish.common.Answerer;
import org.batfish.common.plugin.IBatfish;
import org.batfish.common.plugin.Plugin;
import org.batfish.datamodel.questions.NodesSpecifier;
import org.batfish.datamodel.questions.Question;
import org.batfish.question.QuestionPlugin;
/** Plugin for answer {@link ReferencedStructuresQuestion}. */
@AutoService(Plugin.class)
public class ReferencedStructuresQuestionPlugin extends QuestionPlugin {
@Override
protected Answerer createAnswerer(Question question, IBatfish batfish) {
return new ReferencedStructuresAnswerer(question, batfish);
}
@Override
protected Question createQuestion() {
return new ReferencedStructuresQuestion(".*", NodesSpecifier.ALL, ".*");
}
}
| 263 |
463 | <gh_stars>100-1000
package org.hive2hive.core.events.framework.interfaces;
import net.engio.mbassy.listener.Handler;
import org.hive2hive.core.events.framework.interfaces.file.IFileAddEvent;
import org.hive2hive.core.events.framework.interfaces.file.IFileDeleteEvent;
import org.hive2hive.core.events.framework.interfaces.file.IFileMoveEvent;
import org.hive2hive.core.events.framework.interfaces.file.IFileShareEvent;
import org.hive2hive.core.events.framework.interfaces.file.IFileUpdateEvent;
public interface IFileEventListener {
@Handler
void onFileAdd(IFileAddEvent fileEvent);
@Handler
void onFileUpdate(IFileUpdateEvent fileEvent);
@Handler
void onFileDelete(IFileDeleteEvent fileEvent);
@Handler
void onFileMove(IFileMoveEvent fileEvent);
@Handler
void onFileShare(IFileShareEvent fileEvent);
}
| 276 |
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_BLOCKED_CONTENT_CHROME_POPUP_NAVIGATION_DELEGATE_H_
#define CHROME_BROWSER_UI_BLOCKED_CONTENT_CHROME_POPUP_NAVIGATION_DELEGATE_H_
#include "chrome/browser/ui/browser_navigator_params.h"
#include "components/blocked_content/popup_navigation_delegate.h"
class ChromePopupNavigationDelegate
: public blocked_content::PopupNavigationDelegate {
public:
explicit ChromePopupNavigationDelegate(NavigateParams params);
// blocked_content::PopupNavigationDelegate:
content::RenderFrameHost* GetOpener() override;
bool GetOriginalUserGesture() override;
const GURL& GetURL() override;
NavigateResult NavigateWithGesture(
const blink::mojom::WindowFeatures& window_features,
base::Optional<WindowOpenDisposition> updated_disposition) override;
void OnPopupBlocked(content::WebContents* web_contents,
int total_popups_blocked_on_page) override;
NavigateParams* nav_params() { return ¶ms_; }
private:
NavigateParams params_;
bool original_user_gesture_;
};
#endif // CHROME_BROWSER_UI_BLOCKED_CONTENT_CHROME_POPUP_NAVIGATION_DELEGATE_H_
| 455 |
773 | package org.infernus.idea.checkstyle.csapi;
/**
* Objects which implement this interface are keepers of objects internal to the Checkstyle tool, so from within the
* normal plugin code we cannot know what they are. They are to be used from within the 'csaccess' source set only.
* In this way, we can <em>store</em> objects from the Checkstyle tool itself in other parts of the plugin, although we
* cannot <em>use</em> these objects.
* <p>It is important to make sure that these objects do not outlive the classloader that loaded them (at least not by
* much). When the Checkstyle version is changed in the configuration, all objects which implement this interface
* must be discarded. The new classloader with the new Checkstyle version would not be able to use them and
* {@link org.infernus.idea.checkstyle.exception.CheckstyleVersionMixException CheckstyleVersionMixException}s would
* result.</p>
*/
public interface CheckstyleInternalObject {
// tagging interface
}
| 247 |
3,372 | /*
* 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.codeguruprofiler.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* The structure representing the getProfileRequest.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetProfile" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the default .
* </p>
*
* <pre>
* <code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
* </pre>
*/
private String accept;
/**
* <p>
* The end time of the requested profile. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or <code>startTime</code>,
* but not both.
* </p>
*/
private java.util.Date endTime;
/**
* <p>
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is set to 2,
* then the aggregated profile contains representations of methods <code>A</code> and <code>B</code>.
* </p>
*/
private Integer maxDepth;
/**
* <p>
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned aggregated
* profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>.
* </p>
*
* <pre>
* <code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
* </pre>
*/
private String period;
/**
* <p>
* The name of the profiling group to get.
* </p>
*/
private String profilingGroupName;
/**
* <p>
* The start time of the profile to get. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
*
* <pre>
* <code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
* </pre>
*/
private java.util.Date startTime;
/**
* <p>
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the default .
* </p>
*
* <pre>
* <code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
* </pre>
*
* @param accept
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the
* default . </p>
*
* <pre><code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
*/
public void setAccept(String accept) {
this.accept = accept;
}
/**
* <p>
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the default .
* </p>
*
* <pre>
* <code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
* </pre>
*
* @return The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the
* default . </p>
*
* <pre><code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
*/
public String getAccept() {
return this.accept;
}
/**
* <p>
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the default .
* </p>
*
* <pre>
* <code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
* </pre>
*
* @param accept
* The format of the returned profiling data. The format maps to the <code>Accept</code> and
* <code>Content-Type</code> headers of the HTTP request. You can specify one of the following: or the
* default . </p>
*
* <pre>
* <code> <ul> <li> <p> <code>application/json</code> — standard JSON format </p> </li> <li> <p> <code>application/x-amzn-ion</code> — the Amazon Ion data format. For more information, see <a href="http://amzn.github.io/ion-docs/">Amazon Ion</a>. </p> </li> </ul> </code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withAccept(String accept) {
setAccept(accept);
return this;
}
/**
* <p>
* The end time of the requested profile. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or <code>startTime</code>,
* but not both.
* </p>
*
* @param endTime
* The end time of the requested profile. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or
* <code>startTime</code>, but not both.
*/
public void setEndTime(java.util.Date endTime) {
this.endTime = endTime;
}
/**
* <p>
* The end time of the requested profile. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or <code>startTime</code>,
* but not both.
* </p>
*
* @return The end time of the requested profile. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or
* <code>startTime</code>, but not both.
*/
public java.util.Date getEndTime() {
return this.endTime;
}
/**
* <p>
* The end time of the requested profile. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or <code>startTime</code>,
* but not both.
* </p>
*
* @param endTime
* The end time of the requested profile. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. </p>
* <p>
* If you specify <code>endTime</code>, then you must also specify <code>period</code> or
* <code>startTime</code>, but not both.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withEndTime(java.util.Date endTime) {
setEndTime(endTime);
return this;
}
/**
* <p>
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is set to 2,
* then the aggregated profile contains representations of methods <code>A</code> and <code>B</code>.
* </p>
*
* @param maxDepth
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is
* set to 2, then the aggregated profile contains representations of methods <code>A</code> and
* <code>B</code>.
*/
public void setMaxDepth(Integer maxDepth) {
this.maxDepth = maxDepth;
}
/**
* <p>
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is set to 2,
* then the aggregated profile contains representations of methods <code>A</code> and <code>B</code>.
* </p>
*
* @return The maximum depth of the stacks in the code that is represented in the aggregated profile. For example,
* if CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is
* set to 2, then the aggregated profile contains representations of methods <code>A</code> and
* <code>B</code>.
*/
public Integer getMaxDepth() {
return this.maxDepth;
}
/**
* <p>
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is set to 2,
* then the aggregated profile contains representations of methods <code>A</code> and <code>B</code>.
* </p>
*
* @param maxDepth
* The maximum depth of the stacks in the code that is represented in the aggregated profile. For example, if
* CodeGuru Profiler finds a method <code>A</code>, which calls method <code>B</code>, which calls method
* <code>C</code>, which calls method <code>D</code>, then the depth is 4. If the <code>maxDepth</code> is
* set to 2, then the aggregated profile contains representations of methods <code>A</code> and
* <code>B</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withMaxDepth(Integer maxDepth) {
setMaxDepth(maxDepth);
return this;
}
/**
* <p>
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned aggregated
* profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>.
* </p>
*
* <pre>
* <code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
* </pre>
*
* @param period
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned
* aggregated profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>. </p>
*
* <pre><code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
*/
public void setPeriod(String period) {
this.period = period;
}
/**
* <p>
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned aggregated
* profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>.
* </p>
*
* <pre>
* <code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
* </pre>
*
* @return Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned
* aggregated profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>. </p>
*
* <pre><code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
*/
public String getPeriod() {
return this.period;
}
/**
* <p>
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned aggregated
* profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>.
* </p>
*
* <pre>
* <code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
* </pre>
*
* @param period
* Used with <code>startTime</code> or <code>endTime</code> to specify the time range for the returned
* aggregated profile. Specify using the ISO 8601 format. For example, <code>P1DT1H1M1S</code>. </p>
*
* <pre>
* <code> <p> To get the latest aggregated profile, specify only <code>period</code>. </p> </code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withPeriod(String period) {
setPeriod(period);
return this;
}
/**
* <p>
* The name of the profiling group to get.
* </p>
*
* @param profilingGroupName
* The name of the profiling group to get.
*/
public void setProfilingGroupName(String profilingGroupName) {
this.profilingGroupName = profilingGroupName;
}
/**
* <p>
* The name of the profiling group to get.
* </p>
*
* @return The name of the profiling group to get.
*/
public String getProfilingGroupName() {
return this.profilingGroupName;
}
/**
* <p>
* The name of the profiling group to get.
* </p>
*
* @param profilingGroupName
* The name of the profiling group to get.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withProfilingGroupName(String profilingGroupName) {
setProfilingGroupName(profilingGroupName);
return this;
}
/**
* <p>
* The start time of the profile to get. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
*
* <pre>
* <code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
* </pre>
*
* @param startTime
* The start time of the profile to get. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.</p>
*
* <pre><code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
*/
public void setStartTime(java.util.Date startTime) {
this.startTime = startTime;
}
/**
* <p>
* The start time of the profile to get. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
*
* <pre>
* <code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
* </pre>
*
* @return The start time of the profile to get. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.</p>
*
* <pre><code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
*/
public java.util.Date getStartTime() {
return this.startTime;
}
/**
* <p>
* The start time of the profile to get. Specify using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z
* represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
* </p>
*
* <pre>
* <code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
* </pre>
*
* @param startTime
* The start time of the profile to get. Specify using the ISO 8601 format. For example,
* 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.</p>
*
* <pre>
* <code> <p> If you specify <code>startTime</code>, then you must also specify <code>period</code> or <code>endTime</code>, but not both. </p> </code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetProfileRequest withStartTime(java.util.Date startTime) {
setStartTime(startTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAccept() != null)
sb.append("Accept: ").append(getAccept()).append(",");
if (getEndTime() != null)
sb.append("EndTime: ").append(getEndTime()).append(",");
if (getMaxDepth() != null)
sb.append("MaxDepth: ").append(getMaxDepth()).append(",");
if (getPeriod() != null)
sb.append("Period: ").append(getPeriod()).append(",");
if (getProfilingGroupName() != null)
sb.append("ProfilingGroupName: ").append(getProfilingGroupName()).append(",");
if (getStartTime() != null)
sb.append("StartTime: ").append(getStartTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetProfileRequest == false)
return false;
GetProfileRequest other = (GetProfileRequest) obj;
if (other.getAccept() == null ^ this.getAccept() == null)
return false;
if (other.getAccept() != null && other.getAccept().equals(this.getAccept()) == false)
return false;
if (other.getEndTime() == null ^ this.getEndTime() == null)
return false;
if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false)
return false;
if (other.getMaxDepth() == null ^ this.getMaxDepth() == null)
return false;
if (other.getMaxDepth() != null && other.getMaxDepth().equals(this.getMaxDepth()) == false)
return false;
if (other.getPeriod() == null ^ this.getPeriod() == null)
return false;
if (other.getPeriod() != null && other.getPeriod().equals(this.getPeriod()) == false)
return false;
if (other.getProfilingGroupName() == null ^ this.getProfilingGroupName() == null)
return false;
if (other.getProfilingGroupName() != null && other.getProfilingGroupName().equals(this.getProfilingGroupName()) == false)
return false;
if (other.getStartTime() == null ^ this.getStartTime() == null)
return false;
if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAccept() == null) ? 0 : getAccept().hashCode());
hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode());
hashCode = prime * hashCode + ((getMaxDepth() == null) ? 0 : getMaxDepth().hashCode());
hashCode = prime * hashCode + ((getPeriod() == null) ? 0 : getPeriod().hashCode());
hashCode = prime * hashCode + ((getProfilingGroupName() == null) ? 0 : getProfilingGroupName().hashCode());
hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
return hashCode;
}
@Override
public GetProfileRequest clone() {
return (GetProfileRequest) super.clone();
}
}
| 10,152 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "SliderPage.h"
#include <Gallery/ui_SliderPage.h>
#include <AzQtComponents/Components/Widgets/Slider.h>
SliderPage::SliderPage(QWidget* parent)
: QWidget(parent)
, ui(new Ui::SliderPage)
{
ui->setupUi(this);
ui->percentage->setToolTipFormatting("Opacity ", "%");
ui->percentage->setRange(0, 100);
AzQtComponents::Slider::applyMidPointStyle(ui->midPointSliderDisabled);
AzQtComponents::Slider::applyMidPointStyle(ui->midPointSliderEnabled);
AzQtComponents::Slider::applyMidPointStyle(ui->verticalMidPointSliderEnabled);
AzQtComponents::Slider::applyMidPointStyle(ui->verticalMidPointSliderDisabled);
AzQtComponents::Slider::applyMidPointStyle(ui->doubleMidPointSliderDisabled);
AzQtComponents::Slider::applyMidPointStyle(ui->doubleMidPointSliderEnabled);
AzQtComponents::Slider::applyMidPointStyle(ui->doubleVerticalMidPointSliderEnabled);
AzQtComponents::Slider::applyMidPointStyle(ui->doubleVerticalMidPointSliderDisabled);
{
ui->sliderEnabled->setValue(20);
ui->sliderDisabled->setValue(40);
ui->verticalSliderEnabled->setValue(20);
ui->verticalSliderDisabled->setValue(0);
ui->doubleSliderEnabled->setRange(0, 10);
ui->doubleSliderEnabled->setValue(6.0);
ui->doubleSliderDisabled->setValue(0);
}
{
int min = -10;
int max = 10;
ui->midPointSliderDisabled->setRange(min, max);
ui->midPointSliderDisabled->setValue(5);
ui->midPointSliderEnabled->setRange(min, max);
ui->midPointSliderEnabled->setValue(2);
ui->verticalMidPointSliderEnabled->setRange(min, max);
ui->verticalMidPointSliderEnabled->setValue(-2);
ui->verticalMidPointSliderDisabled->setRange(min, max);
ui->verticalMidPointSliderDisabled->setValue(-5);
}
{
int min = -20;
int max = 20;
ui->doubleMidPointSliderDisabled->setRange(min, max);
ui->doubleMidPointSliderDisabled->setValue(10.0);
ui->doubleMidPointSliderEnabled->setRange(min, max);
ui->doubleMidPointSliderEnabled->setValue(4);
ui->doubleVerticalMidPointSliderEnabled->setRange(min, max);
ui->doubleVerticalMidPointSliderEnabled->setValue(-4.0);
ui->doubleVerticalMidPointSliderDisabled->setRange(min, max);
ui->doubleVerticalMidPointSliderDisabled->setValue(-10.0);
}
{
double min = 0.0;
double max = 1.0;
double value = 0.5;
const auto curveMidpointSliders =
{
ui->curveMidpoint25,
ui->curveMidpoint5,
ui->curveMidpoint75,
ui->verticalcurveMidpoint25,
ui->verticalcurveMidpoint5,
ui->verticalcurveMidpoint75
};
for (auto slider : curveMidpointSliders)
{
slider->setRange(min, max);
slider->setValue(value);
AzQtComponents::Slider::applyMidPointStyle(slider);
}
ui->curveMidpoint25->setCurveMidpoint(0.25);
ui->verticalcurveMidpoint25->setCurveMidpoint(0.25);
ui->curveMidpoint75->setCurveMidpoint(0.75);
ui->verticalcurveMidpoint75->setCurveMidpoint(0.75);
}
QString exampleText = R"(
A Slider is a wrapper around a QSlider.<br/>
There are two variants: SliderInt and SliderDouble, for working with signed integers and doubles, respectively.<br/>
They add tooltip functionality, as well as conversion to the proper data types (int and double).
<br/>
<pre>
#include <AzQtComponents/Components/Widgets/Slider.h>
#include <QDebug>
// Here's an example that creates a slider and sets the hover/tooltip indicator to display as a percentage
SliderInt* sliderInt = new SliderInt();
sliderInt->setRange(0, 100);
sliderInt->setToolTipFormatting("", "%");
// Assuming you've created a slider already (either in code or via .ui file), give it the mid point style like this:
Slider::applyMidPointStyle(sliderInt);
// Disable it like this:
sliderInt->setEnabled(false);
// Here's an example of creating a SliderDouble and setting it up:
SliderDouble* sliderDouble = new SliderDouble();
double min = -10.0;
double max = 10.0;
int numSteps = 21;
sliderDouble->setRange(min, max, numSteps);
sliderDouble->setValue(0.0);
// Listen for changes; same format for SliderInt as SliderDouble
connect(sliderDouble, &SliderDouble::valueChanged, sliderDouble, [sliderDouble](double newValue){
qDebug() << "Slider value changed to " << newValue;
});
</pre>
)";
ui->exampleText->setHtml(exampleText);
}
SliderPage::~SliderPage()
{
}
#include <Gallery/SliderPage.moc> | 2,033 |
1,657 | <gh_stars>1000+
"""
An example of using MultiBlockSlice to interleave frames in a virtual dataset.
"""
import h5py
# These files were written round-robin in blocks of 1000 frames from a single source
# 1.h5 has 0-999, 4000-4999, ...; 2.h4 has 1000-1999, 5000-5999, ...; etc
# The frames from each block are contiguous within each file
# e.g. 1.h5 = [..., 998, 999, 4000, 4001, ... ]
files = ["1.h5", "2.h5", "3.h5", "4.h5"]
dataset_name = "data"
dtype = "float"
source_shape = (25000, 256, 512)
target_shape = (100000, 256, 512)
block_size = 1000
v_layout = h5py.VirtualLayout(shape=target_shape, dtype=dtype)
for file_idx, file_path in enumerate(files):
v_source = h5py.VirtualSource(
file_path, name=dataset_name, shape=source_shape, dtype=dtype
)
dataset_frames = v_source.shape[0]
# A single raw file maps to every len(files)th block of frames in the VDS
start = file_idx * block_size # 0, 1000, 2000, 3000
stride = len(files) * block_size # 4000
count = dataset_frames // block_size # 25
block = block_size # 1000
# MultiBlockSlice for frame dimension and full extent for height and width
v_layout[h5py.MultiBlockSlice(start, stride, count, block), :, :] = v_source
with h5py.File("interleave_vds.h5", "w", libver="latest") as f:
f.create_virtual_dataset(dataset_name, v_layout, fillvalue=0)
| 515 |
6,989 | <reponame>HeyLey/catboost
#pragma once
#include "defaults.h"
#include <util/generic/ptr.h>
//named sempahore
class TSemaphore {
public:
TSemaphore(const char* name, ui32 maxFreeCount);
~TSemaphore();
//Increase the semaphore counter.
void Release() noexcept;
//Keep a thread held while the semaphore counter is equal 0.
void Acquire() noexcept;
//Try to enter the semaphore gate. A non-blocking variant of Acquire.
//Returns 'true' if the semaphore counter decreased
bool TryAcquire() noexcept;
private:
class TImpl;
THolder<TImpl> Impl_;
};
//unnamed semaphore, faster, than previous
class TFastSemaphore {
public:
TFastSemaphore(ui32 maxFreeCount);
~TFastSemaphore();
void Release() noexcept;
void Acquire() noexcept;
bool TryAcquire() noexcept;
private:
class TImpl;
THolder<TImpl> Impl_;
};
| 331 |
852 | #include "DataFormats/Common/interface/DetSetVector.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/FEDRawData/interface/FEDRawDataCollection.h"
#include "DataFormats/FEDRawData/interface/FEDTrailer.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/utils.h"
#include "EventFilter/Phase2TrackerRawToDigi/test/plugins/Phase2TrackerFEDTestAnalyzer.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDBuffer.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDChannel.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDHeader.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDRawChannelUnpacker.h"
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDZSChannelUnpacker.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/ESHandle.h"
using namespace Phase2Tracker;
using namespace std;
// -----------------------------------------------------------------------------
//
Phase2TrackerFEDTestAnalyzer::Phase2TrackerFEDTestAnalyzer(const edm::ParameterSet& pset) {
LogDebug("Phase2TrackerFEDTestAnalyzer") << "[Phase2TrackerFEDTestAnalyzer::" << __func__ << "]"
<< "Constructing object...";
token_ = consumes<FEDRawDataCollection>(pset.getParameter<edm::InputTag>("ProductLabel"));
}
// -----------------------------------------------------------------------------
//
Phase2TrackerFEDTestAnalyzer::~Phase2TrackerFEDTestAnalyzer() {
LogDebug("Phase2TrackerFEDTestAnalyzer") << "[Phase2TrackerFEDTestAnalyzer::" << __func__ << "]"
<< " Destructing object...";
}
// -----------------------------------------------------------------------------
//
void Phase2TrackerFEDTestAnalyzer::beginJob() {
LogDebug("Phase2TrackerFEDTestAnalyzer") << "[Phase2TrackerFEDTestAnalyzer::" << __func__ << "]";
}
// -----------------------------------------------------------------------------
//
void Phase2TrackerFEDTestAnalyzer::endJob() {
LogDebug("Phase2TrackerFEDTestAnalyzer") << "[Phase2TrackerFEDTestAnalyzer::" << __func__ << "]";
}
// -----------------------------------------------------------------------------
//
void Phase2TrackerFEDTestAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setup) {
// Retrieve FEDRawData collection
edm::Handle<FEDRawDataCollection> buffers;
event.getByToken(token_, buffers);
// Analyze strip tracker FED buffers in data
size_t fedIndex;
for (fedIndex = 0; fedIndex < Phase2Tracker::CMS_FED_ID_MAX; ++fedIndex) {
const FEDRawData& fed = buffers->FEDData(fedIndex);
if (fed.size() != 0 && fedIndex >= Phase2Tracker::FED_ID_MIN && fedIndex <= Phase2Tracker::FED_ID_MAX) {
// construct buffer
Phase2Tracker::Phase2TrackerFEDBuffer* buffer = 0;
buffer = new Phase2Tracker::Phase2TrackerFEDBuffer(fed.data(), fed.size());
cout << " -------------------------------------------- " << endl;
cout << " buffer debug ------------------------------- " << endl;
cout << " -------------------------------------------- " << endl;
cout << " buffer size : " << buffer->bufferSize() << endl;
cout << " fed id : " << fedIndex << endl;
cout << " -------------------------------------------- " << endl;
cout << " tracker header debug ------------------------" << endl;
cout << " -------------------------------------------- " << endl;
Phase2TrackerFEDHeader tr_header = buffer->trackerHeader();
cout << " Version : " << hex << setw(2) << (int)tr_header.getDataFormatVersion() << endl;
cout << " Mode : " << hex << setw(2) << (int)tr_header.getDebugMode() << endl;
cout << " Type : " << hex << setw(2) << (int)tr_header.getEventType() << endl;
cout << " Readout : " << hex << setw(2) << (int)tr_header.getReadoutMode() << endl;
cout << " Status : " << hex << setw(16) << (int)tr_header.getGlibStatusCode() << endl;
cout << " FE stat : ";
for (int i = 15; i >= 0; i--) {
if ((tr_header.frontendStatus())[i]) {
cout << "1";
} else {
cout << "0";
}
}
cout << endl;
cout << " Nr CBC : " << hex << setw(16) << (int)tr_header.getNumberOfCBC() << endl;
cout << " CBC stat : ";
for (int i = 0; i < tr_header.getNumberOfCBC(); i++) {
cout << hex << setw(2) << (int)tr_header.CBCStatus()[i] << " ";
}
cout << endl;
cout << " -------------------------------------------- " << endl;
cout << " Payload ----------------------------------- " << endl;
cout << " -------------------------------------------- " << endl;
// loop channels
int ichan = 0;
for (int ife = 0; ife < 16; ife++) {
for (int icbc = 0; icbc < 16; icbc++) {
const Phase2TrackerFEDChannel& channel = buffer->channel(ichan);
if (channel.length() > 0) {
cout << dec << " reading channel : " << icbc << " on FE " << ife;
cout << dec << " with length : " << (int)channel.length() << endl;
Phase2TrackerFEDRawChannelUnpacker unpacker = Phase2TrackerFEDRawChannelUnpacker(channel);
while (unpacker.hasData()) {
std::cout << (unpacker.stripOn() ? "1" : "_");
unpacker++;
}
std::cout << std::endl;
}
ichan++;
}
} // end loop on channels
}
}
}
| 2,018 |
2,365 | <reponame>daofresh/primevue
{
"main": "./useconfirm.cjs.js",
"module": "./useconfirm.esm.js",
"unpkg": "./useconfirm.min.js",
"types": "./UseConfirm.d.ts"
} | 78 |
1,056 | <gh_stars>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.
*/
package org.netbeans.modules.j2ee.deployment.impl;
import java.util.Collection;
import java.util.Iterator;
/**
* @author nn136682
*/
public class Install extends org.openide.modules.ModuleInstall {
/** Creates a new instance of Install */
public Install() {
}
@Override public void close() {
if (ServerRegistry.wasInitialized ()) {
Collection instances = ServerRegistry.getInstance().getInstances();
for (Iterator i=instances.iterator(); i.hasNext();) {
((ServerInstance)i.next()).stopIfStartedByIde();
}
}
}
}
| 442 |
335 | {
"word": "Box",
"definitions": [
"Put in or provide with a box.",
"Enclose (a piece of text) within printed lines.",
"Restrict the ability of (a person or vehicle) to move freely.",
"Mix up different flocks."
],
"parts-of-speech": "Verb"
} | 119 |
674 | <gh_stars>100-1000
//
// CartridgeMegaBoy.h
// Clock Signal
//
// Created by <NAME> on 18/03/2017.
// Copyright 2017 <NAME>. All rights reserved.
//
#ifndef Atari2600_CartridgeMegaBoy_hpp
#define Atari2600_CartridgeMegaBoy_hpp
#include "Cartridge.hpp"
namespace Atari2600 {
namespace Cartridge {
class MegaBoy: public BusExtender {
public:
MegaBoy(uint8_t *rom_base, std::size_t rom_size) :
BusExtender(rom_base, rom_size),
rom_ptr_(rom_base),
current_page_(0) {
}
void perform_bus_operation(CPU::MOS6502::BusOperation operation, uint16_t address, uint8_t *value) {
address &= 0x1fff;
if(!(address & 0x1000)) return;
if(address == 0x1ff0) {
current_page_ = (current_page_ + 1) & 15;
rom_ptr_ = rom_base_ + current_page_ * 4096;
}
if(isReadOperation(operation)) {
*value = rom_ptr_[address & 4095];
}
}
private:
uint8_t *rom_ptr_;
uint8_t current_page_;
};
}
}
#endif /* CartridgeMegaBoy_h */
| 409 |
320 | <filename>jme3-wavefront/src/com/jme3/gde/wavefront/WaveFrontOBJDataObject.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.jme3.gde.wavefront;
import com.jme3.gde.core.assets.SpatialAssetDataObject;
import java.io.IOException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.MIMEResolver;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectExistsException;
import org.openide.loaders.MultiFileLoader;
@MIMEResolver.ExtensionRegistration(
displayName = "Wavefront OBJ",
mimeType = "text/x-wavefrontobj",
extension = {"obj", "OBJ"}
)
@DataObject.Registration(displayName = "Wavefront OBJ", mimeType = "text/x-wavefrontobj", iconBase ="com/jme3/gde/wavefront/People_039.gif")
@ActionReferences(value = {
@ActionReference(id =
@ActionID(category = "jMonkeyPlatform", id = "com.jme3.gde.core.assets.actions.ConvertModel"), path = "Loaders/text/x-wavefrontobj/Actions", position = 10),
@ActionReference(id =
@ActionID(category = "jMonkeyPlatform", id = "com.jme3.gde.core.assets.actions.OpenModel"), path = "Loaders/text/x-wavefrontobj/Actions", position = 20),
@ActionReference(id =
@ActionID(category = "Edit", id = "org.openide.actions.CutAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 200, separatorBefore = 100),
@ActionReference(id =
@ActionID(category = "Edit", id = "org.openide.actions.CopyAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 300, separatorAfter = 400),
@ActionReference(id =
@ActionID(category = "Edit", id = "org.openide.actions.DeleteAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 500),
@ActionReference(id =
@ActionID(category = "System", id = "org.openide.actions.RenameAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 600, separatorAfter = 700),
@ActionReference(id =
@ActionID(category = "System", id = "org.openide.actions.SaveAsTemplateAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 800, separatorAfter = 900),
@ActionReference(id =
@ActionID(category = "System", id = "org.openide.actions.FileSystemAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 1000, separatorAfter = 1100),
@ActionReference(id =
@ActionID(category = "System", id = "org.openide.actions.ToolsAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 1200),
@ActionReference(id =
@ActionID(category = "System", id = "org.openide.actions.PropertiesAction"), path = "Loaders/text/x-wavefrontobj/Actions", position = 1300)
})
public class WaveFrontOBJDataObject extends SpatialAssetDataObject {
public WaveFrontOBJDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
super(pf, loader);
}
}
| 1,048 |
848 | <reponame>donsheng/acrn-hypervisor
/*
* Copyright (C) 2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "log_sys.h"
#include "fsutils.h"
#include "strutils.h"
#include "vmrecord.h"
#include <stdlib.h>
int vmrecord_last(struct vmrecord_t *vmrecord, const char *vm_name,
size_t nlen, char *vmkey, size_t ksize)
{
int res;
char *p;
char *key;
if (!vmrecord || !vm_name || !nlen || !vmkey || !ksize)
return -1;
key = malloc(nlen + 2);
if (!key)
return -1;
memcpy(key, vm_name, nlen);
key[nlen] = ' ';
key[nlen + 1] = '\0';
pthread_mutex_lock(&vmrecord->mtx);
res = file_read_key_value_r(vmkey, ksize, vmrecord->path, key,
nlen + 1);
pthread_mutex_unlock(&vmrecord->mtx);
free(key);
if (res < 0) {
LOGE("failed to search %s, %s\n", vmrecord->path,
strerror(errno));
return -1;
}
p = strchr(vmkey, ' ');
if (p)
*p = 0;
return 0;
}
/* This function must be called with holding vmrecord mutex */
int vmrecord_mark(struct vmrecord_t *vmrecord, const char *vmkey,
size_t klen, enum vmrecord_mark_t type)
{
size_t len;
char *line;
char *tag;
if (!vmrecord || !vmrecord->recos || !vmkey || !klen)
return -1;
line = get_line(vmkey, klen, vmrecord->recos->begin,
vmrecord->recos->size, vmrecord->recos->begin, &len);
if (!line)
return -1;
tag = line + len - VMRECORD_TAG_LEN;
if (type == SUCCESS)
memcpy(tag, VMRECORD_TAG_SUCCESS, VMRECORD_TAG_LEN);
else if (type == NOT_FOUND)
memcpy(tag, VMRECORD_TAG_NOT_FOUND, VMRECORD_TAG_LEN);
else if (type == MISS_LOG)
memcpy(tag, VMRECORD_TAG_MISS_LOG, VMRECORD_TAG_LEN);
else if (type == WAITING_SYNC)
memcpy(tag, VMRECORD_TAG_WAITING_SYNC, VMRECORD_TAG_LEN);
else if (type == ON_GOING)
memcpy(tag, VMRECORD_TAG_ON_GOING, VMRECORD_TAG_LEN);
else if (type == NO_RESRC)
memcpy(tag, VMRECORD_TAG_NO_RESOURCE, VMRECORD_TAG_LEN);
else
return -1;
return 0;
}
int vmrecord_open_mark(struct vmrecord_t *vmrecord, const char *vmkey,
size_t klen, enum vmrecord_mark_t type)
{
int ret;
if (!vmrecord || !vmkey || !klen)
return -1;
pthread_mutex_lock(&vmrecord->mtx);
vmrecord->recos = mmap_file(vmrecord->path);
if (!vmrecord->recos) {
LOGE("failed to mmap %s, %s\n", vmrecord->path,
strerror(errno));
ret = -1;
goto unlock;
}
if (!vmrecord->recos->size ||
mm_count_lines(vmrecord->recos) < VMRECORD_HEAD_LINES) {
LOGE("(%s) invalid\n", vmrecord->path);
ret = -1;
goto out;
}
ret = vmrecord_mark(vmrecord, vmkey, klen, type);
out:
unmap_file(vmrecord->recos);
unlock:
pthread_mutex_unlock(&vmrecord->mtx);
return ret;
}
int vmrecord_gen_ifnot_exists(struct vmrecord_t *vmrecord)
{
const char * const head =
"/* DONT EDIT!\n"
" * This file records VM id synced or about to be synched,\n"
" * the tag:\n"
" * \"<==\" indicates event waiting to sync.\n"
" * \"NOT_FOUND\" indicates event not found in User VM.\n"
" * \"MISS_LOGS\" indicates event miss logs in User VM.\n"
" * \"ON_GOING\" indicates event is under syncing.\n"
" * \"NO_RESORC\" indicates no enough resources in Service VM.\n"
" */\n\n";
if (!vmrecord) {
LOGE("vmrecord was not initialized\n");
return -1;
}
pthread_mutex_lock(&vmrecord->mtx);
if (!file_exists(vmrecord->path)) {
if (overwrite_file(vmrecord->path, head) < 0) {
pthread_mutex_unlock(&vmrecord->mtx);
LOGE("failed to create file (%s), %s\n",
vmrecord->path, strerror(errno));
return -1;
}
}
pthread_mutex_unlock(&vmrecord->mtx);
return 0;
}
int vmrecord_new(struct vmrecord_t *vmrecord, const char *vm_name,
const char *key)
{
char log_new[64];
int nlen;
if (!vmrecord || !vm_name || !key)
return -1;
nlen = snprintf(log_new, sizeof(log_new), "%s %s %s\n",
vm_name, key, VMRECORD_TAG_WAITING_SYNC);
if (s_not_expect(nlen, sizeof(log_new))) {
LOGE("failed to construct record, key (%s)\n", key);
return -1;
}
pthread_mutex_lock(&vmrecord->mtx);
if (append_file(vmrecord->path, log_new, strnlen(log_new, 64)) < 0) {
pthread_mutex_unlock(&vmrecord->mtx);
LOGE("failed to append file (%s), %s\n", vmrecord->path,
strerror(errno));
return -1;
}
pthread_mutex_unlock(&vmrecord->mtx);
return 0;
}
| 1,867 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-xjwx-qg8w-3x9p",
"modified": "2022-05-02T03:43:22Z",
"published": "2022-05-02T03:43:22Z",
"aliases": [
"CVE-2009-3249"
],
"details": "Multiple directory traversal vulnerabilities in vtiger CRM 5.0.4 allow remote attackers to include and execute arbitrary local files via a .. (dot dot) in (1) the module parameter to graph.php; or the (2) module or (3) file parameter to include/Ajax/CommonAjax.php, reachable through modules/Campaigns/CampaignsAjax.php, modules/SalesOrder/SalesOrderAjax.php, modules/System/SystemAjax.php, modules/Products/ProductsAjax.php, modules/uploads/uploadsAjax.php, modules/Dashboard/DashboardAjax.php, modules/Potentials/PotentialsAjax.php, modules/Notes/NotesAjax.php, modules/Faq/FaqAjax.php, modules/Quotes/QuotesAjax.php, modules/Utilities/UtilitiesAjax.php, modules/Calendar/ActivityAjax.php, modules/Calendar/CalendarAjax.php, modules/PurchaseOrder/PurchaseOrderAjax.php, modules/HelpDesk/HelpDeskAjax.php, modules/Invoice/InvoiceAjax.php, modules/Accounts/AccountsAjax.php, modules/Reports/ReportsAjax.php, modules/Contacts/ContactsAjax.php, and modules/Portal/PortalAjax.php; and allow remote authenticated users to include and execute arbitrary local files via a .. (dot dot) in the step parameter in an Import action to the (4) Accounts, (5) Contacts, (6) HelpDesk, (7) Leads, (8) Potentials, (9) Products, or (10) Vendors module, reachable through index.php and related to modules/Import/index.php and multiple Import.php files.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-3249"
},
{
"type": "WEB",
"url": "http://marc.info/?l=bugtraq&m=125060676515670&w=2"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/36309"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/8118"
},
{
"type": "WEB",
"url": "http://www.exploit-db.com/exploits/9450"
},
{
"type": "WEB",
"url": "http://www.osvdb.org/57239"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/36062"
},
{
"type": "WEB",
"url": "http://www.ush.it/2009/08/18/vtiger-crm-504-multiple-vulnerabilities/"
},
{
"type": "WEB",
"url": "http://www.ush.it/team/ush/hack-vtigercrm_504/vtigercrm_504.txt"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2009/2319"
}
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 1,147 |
502 | <gh_stars>100-1000
/**
* Copyright 1996-2013 Founder International Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author kenshin
*/
package com.founder.fix.fixflow.core.impl.db;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.founder.fix.bpmn2extensions.sqlmappingconfig.Result;
import com.founder.fix.bpmn2extensions.sqlmappingconfig.ResultMap;
import com.founder.fix.fixflow.core.impl.Context;
import com.founder.fix.fixflow.core.impl.util.JavaBeanUtil;
import com.founder.fix.fixflow.core.impl.util.StringUtil;
import com.founder.fix.fixflow.core.scriptlanguage.AbstractScriptLanguageMgmt;
public abstract class AbstractPersistentObject <T> implements PersistentObject {
/**
*
*/
private static final long serialVersionUID = -1542067996535178080L;
private ResultMap resultMap;
private boolean isAdd=true;
public boolean isAdd() {
return isAdd;
}
public void setAdd(boolean isAdd) {
this.isAdd = isAdd;
}
/**
* 获取当前对象所使用的数据映射规则
* @return
*/
public ResultMap getResultMap() {
return resultMap;
}
//用户自定义字段用来存储数据库表中的新增字段
/**
* 用户自定义字段
*/
protected Map<String, Object> extensionFields = new HashMap<String, Object>();
/**
* 获取用户自定义字段值
* @param fieldName 字段名称
* @return
*/
public Object getExtensionField(String fieldName) {
return extensionFields.get(fieldName);
}
/**
* 获取用户自定义字段Map
* @return
*/
public Map<String, Object> getExtensionFields() {
return extensionFields;
}
/**
* 设置用户自定义字段
* @param extensionFields
*/
protected void setExtensionFields(Map<String, Object> extensionFields) {
this.extensionFields = extensionFields;
}
/**
* 添加一个用户自定义字段
* @param fieldName 字段名称
* @param fieldValue 字段值
*/
protected void addExtensionField(String fieldName, Object fieldValue) {
this.extensionFields.put(fieldName, fieldValue);
}
/**
* 持久化扩展字段
*/
protected Map<String, Object> persistenceExtensionFields = new HashMap<String, Object>();
/**
* 获取持久化Map
* @return
*/
public Map<String, Object> getPersistenceExtensionFields() {
return persistenceExtensionFields;
}
/**
* 设置一个持久化Map,这个值将会被持久到表中
* @param fieldName 字段名称
* @param value 字段值
*/
public void setPersistenceExtensionField(String fieldName, Object value) {
extensionFields.put(fieldName, value);
persistenceExtensionFields.put(fieldName, value);
}
// 抽象方法 ////////////////////////
/**
* 获取拷贝所使用的业务规则编号
* @return
*/
public abstract String getCloneRuleId();
/**
* 获取能持久化到数据的Map的业务规则编号
* @return
*/
public abstract String getPersistentDbMapRuleId();
/**
* 获取对象Map化业务规则编号
* @return
*/
public abstract String getPersistentStateRuleId();
// 公用方法
/**
* 从数据库初始化对象
*
* @param entityMap
* 字段Map
* @return
*/
@SuppressWarnings("rawtypes")
public void persistentInit(ResultMap resultMap, Map<String, Object> entityMap) {
String className = resultMap.getType();
this.resultMap=resultMap;
try {
Class clazz = Class.forName(className);
//Object obj = clazz.newInstance();
// 获得类的所有属性
List<Result> results=resultMap.getResult();
for (Result result : results) {
Object dataObj=entityMap.get(result.getColumn());
if(dataObj==null){
continue;
}
// PropertyDescriptor pd = new PropertyDescriptor(result.getProperty(), clazz);
// 获得写方法
// Method wM = pd.getWriteMethod();
Method wM = JavaBeanUtil.getSetStringMethod(clazz, result.getProperty(), result.getJdbcType());
if(wM==null){
continue;
}
// 获得读方法
//Method rM = pd.getReadMethod();
// 获得方法的参数,因为是标准的set方法,所以只取第一个参数
Class[] classes = wM.getParameterTypes();
// 判断参数不为空,则只有一个
if (classes != null && classes.length == 1) {
// 判断参数类型
if (classes[0].equals(String.class)) {
wM.invoke(this, StringUtil.getString(dataObj));
}else if(classes[0].equals(Date.class)){
dataObj = StringUtil.getDate(dataObj);
wM.invoke(this, dataObj);
}else if(classes[0].equals(int.class)){
wM.invoke(this, StringUtil.getInt(dataObj));
}else if(classes[0].equals(byte[].class)){
wM.invoke(this,(byte[]) dataObj);
}
}
entityMap.remove(result.getColumn());
}
for (String mapKey : entityMap.keySet()) {
addExtensionField(mapKey, entityMap.get(mapKey));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
/**
* 拷贝对象
*/
public T clone(){
AbstractScriptLanguageMgmt scriptLanguageMgmt=Context.getAbstractScriptLanguageMgmt();
T tObject=(T)scriptLanguageMgmt.executeBusinessRules(getCloneRuleId(), this);
return tObject;
}
/**
* 获取能持久化到数据的Map
*
* @return 对应到数据库字段的Map
*/
public Map<String, Object> getPersistentDbMap() {
Map<String, Object> objectParam = new HashMap<String, Object>();
objectParam=(Map<String, Object>)Context.getCommandContext().getTaskManager().getPersistentDbMap(getPersistentDbMapRuleId(), this);
return objectParam;
}
@SuppressWarnings("unchecked")
public Map<String, Object> getPersistentState() {
Map<String, Object> persistentState =null;
persistentState=(Map<String, Object> )Context.getCommandContext().getMappingSqlSession().selectOne(getPersistentStateRuleId(), this);
return persistentState;
}
}
| 3,058 |
1,627 | package net.querz.mcaselector.io.job;
import net.querz.mcaselector.debug.Debug;
import net.querz.mcaselector.io.ByteArrayPointer;
import net.querz.mcaselector.io.RegionDirectories;
import net.querz.mcaselector.io.mca.ChunkData;
import net.querz.mcaselector.io.mca.EntitiesMCAFile;
import net.querz.mcaselector.io.mca.PoiMCAFile;
import net.querz.mcaselector.io.mca.RegionMCAFile;
import net.querz.mcaselector.point.Point2i;
import net.querz.mcaselector.progress.Timer;
import net.querz.mcaselector.tiles.Tile;
import net.querz.mcaselector.tiles.overlay.OverlayParser;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
public class ParseDataJob extends LoadDataJob {
private static final Set<Point2i> loading = ConcurrentHashMap.newKeySet();
private final BiConsumer<int[], UUID> dataCallback;
private final UUID world;
private final OverlayParser parser;
private final Tile tile;
public ParseDataJob(Tile tile, RegionDirectories dirs, UUID world, BiConsumer<int[], UUID> dataCallback, OverlayParser parser) {
super(dirs);
this.tile = tile;
this.dataCallback = dataCallback;
this.world = world;
this.parser = parser;
setLoading(tile, true);
}
public static boolean isLoading(Tile tile) {
return loading.contains(tile.getLocation());
}
public static synchronized void setLoading(Tile tile, boolean loading) {
if (loading) {
ParseDataJob.loading.add(tile.getLocation());
} else {
ParseDataJob.loading.remove(tile.getLocation());
}
}
public Tile getTile() {
return tile;
}
@Override
public void run() {
execute();
}
@Override
public void execute() {
Timer t = new Timer();
RegionMCAFile regionMCAFile = null;
if (getRegionDirectories().getRegion() != null && getRegionDirectories().getRegion().exists() && getRegionDirectories().getRegion().length() > 0) {
byte[] regionData = loadRegion();
regionMCAFile = new RegionMCAFile(getRegionDirectories().getRegion());
if (regionData != null) {
// load EntitiesMCAFile
ByteArrayPointer ptr = new ByteArrayPointer(regionData);
try {
regionMCAFile.load(ptr);
} catch (IOException ex) {
Debug.errorf("failed to read mca file header from %s", getRegionDirectories().getRegion());
}
}
}
EntitiesMCAFile entitiesMCAFile = null;
if (getRegionDirectories().getEntities() != null && getRegionDirectories().getEntities().exists() && getRegionDirectories().getEntities().length() > 0) {
byte[] entitiesData = loadEntities();
entitiesMCAFile = new EntitiesMCAFile(getRegionDirectories().getEntities());
if (entitiesData != null) {
// load EntitiesMCAFile
ByteArrayPointer ptr = new ByteArrayPointer(entitiesData);
try {
entitiesMCAFile.load(ptr);
} catch (IOException ex) {
Debug.errorf("failed to read mca file header from %s", getRegionDirectories().getEntities());
}
}
}
PoiMCAFile poiMCAFile = null;
if (getRegionDirectories().getPoi() != null && getRegionDirectories().getPoi().exists() && getRegionDirectories().getPoi().length() > 0) {
byte[] poiData = loadPoi();
poiMCAFile = new PoiMCAFile(getRegionDirectories().getPoi());
if (poiData != null) {
// load PoiMCAFile
ByteArrayPointer ptr = new ByteArrayPointer(poiData);
try {
poiMCAFile.load(ptr);
} catch (IOException ex) {
Debug.errorf("failed to read mca file header from %s", getRegionDirectories().getPoi());
}
}
}
if (regionMCAFile == null && poiMCAFile == null && entitiesMCAFile == null) {
dataCallback.accept(null, world);
Debug.dumpf("no data to load and parse for region %s", getRegionDirectories().getLocation());
setLoading(tile, false);
return;
}
int[] data = new int[1024];
for (int i = 0; i < 1024; i++) {
ChunkData chunkData = new ChunkData(
regionMCAFile == null ? null : regionMCAFile.getChunk(i),
poiMCAFile == null ? null : poiMCAFile.getChunk(i),
entitiesMCAFile == null ? null : entitiesMCAFile.getChunk(i));
try {
data[i] = chunkData.parseData(parser);
} catch (Exception ex) {
Debug.dumpException("failed to parse chunk data at index " + i, ex);
}
}
dataCallback.accept(data, world);
setLoading(tile, false);
Debug.dumpf("took %s to load and parse data for region %s", t, getRegionDirectories().getLocation());
}
@Override
public void cancel() {
setLoading(tile, false);
}
}
| 1,651 |
839 | /**
* 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.cxf.configuration;
/**
* The configurer's interface
*
* A class that implements this interface will perform a
* bean's configuration work
*/
public interface Configurer {
String DEFAULT_USER_CFG_FILE = "cxf.xml";
String USER_CFG_FILE_PROPERTY_NAME = "cxf.config.file";
String USER_CFG_FILE_PROPERTY_URL = "cxf.config.file.url";
/**
* set up the Bean's value by using Dependency Injection from the application context
* @param beanInstance the instance of the bean which needs to be configured
*/
void configureBean(Object beanInstance);
/**
* set up the Bean's value by using Dependency Injection from the application context
* with a proper name. You can use * as the prefix of wildcard name.
* @param name the name of the bean which needs to be configured
* @param beanInstance the instance of bean which need to be configured
*/
void configureBean(String name, Object beanInstance);
}
| 496 |
506 | <reponame>Ashindustry007/competitive-programming<gh_stars>100-1000
// https://abc074.contest.atcoder.jp/tasks/arc083_a
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d, e, f;
cin >> a >> b >> c >> d >> e >> f;
int sugar_water = 0;
int sugar = 0;
double density = 0;
for (int i = 0; i * a * 100 <= f; i++) {
for (int j = 0; (i * a + j * b) * 100 <= f; j++) {
for (int k = 0; (i * a + j * b) * 100 + k * c <= f; k++) {
for (int l = 0; (i * a + j * b) * 100 + k * c + l * d <= f; l++) {
int w = (i * a + j * b) * 100;
int need = e * (i * a + j * b);
int s = k * c + l * d;
if (s > need) break;
if (s + w == 0) continue;
double den = double(100.0 * s) / double(s + w);
if (den >= density) {
density = den;
sugar = s;
sugar_water = s + w;
}
}
}
}
}
cout << sugar_water << " " << sugar << endl;
}
| 449 |
2,171 | <filename>src/test/integration/standalone_functions_test.cpp
#include <gtest/gtest.h>
#include <test/test-models/good-standalone-functions/basic.hpp>
TEST(standalone_functions, int_only_multiplication) {
EXPECT_EQ(int_only_multiplication(2, 5), 10);
EXPECT_NEAR(my_log1p_exp(1), 1.3132, 1E-4);
Eigen::Matrix<double, -1, 1> a(6), correct(6), res(6);
a << 1, 2, 3, 4, 5, 6;
res = my_vector_mul_by_5(a);
correct << 5, 10, 15, 20, 25, 30;
for (int i = 0; i < a.size(); i++) {
EXPECT_EQ(res(i), correct(i));
}
}
| 239 |
1,318 | /*
* Copyright 2016 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.linkedin.drelephant.schedulers;
/**
* Scheduler interface defining the
*/
public interface Scheduler {
/**
* Return the Scheduler Name
*
* @return the scheduler name
*/
public String getSchedulerName();
/**
* True if the the scheduler object was not able to parse the given properties
*
* @return true the scheduler is empty
*/
public boolean isEmpty();
/**
* Return the Job Definition Id of the job in the workflow
*
* @return the job definition id
*/
public String getJobDefId();
/**
* Return the Job Execution Id of the job in the workflow
*
* @return the job execution id
*/
public String getJobExecId();
/**
* Return the Flow Definition Id of the workflow
*
* @return the flow definition id
*/
public String getFlowDefId();
/**
* Return the Flow Execution Id of the workflow
*
* @return the flow execution id
*/
public String getFlowExecId();
/**
* Return a link to the job's definition
*
* @return the job definition url
*/
public String getJobDefUrl();
/**
* Return a link to the job's execution
*
* @return the job execution url
*/
public String getJobExecUrl();
/**
* Return a link to the flow's definition
*
* @return the flow definition url
*/
public String getFlowDefUrl();
/**
* Return a link to the flow's execution
*
* @return the flow execution url
*/
public String getFlowExecUrl();
/**
* Return the name of the Job/Action in the Flow
*
* @return the job/action name
*/
public String getJobName();
/**
* Return the workflow depth
*
* @return the workflow depth
*/
public int getWorkflowDepth();
}
| 700 |
471 | <reponame>akashkj/commcare-hq
from datetime import datetime
from unittest.mock import patch
from django.test import SimpleTestCase, TestCase
from corehq.apps.users.models import (
CommCareUser,
CouchUser,
Invitation,
WebUser,
)
from corehq.apps.domain.models import Domain
class CouchUserTest(SimpleTestCase):
def test_web_user_flag(self):
self.assertTrue(WebUser().is_web_user())
self.assertTrue(CouchUser.wrap(WebUser().to_json()).is_web_user())
self.assertFalse(CommCareUser().is_web_user())
self.assertFalse(CouchUser.wrap(CommCareUser().to_json()).is_web_user())
with self.assertRaises(NotImplementedError):
CouchUser().is_web_user()
def test_commcare_user_flag(self):
self.assertFalse(WebUser().is_commcare_user())
self.assertFalse(CouchUser.wrap(WebUser().to_json()).is_commcare_user())
self.assertTrue(CommCareUser().is_commcare_user())
self.assertTrue(CouchUser.wrap(CommCareUser().to_json()).is_commcare_user())
with self.assertRaises(NotImplementedError):
CouchUser().is_commcare_user()
class InvitationTest(TestCase):
@classmethod
def setUpClass(cls):
super(InvitationTest, cls).setUpClass()
cls.invitations = [
Invitation(domain='domain_1', email='<EMAIL>', invited_by='<EMAIL>',
invited_on=datetime.utcnow()),
Invitation(domain='domain_1', email='<EMAIL>', invited_by='<EMAIL>',
invited_on=datetime.utcnow(), is_accepted=True),
Invitation(domain='domain_1', email='<EMAIL>', invited_by='<EMAIL>',
invited_on=datetime.utcnow(), is_accepted=True),
Invitation(domain='domain_2', email='<EMAIL>', invited_by='<EMAIL>',
invited_on=datetime.utcnow()),
]
for inv in cls.invitations:
inv.save()
def test_by_domain(self):
self.assertEqual(len(Invitation.by_domain('domain_1')), 1)
self.assertEqual(len(Invitation.by_domain('domain_1', is_accepted=True)), 2)
self.assertEqual(len(Invitation.by_domain('domain_2')), 1)
self.assertEqual(len(Invitation.by_domain('domain_3')), 0)
def test_by_email(self):
self.assertEqual(len(Invitation.by_email('<EMAIL>')), 1)
self.assertEqual(len(Invitation.by_email('<EMAIL>')), 1)
self.assertEqual(len(Invitation.by_email('<EMAIL>')), 0)
@classmethod
def tearDownClass(cls):
for inv in cls.invitations:
inv.delete()
super(InvitationTest, cls).tearDownClass()
class User_MessagingDomain_Tests(SimpleTestCase):
def test_web_user_with_no_messaging_domain_returns_false(self):
user = WebUser(domains=['domain_no_messaging_1', 'domain_no_messaging_2'])
self.assertFalse(user.belongs_to_messaging_domain())
def test_web_user_with_messaging_domain_returns_true(self):
user = WebUser(domains=['domain_no_messaging_1', 'domain_with_messaging', 'domain_no_messaging_2'])
self.assertTrue(user.belongs_to_messaging_domain())
def test_commcare_user_is_compatible(self):
user = CommCareUser(domain='domain_no_messaging_1')
self.assertFalse(user.belongs_to_messaging_domain())
def setUp(self):
self.domains = {
'domain_no_messaging_1': Domain(granted_messaging_access=False),
'domain_no_messaging_2': Domain(granted_messaging_access=False),
'domain_with_messaging': Domain(granted_messaging_access=True),
}
patcher = patch.object(Domain, 'get_by_name', side_effect=self._get_domain_by_name)
patcher.start()
self.addCleanup(patcher.stop)
def _get_domain_by_name(self, name):
return self.domains[name]
| 1,691 |
1,362 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.domain import Domain
from twilio.rest.lookups.v1 import V1
class Lookups(Domain):
def __init__(self, twilio):
"""
Initialize the Lookups Domain
:returns: Domain for Lookups
:rtype: twilio.rest.lookups.Lookups
"""
super(Lookups, self).__init__(twilio)
self.base_url = 'https://lookups.twilio.com'
# Versions
self._v1 = None
@property
def v1(self):
"""
:returns: Version v1 of lookups
:rtype: twilio.rest.lookups.v1.V1
"""
if self._v1 is None:
self._v1 = V1(self)
return self._v1
@property
def phone_numbers(self):
"""
:rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList
"""
return self.v1.phone_numbers
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Lookups>'
| 568 |
460 | #include "../../../tools/designer/src/lib/shared/qtresourcemodel_p.h"
| 27 |
1,647 | <filename>pythran/pythonic/include/numpy/asscalar.hpp
#ifndef PYTHONIC_INCLUDE_NUMPY_ASSCALAR_HPP
#define PYTHONIC_INCLUDE_NUMPY_ASSCALAR_HPP
#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/ndarray.hpp"
#include "pythonic/include/numpy/asarray.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
template <class T>
using asscalar_result_type = typename std::conditional<
std::is_integral<T>::value, long,
typename std::conditional<std::is_floating_point<T>::value, double,
std::complex<double>>::type>::type;
template <class E>
asscalar_result_type<typename E::dtype> asscalar(E const &expr);
DEFINE_FUNCTOR(pythonic::numpy, asscalar);
}
PYTHONIC_NS_END
#endif
| 334 |
1,467 | <gh_stars>1000+
{
"version": "2.5.66",
"date": "2019-06-18",
"entries": [
{
"type": "feature",
"category": "AWS Resource Groups Tagging API",
"description": "You can use tag policies to help standardize on tags across your organization's resources."
},
{
"type": "feature",
"category": "Amazon Elastic Compute Cloud",
"description": "You can now launch new 12xlarge, 24xlarge, and metal instance sizes on the Amazon EC2 compute optimized C5 instance types featuring 2nd Gen Intel Xeon Scalable Processors."
}
]
} | 259 |
4,200 | <reponame>kbens/rundeck<filename>core/src/main/java/com/dtolabs/rundeck/core/rules/StateWorkflowSystem.java
/*
* Copyright 2019 Rundeck, Inc. (http://rundeck.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtolabs.rundeck.core.rules;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/**
* Uses a mutable state and rule engine
*/
public interface StateWorkflowSystem
extends WorkflowSystem<Map<String, String>>
{
/**
* state object
*/
MutableStateObj getState();
/**
* Rule engine
*/
RuleEngine getRuleEngine();
/**
* state change for given identity
*/
interface StateChange<D> {
/**
* identity for change
*/
String getIdentity();
/**
* @return new state data
*/
Map<String, String> getState();
/**
* @return shared data
*/
SharedData<D, Map<String, String>> getSharedData();
}
/**
* Create State Change
*
* @param identity
* @param stateSupplier
* @param sharedData
* @param <D>
*/
static <D> StateChange<D> stateChange(
String identity,
Supplier<Map<String, String>> stateSupplier,
SharedData<D, Map<String, String>> sharedData
)
{
return new StateWorkflowSystem.StateChange<D>() {
@Override
public String getIdentity() {
return identity;
}
@Override
public Map<String, String> getState() {
return stateSupplier.get();
}
@Override
public SharedData<D, Map<String, String>> getSharedData() {
return sharedData;
}
};
}
/**
* state change for given identity
*/
interface StateEvent<D> {
/**
* Current state
*/
MutableStateObj getState();
SharedData<D, Map<String, String>> getSharedData();
}
/**
* Create StateEvent
*
* @param state
* @param sharedData
* @param <D>
*/
static <D> StateEvent<D> stateEvent(
MutableStateObj state,
WorkflowSystem.SharedData<D, Map<String, String>> sharedData
)
{
return new StateWorkflowSystem.StateEvent<D>() {
@Override
public MutableStateObj getState() {
return state;
}
@Override
public SharedData<D, Map<String, String>> getSharedData() {
return sharedData;
}
};
}
/**
* state change event for given identity
*/
interface StateChangeEvent<D> {
/**
* Current state
*/
public MutableStateObj getState();
/**
* State change
*/
StateChange<D> getStateChange();
}
/**
* Create StateChangeEvent
*
* @param state
* @param stateChange
* @param <D>
*/
static <D> StateChangeEvent<D> stateChangeEvent(
MutableStateObj state,
StateChange<D> stateChange
)
{
return new StateWorkflowSystem.StateChangeEvent<D>() {
@Override
public MutableStateObj getState() {
return state;
}
@Override
public StateChange<D> getStateChange() {
return stateChange;
}
};
}
/**
* operation event with identity
*/
interface OperationEvent<D>
extends StateEvent<D>
{
/**
* Get operation identity
*/
String getIdentity();
}
/**
* Create OperationEvent
*
* @param identity
* @param state
* @param sharedData
* @param <D>
*/
static <D> OperationEvent<D> operationEvent(
String identity,
MutableStateObj state,
WorkflowSystem.SharedData<D, Map<String, String>> sharedData
)
{
return new StateWorkflowSystem.OperationEvent<D>() {
@Override
public String getIdentity() {
return identity;
}
@Override
public MutableStateObj getState() {
return state;
}
@Override
public SharedData<D, Map<String, String>> getSharedData() {
return sharedData;
}
};
}
/**
* operation completed event
*/
interface OperationCompleteEvent<D, RES extends OperationCompleted<D>, OP extends Operation<D, RES>>
extends OperationEvent<D>
{
/**
* @return result of operation
*/
WorkflowSystem.OperationResult<D, RES, OP> getResult();
}
/**
* Create OperationCompleteEvent
* @param identity
* @param state
* @param sharedData
* @param result
* @param <D>
* @param <RES>
* @param <OP>
* @return
*/
static <D, RES extends OperationCompleted<D>, OP extends Operation<D, RES>> OperationCompleteEvent<D, RES, OP> operationCompleteEvent(
String identity,
MutableStateObj state,
WorkflowSystem.SharedData<D, Map<String, String>> sharedData,
final OperationResult<D, RES, OP> result
)
{
return new StateWorkflowSystem.OperationCompleteEvent<D, RES, OP>() {
@Override
public String getIdentity() {
return identity;
}
@Override
public MutableStateObj getState() {
return state;
}
@Override
public SharedData<D, Map<String, String>> getSharedData() {
return sharedData;
}
@Override
public OperationResult<D, RES, OP> getResult() {
return result;
}
};
}
/**
* Handle the state changes for the rule engine
*
* @param change a single change
* @return true if internal state was changed
*/
boolean processStateChange(WorkflowEngine.StateChange<?> change);
/**
* @return true if the state indicates the workflow should end
*/
boolean isWorkflowEndState();
/**
* listener
*/
List<WorkflowSystemEventListener> getListeners();
/**
* set listener
*
* @param listener
*/
void setListeners(List<WorkflowSystemEventListener> listeners);
}
| 3,207 |
2,151 | <gh_stars>1000+
// Copyright 2018 The Feed 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 com.google.android.libraries.feed.piet.host;
import android.view.View;
import com.google.search.now.ui.piet.ActionsProto.Action;
import com.google.search.now.ui.piet.PietProto.Frame;
/**
* Interface from the Piet host which provides handling of {@link Action} from the UI. An instance
* of this is provided by the host. When an action is raised by the client {@link
* #handleAction(Action, Frame, View, String)} will be called.
*/
public interface ActionHandler {
/** Called on a event, such as a click of a view, on a UI element */
// TODO: Do we need the veLoggingToken, one is defined in the Action
void handleAction(Action action, Frame frame, View view, /*@Nullable*/ String veLoggingToken);
}
| 373 |
1,444 | <reponame>GabrielSturtevant/mage
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.ObjectColor;
import mage.abilities.common.BlocksOrBecomesBlockedSourceTriggeredAbility;
import mage.abilities.common.delayed.AtTheEndOfCombatDelayedTriggeredAbility;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.CreateDelayedTriggeredAbilityEffect;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.Predicates;
import mage.filter.predicate.mageobject.ColorPredicate;
/**
*
* @author jeffwadsworth
*/
public final class Abomination extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("green or white creature");
static {
filter.add(Predicates.or(new ColorPredicate(ObjectColor.GREEN), new ColorPredicate(ObjectColor.WHITE)));
}
public Abomination(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{B}{B}");
this.subtype.add(SubType.HORROR);
this.power = new MageInt(2);
this.toughness = new MageInt(6);
// Whenever Abomination blocks or becomes blocked by a green or white creature, destroy that creature at end of combat.
Effect effect = new CreateDelayedTriggeredAbilityEffect(new AtTheEndOfCombatDelayedTriggeredAbility(new DestroyTargetEffect()), true);
effect.setText("destroy that creature at end of combat");
this.addAbility(new BlocksOrBecomesBlockedSourceTriggeredAbility(effect, filter, false));
}
private Abomination(final Abomination card) {
super(card);
}
@Override
public Abomination copy() {
return new Abomination(this);
}
}
| 632 |
413 | <reponame>philomenec/reco-gym
from numpy.random.mtrand import RandomState
import numpy as np
from .time_generator import TimeGenerator
class NormalTimeGenerator(TimeGenerator):
""""""
def __init__(self, config):
super(NormalTimeGenerator, self).__init__(config)
self.current_time = 0
if not hasattr(self.config, 'normal_time_mu'):
self.normal_time_mu = 0
else:
self.normal_time_mu = self.config.normal_time_mu
if not hasattr(self.config, 'normal_time_sigma'):
self.normal_time_sigma = 1
else:
self.normal_time_sigma = self.config.normal_time_sigma
self.rng = RandomState(config.random_seed)
def new_time(self):
tmp_time = self.current_time
self.current_time += np.abs(self.rng.normal(self.normal_time_mu, self.normal_time_sigma))
return tmp_time
def reset(self):
self.current_time = 0
| 418 |
368 | <reponame>gta-chaos-mod/plugin-sdk
/*
Plugin-SDK (Grand Theft Auto) SHARED header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "CTimer.h"
class KeyCheck {
static unsigned char currStates[256];
static unsigned char prevStates[256];
static unsigned int timeDelayPressed[256];
public:
static void Update();
static bool Check(unsigned int key);
static bool CheckJustDown(unsigned int key);
static bool CheckJustUp(unsigned int key);
static bool CheckWithDelay(unsigned int key, unsigned int time);
};
| 219 |
648 | <reponame>swrobel/fhir
{"resourceType":"DataElement","id":"ImplementationGuide.page.type","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/ImplementationGuide.page.type","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"ImplementationGuide.page.type","path":"ImplementationGuide.page.type","short":"Kind of resource to include in the list","definition":"For constructed pages, what kind of resources to include in the list.","min":0,"max":"*","type":[{"code":"code"}],"binding":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName","valueString":"ResourceType"},{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-isCommonBinding","valueBoolean":true}],"strength":"required","description":"One of the resource types defined as part of FHIR.","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/resource-types"}}}]} | 267 |
1,338 | <reponame>Yn0ga/haiku<filename>src/apps/autoraise/settings.cpp
#include "settings.h"
#include <iostream>
#define CONF_ADDPROP(_type, _name) \
void AutoRaiseSettings::Set##_name(_type value)\
{\
_conf##_name = value;\
}\
\
_type AutoRaiseSettings::_name()\
{\
return _conf##_name;\
}\
CONF_ADDPROP(bool, Active)
CONF_ADDPROP(bigtime_t, Delay)
CONF_ADDPROP(int32, Mode)
#undef CONF_ADDPROP
AutoRaiseSettings::AutoRaiseSettings()
{
_confActive = false;
_confDelay = DEFAULT_DELAY;
_confMode = Mode_All;
BPath prefPath;
find_directory(B_USER_SETTINGS_DIRECTORY, &prefPath);
prefPath.Append(SETTINGS_FILE);
_settingsFile.SetTo(prefPath.Path(), B_READ_WRITE | B_CREATE_FILE);
if (_settingsMessage.Unflatten(&_settingsFile) == B_OK){
if (_settingsMessage.FindBool(AR_ACTIVE, &_confActive) != B_OK)
printf("AutoRaiseSettings::AutoRaiseSettings();\tFailed to load active boolean from settings file. Using default\n");
if (_settingsMessage.FindInt64(AR_DELAY, &_confDelay) != B_OK)
printf("AutoRaiseSettings::AutoRaiseSettings();\tFailed to load delay from settings file. Using default\n");
if (_settingsMessage.FindInt32(AR_MODE, &_confMode) != B_OK)
printf("AutoRaiseSettings::AutoRaiseSettings();\tFailed to load mode from settings file. Using default\n");
}
else
{
printf("AutoRaiseSettings::AutoRaiseSettings()\nUnable to open settings file (either corrupted or doesn't exist), using defaults.\n");
}
_settingsFile.Unset();
}
AutoRaiseSettings::~AutoRaiseSettings()
{
BPath prefPath;
find_directory(B_USER_SETTINGS_DIRECTORY, &prefPath);
prefPath.Append(SETTINGS_FILE);
//clobber existing settings and write in new ones
_settingsFile.SetTo(prefPath.Path(), B_READ_WRITE | B_ERASE_FILE);
//empty message and refill it with whatever has been set
_settingsMessage.MakeEmpty();
_settingsMessage.AddBool(AR_ACTIVE, _confActive);
_settingsMessage.AddInt64(AR_DELAY, _confDelay);
_settingsMessage.AddInt32(AR_MODE, _confMode);
//write message to settings file
if (_settingsMessage.Flatten(&_settingsFile) != B_OK)
printf("Error occurred writing settings\n");
_settingsFile.Unset();
}
| 801 |
1,602 | /* mpn_trialdiv -- find small factors of an mpn number using trial division.
Contributed to the GNU project by <NAME>.
THE FUNCTION IN THIS FILE IS INTERNAL WITH A MUTABLE INTERFACE. IT IS ONLY
SAFE TO REACH IT THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST
GUARANTEED THAT IT WILL CHANGE OR DISAPPEAR IN A FUTURE GNU MP RELEASE.
Copyright 2009, 2010, 2012, 2013 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.
or both in parallel, as here.
The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
/*
This function finds the first (smallest) factor represented in
trialdivtab.h. It does not stop the factoring effort just because it has
reached some sensible limit, such as the square root of the input number.
The caller can limit the factoring effort by passing NPRIMES. The function
will then divide until that limit, or perhaps a few primes more. A position
which only mpn_trialdiv can make sense of is returned in the WHERE
parameter. It can be used for restarting the factoring effort; the first
call should pass 0 here.
Input: 1. A non-negative number T = {tp,tn}
2. NPRIMES as described above,
3. *WHERE as described above.
Output: 1. *WHERE updated as described above.
2. Return value is non-zero if we found a factor, else zero
To get the actual prime factor, compute the mod B inverse
of the return value.
*/
#include "gmp-impl.h"
struct gmp_primes_dtab {
mp_limb_t binv;
mp_limb_t lim;
};
struct gmp_primes_ptab {
mp_limb_t ppp; /* primes, multiplied together */
mp_limb_t cps[7]; /* ppp values pre-computed for mpn_mod_1s_4p */
gmp_uint_least32_t idx:24; /* index of first primes in dtab */
gmp_uint_least32_t np :8; /* number of primes related to this entry */
};
static const struct gmp_primes_dtab gmp_primes_dtab[] =
{
#define WANT_dtab
#define P(p,inv,lim) {inv,lim}
#include "trialdivtab.h"
#undef WANT_dtab
#undef P
{0,0}
};
static const struct gmp_primes_ptab gmp_primes_ptab[] =
{
#define WANT_ptab
#include "trialdivtab.h"
#undef WANT_ptab
};
#define PTAB_LINES (sizeof (gmp_primes_ptab) / sizeof (gmp_primes_ptab[0]))
/* FIXME: We could optimize out one of the outer loop conditions if we
had a final ptab entry with a huge np field. */
mp_limb_t
mpn_trialdiv (mp_srcptr tp, mp_size_t tn, mp_size_t nprimes, int *where)
{
mp_limb_t ppp;
const mp_limb_t *cps;
const struct gmp_primes_dtab *dp;
long i, j, idx, np;
mp_limb_t r, q;
ASSERT (tn >= 1);
for (i = *where; i < PTAB_LINES; i++)
{
ppp = gmp_primes_ptab[i].ppp;
cps = gmp_primes_ptab[i].cps;
r = mpn_mod_1s_4p (tp, tn, ppp << cps[1], cps);
idx = gmp_primes_ptab[i].idx;
np = gmp_primes_ptab[i].np;
/* Check divisibility by individual primes. */
dp = &gmp_primes_dtab[idx] + np;
for (j = -np; j < 0; j++)
{
q = r * dp[j].binv;
if (q <= dp[j].lim)
{
*where = i;
return dp[j].binv;
}
}
nprimes -= np;
if (nprimes <= 0)
return 0;
}
return 0;
}
| 1,540 |
6,098 | package hex.security;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import water.AbstractH2OExtension;
import water.H2O;
import water.persist.PersistHdfs;
import water.persist.security.HdfsDelegationTokenRefresher;
import water.util.Log;
import java.io.IOException;
import java.time.Duration;
/**
* Authenticates the H2O Node to access secured Hadoop cluster in a standalone mode.
*
* This extension assumes that if Hadoop configuration is present and it has Kerberos enabled
* the user will likely want to read data from HDFS even though H2O is running in a standalone mode (not on Hadoop).
* The extension attempts to authenticate the user using an existing Kerberos ticket. This means the Kerberos ticket
* needs to be manually acquired by the user on each node before the H2O instance is started.
*
* The extension fails gracefully if the user cannot be authenticated and doesn't stop H2O start-up. The failure
* will be logged as an error.
*/
public class KerberosExtension extends AbstractH2OExtension {
public static String NAME = "KrbStandalone";
@Override
public String getExtensionName() {
return NAME;
}
@Override
public void onLocalNodeStarted() {
Configuration conf = PersistHdfs.CONF;
if (conf == null)
return; // this is theoretically possible although unlikely
if (isKerberosEnabled(conf)) {
UserGroupInformation.setConfiguration(conf);
final UserGroupInformation ugi;
if (H2O.ARGS.keytab_path != null || H2O.ARGS.principal != null) {
if (H2O.ARGS.keytab_path == null) {
throw new RuntimeException("Option keytab_path needs to be specified when option principal is given.");
}
if (H2O.ARGS.principal == null) {
throw new RuntimeException("Option principal needs to be specified when option keytab_path is given.");
}
Log.debug("Kerberos enabled in Hadoop configuration. Trying to login user from keytab.");
ugi = loginUserFromKeytab(H2O.ARGS.principal, H2O.ARGS.keytab_path);
} else {
Log.debug("Kerberos enabled in Hadoop configuration. Trying to login the (default) user.");
ugi = loginDefaultUser();
}
if (ugi != null) {
Log.info("Kerberos subsystem initialized. Using user '" + ugi.getShortUserName() + "'.");
}
if (H2O.ARGS.hdfs_token_refresh_interval != null) {
long refreshIntervalSecs = parseRefreshIntervalToSecs(H2O.ARGS.hdfs_token_refresh_interval);
Log.info("HDFS token will be refreshed every " + refreshIntervalSecs +
"s (user specified " + H2O.ARGS.hdfs_token_refresh_interval + ").");
HdfsDelegationTokenRefresher.startRefresher(conf, H2O.ARGS.principal, H2O.ARGS.keytab_path, refreshIntervalSecs);
}
} else {
Log.info("Kerberos not configured");
if (H2O.ARGS.hdfs_token_refresh_interval != null) {
Log.warn("Option hdfs_token_refresh_interval ignored because Kerberos is not configured.");
}
if (H2O.ARGS.keytab_path != null) {
Log.warn("Option keytab_path ignored because Kerberos is not configured.");
}
if (H2O.ARGS.principal != null) {
Log.warn("Option principal ignored because Kerberos is not configured.");
}
}
}
private long parseRefreshIntervalToSecs(String refreshInterval) {
try {
if (!refreshInterval.contains("P")) { // convenience - allow user to specify just "10M", instead of requiring "PT10M"
refreshInterval = "PT" + refreshInterval;
}
return Duration.parse(refreshInterval.toLowerCase()).getSeconds();
} catch (Exception e) {
throw new IllegalArgumentException("Unable to parse refresh interval, got " + refreshInterval +
". Example of correct specification '4H' (token will be refreshed every 4 hours).", e);
}
}
private UserGroupInformation loginDefaultUser() {
try {
UserGroupInformation.loginUserFromSubject(null);
return UserGroupInformation.getCurrentUser();
} catch (IOException e) {
Log.err("Kerberos initialization FAILED. Kerberos ticket needs to be acquired before starting H2O (run kinit).", e);
return null;
}
}
private static UserGroupInformation loginUserFromKeytab(String authPrincipal, String authKeytabPath) {
try {
UserGroupInformation.loginUserFromKeytab(authPrincipal, authKeytabPath);
return UserGroupInformation.getCurrentUser();
} catch (IOException e) {
throw new RuntimeException("Failed to login user " + authPrincipal + " from keytab " + authKeytabPath);
}
}
private static boolean isKerberosEnabled(Configuration conf) {
return "kerberos".equals(conf.get("hadoop.security.authentication"));
}
}
| 1,705 |
892 | <filename>advisories/unreviewed/2022/05/GHSA-gp7h-5r24-jv2w/GHSA-gp7h-5r24-jv2w.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-gp7h-5r24-jv2w",
"modified": "2022-05-13T01:36:08Z",
"published": "2022-05-13T01:36:08Z",
"aliases": [
"CVE-2017-9282"
],
"details": "An integer overflow (CWE-190) led to an out-of-bounds write (CWE-787) on a heap-allocated area, leading to heap corruption in Micro Focus VisiBroker 8.5. The feasibility of leveraging this vulnerability for further attacks was not assessed.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-9282"
},
{
"type": "WEB",
"url": "https://community.microfocus.com/microfocus/corba/visibroker_-_world_class_middleware/w/knowledge_base/29171/visibroker-8-5-service-pack-4-hotfix-3-security-fixes"
}
],
"database_specific": {
"cwe_ids": [
"CWE-190"
],
"severity": "CRITICAL",
"github_reviewed": false
}
} | 542 |
643 | <gh_stars>100-1000
package org.apache.velocity;
import org.apache.velocity.context.Context;
import java.io.Writer;
import java.util.List;
public class Template {
public void merge(Context context, Writer writer) {
}
public void merge(Context context, Writer writer, List<String> macroLibraries) {
}
}
| 104 |
2,151 | //
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// system_utils.cpp: Implementation of common functions
#include "system_utils.h"
namespace angle
{
bool PrependPathToEnvironmentVar(const char *variableName, const char *path)
{
std::string oldValue = GetEnvironmentVar(variableName);
const char *newValue = nullptr;
std::string buf;
if (oldValue.empty())
{
newValue = path;
}
else
{
buf = path;
buf += GetPathSeparator();
buf += oldValue;
newValue = buf.c_str();
}
return SetEnvironmentVar(variableName, newValue);
}
} // namespace angle
| 270 |
5,411 | // vendor/chromium/mojo/public/mojom/base/file_path.mojom-forward.h is auto generated by mojom_bindings_generator.py, do not edit
// 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.
#ifndef VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_PATH_MOJOM_FORWARD_H_
#define VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_PATH_MOJOM_FORWARD_H_
#include "mojo/public/cpp/bindings/struct_forward.h"
#include "mojo/public/interfaces/bindings/native_struct.mojom-forward.h"
namespace mojo_base {
namespace mojom {
class FilePathDataView;
class FilePath;
using FilePathPtr = mojo::StructPtr<FilePath>;
} // namespace mojom
} // namespace mojo_base
#include "base/files/file_path.h"
#endif // VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_PATH_MOJOM_FORWARD_H_ | 337 |
679 | /*
* (C) 1988, 1989 by Adobe Systems Incorporated. All rights reserved.
*
* This file may be freely copied and redistributed as long as:
* 1) This entire notice continues to be included in the file,
* 2) If the file has been modified in any way, a notice of such
* modification is conspicuously indicated.
*
* PostScript, Display PostScript, and Adobe are registered trademarks of
* Adobe Systems Incorporated.
*
* ************************************************************************
* THE INFORMATION BELOW IS FURNISHED AS IS, IS SUBJECT TO CHANGE WITHOUT
* NOTICE, AND SHOULD NOT BE CONSTRUED AS A COMMITMENT BY ADOBE SYSTEMS
* INCORPORATED. ADOBE SYSTEMS INCORPORATED ASSUMES NO RESPONSIBILITY OR
* LIABILITY FOR ANY ERRORS OR INACCURACIES, MAKES NO WARRANTY OF ANY
* KIND (EXPRESS, IMPLIED OR STATUTORY) WITH RESPECT TO THIS INFORMATION,
* AND EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR PARTICULAR PURPOSES AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
* ************************************************************************
*/
/*
* Changes made for OpenOffice.org
*
* 10/24/2000 pl - changed code to compile with c++-compilers
* - added namespace to avoid symbol clashes
* - replaced BOOL by bool
* - added function to free space allocated by parseFile
* 10/26/2000 pl - added additional keys
* - added ability to parse slightly broken files
* - added charwidth member to GlobalFontInfo
* 04/26/2001 pl - added OpenOffice header
* 10/19/2005 pl - changed parseFile to accept a file name instead of a stream
*/
/* ParseAFM.h
*
* This header file is used in conjunction with the parseAFM.c file.
* Together these files provide the functionality to parse Adobe Font
* Metrics files and store the information in predefined data structures.
* It is intended to work with an application program that needs font metric
* information. The program can be used as is by making a procedure call to
* parse an AFM file and have the data stored, or an application developer
* may wish to customize the code.
*
* This header file defines the data structures used as well as the key
* strings that are currently recognized by this version of the AFM parser.
* This program is based on the document "Adobe Font Metrics Files,
* Specification Version 2.0".
*
* AFM files are separated into distinct sections of different data. Because
* of this, the parseAFM program can parse a specified file to only save
* certain sections of information based on the application's needs. A record
* containing the requested information will be returned to the application.
*
* AFM files are divided into five sections of data:
* 1) The Global Font Information
* 2) The Character Metrics Information
* 3) The Track Kerning Data
* 4) The Pair-Wise Kerning Data
* 5) The Composite Character Data
*
* Basically, the application can request any of these sections independent
* of what other sections are requested. In addition, in recognizing that
* many applications will want ONLY the x-width of characters and not all
* of the other character metrics information, there is a way to receive
* only the width information so as not to pay the storage cost for the
* unwanted data. An application should never request both the
* "quick and dirty" char metrics (widths only) and the Character Metrics
* Information since the Character Metrics Information will contain all
* of the character widths as well.
*
* There is a procedure in parseAFM.c, called parseFile, that can be
* called from any application wishing to get information from the AFM File.
* This procedure expects 3 parameters: a vaild file descriptor, a pointer
* to a (FontInfo *) variable (for which space will be allocated and then
* will be filled in with the data requested), and a mask specifying
* which data from the AFM File should be saved in the FontInfo structure.
*
* The flags that can be used to set the appropriate mask are defined below.
* In addition, several commonly used masks have already been defined.
*
* History:
* original: DSM Thu Oct 20 17:39:59 PDT 1988
* modified: DSM Mon Jul 3 14:17:50 PDT 1989
* - added 'storageProblem' return code
* - fixed typos
*/
#include <stdio.h>
namespace psp {
/* your basic constants */
#define EOL '\n' /* end-of-line indicator */
#define MAX_NAME 4096 /* max length for identifiers */
#define FLAGS int
/* Flags that can be AND'ed together to specify exactly what
* information from the AFM file should be saved.
*/
#define P_G 0x01 /* 0000 0001 */ /* Global Font Info */
#define P_W 0x02 /* 0000 0010 */ /* Character Widths ONLY */
#define P_M 0x06 /* 0000 0110 */ /* All Char Metric Info */
#define P_P 0x08 /* 0000 1000 */ /* Pair Kerning Info */
#define P_T 0x10 /* 0001 0000 */ /* Track Kerning Info */
#define P_C 0x20 /* 0010 0000 */ /* Composite Char Info */
/* Commonly used flags
*/
#define P_GW (P_G | P_W)
#define P_GM (P_G | P_M)
#define P_GMP (P_G | P_M | P_P)
#define P_GMK (P_G | P_M | P_P | P_T)
#define P_ALL (P_G | P_M | P_P | P_T | P_C)
/* Possible return codes from the parseFile procedure.
*
* ok means there were no problems parsing the file.
*
* parseError means that there was some kind of parsing error, but the
* parser went on. This could include problems like the count for any given
* section does not add up to how many entries there actually were, or
* there was a key that was not recognized. The return record may contain
* vaild data or it may not.
*
* earlyEOF means that an End of File was encountered before expected. This
* may mean that the AFM file had been truncated, or improperly formed.
*
* storageProblem means that there were problems allocating storage for
* the data structures that would have contained the AFM data.
*/
enum afmError { ok = 0, parseError = -1, earlyEOF = -2, storageProblem = -3 };
/************************* TYPES *********************************/
/* Below are all of the data structure definitions. These structures
* try to map as closely as possible to grouping and naming of data
* in the AFM Files.
*/
/* Bounding box definition. Used for the Font BBox as well as the
* Character BBox.
*/
typedef struct
{
int llx; /* lower left x-position */
int lly; /* lower left y-position */
int urx; /* upper right x-position */
int ury; /* upper right y-position */
} BBox;
/* Global Font information.
* The key that each field is associated with is in comments. For an
* explanation about each key and its value please refer to the AFM
* documentation (full title & version given above).
*/
typedef struct
{
char *afmVersion; /* key: StartFontMetrics */
char *fontName; /* key: FontName */
char *fullName; /* key: FullName */
char *familyName; /* key: FamilyName */
char *weight; /* key: Weight */
float italicAngle; /* key: ItalicAngle */
bool isFixedPitch; /* key: IsFixedPitch */
BBox fontBBox; /* key: FontBBox */
int underlinePosition; /* key: UnderlinePosition */
int underlineThickness; /* key: UnderlineThickness */
char *version; /* key: Version */
char *notice; /* key: Notice */
char *encodingScheme; /* key: EncodingScheme */
int capHeight; /* key: CapHeight */
int xHeight; /* key: XHeight */
int ascender; /* key: Ascender */
int descender; /* key: Descender */
int charwidth; /* key: CharWidth */
} GlobalFontInfo;
/* Ligature definition is a linked list since any character can have
* any number of ligatures.
*/
typedef struct _t_ligature
{
char *succ, *lig;
struct _t_ligature *next;
} Ligature;
/* Character Metric Information. This structure is used only if ALL
* character metric information is requested. If only the character
* widths is requested, then only an array of the character x-widths
* is returned.
*
* The key that each field is associated with is in comments. For an
* explanation about each key and its value please refer to the
* Character Metrics section of the AFM documentation (full title
* & version given above).
*/
typedef struct
{
int code, /* key: C */
wx, /* key: WX */
w0x, /* key: W0X */
wy; /* together wx and wy are associated with key: W */
char *name; /* key: N */
BBox charBBox; /* key: B */
Ligature *ligs; /* key: L (linked list; not a fixed number of Ls */
} CharMetricInfo;
/* Track kerning data structure.
* The fields of this record are the five values associated with every
* TrackKern entry.
*
* For an explanation about each value please refer to the
* Track Kerning section of the AFM documentation (full title
* & version given above).
*/
typedef struct
{
int degree;
float minPtSize,
minKernAmt,
maxPtSize,
maxKernAmt;
} TrackKernData;
/* Pair Kerning data structure.
* The fields of this record are the four values associated with every
* KP entry. For KPX entries, the yamt will be zero.
*
* For an explanation about each value please refer to the
* Pair Kerning section of the AFM documentation (full title
* & version given above).
*/
typedef struct
{
char *name1;
char *name2;
int xamt,
yamt;
} PairKernData;
/* PCC is a piece of a composite character. This is a sub structure of a
* compCharData described below.
* These fields will be filled in with the values from the key PCC.
*
* For an explanation about each key and its value please refer to the
* Composite Character section of the AFM documentation (full title
* & version given above).
*/
typedef struct
{
char *pccName;
int deltax,
deltay;
} Pcc;
/* Composite Character Information data structure.
* The fields ccName and numOfPieces are filled with the values associated
* with the key CC. The field pieces points to an array (size = numOfPieces)
* of information about each of the parts of the composite character. That
* array is filled in with the values from the key PCC.
*
* For an explanation about each key and its value please refer to the
* Composite Character section of the AFM documentation (full title
* & version given above).
*/
typedef struct
{
char *ccName;
int numOfPieces;
Pcc *pieces;
} CompCharData;
/* FontInfo
* Record type containing pointers to all of the other data
* structures containing information about a font.
* A a record of this type is filled with data by the
* parseFile function.
*/
typedef struct
{
GlobalFontInfo *gfi; /* ptr to a GlobalFontInfo record */
int *cwi; /* ptr to 256 element array of just char widths */
int numOfChars; /* number of entries in char metrics array */
CharMetricInfo *cmi; /* ptr to char metrics array */
int numOfTracks; /* number to entries in track kerning array */
TrackKernData *tkd; /* ptr to track kerning array */
int numOfPairs; /* number to entries in pair kerning array */
PairKernData *pkd; /* ptr to pair kerning array */
int numOfComps; /* number to entries in comp char array */
CompCharData *ccd; /* ptr to comp char array */
} FontInfo;
/************************* PROCEDURES ****************************/
/* Call this procedure to do the grunt work of parsing an AFM file.
*
* "fp" should be a valid file pointer to an AFM file.
*
* "fi" is a pointer to a pointer to a FontInfo record structure
* (defined above). Storage for the FontInfo structure will be
* allocated in parseFile and the structure will be filled in
* with the requested data from the AFM File.
*
* "flags" is a mask with bits set representing what data should
* be saved. Defined above are valid flags that can be used to set
* the mask, as well as a few commonly used masks.
*
* The possible return codes from parseFile are defined above.
*/
int parseFile( const char* pFilename, FontInfo **fi, FLAGS flags );
void freeFontInfo(FontInfo *fi);
} // namespace
| 3,878 |
1,808 | import hyperion, time
from random import randint
#get args
rotationTime = float(hyperion.args.get('rotationTime', 4))
marginPos = float(hyperion.args.get('margin-pos', 2))
# define pacman
pacman = bytearray((255, 255, 0))
# define ghosts
redGuy = bytearray((255, 0, 0))
pinkGuy = bytearray((255, 184, 255))
blueGuy = bytearray((0, 255, 255))
slowGuy = bytearray((255, 184, 81))
light = bytearray((255, 184, 174))
background = bytearray((0, 0, 0))
#helper
posPac = 1
diffPac = 6*marginPos
diffGuys = 3*marginPos
sleepTime = max(0.02,rotationTime/hyperion.ledCount)
posPinkGuy = posPac + diffPac
posBlueGuy = posPinkGuy + diffGuys
posSlowGuy = posBlueGuy + diffGuys
posRedGuy = posSlowGuy + diffGuys
# initialize the led data
ledDataEscape = bytearray()
for i in range(hyperion.ledCount):
if i == 1:
ledDataEscape += pacman
elif i == posPinkGuy:
ledDataEscape += pinkGuy
elif i == posBlueGuy:
ledDataEscape += blueGuy
elif i == posSlowGuy:
ledDataEscape += slowGuy
elif i == posRedGuy:
ledDataEscape += redGuy
else:
ledDataEscape += background
ledDataChase = bytearray()
for i in range(hyperion.ledCount):
if i == 1:
ledDataChase += pacman
elif i in [posPinkGuy, posBlueGuy, posSlowGuy, posRedGuy]:
ledDataChase += bytearray((33, 33, 255))
else:
ledDataChase += background
# increment = 3, because LED-Color is defined by 3 Bytes
increment = 3
def shiftLED(ledData, increment, limit, lightPos=None):
state = 0
while state < limit and not hyperion.abort():
ledData = ledData[increment:] + ledData[:increment]
if (lightPos):
tmp = ledData[lightPos]
ledData[lightPos] = light
hyperion.setColor(ledData)
if (lightPos):
ledData[lightPos] = tmp
time.sleep(sleepTime)
state += 1
# start the write data loop
while not hyperion.abort():
# escape mode
ledData = ledDataEscape
shiftLED(ledData, increment, hyperion.ledCount)
random = randint(10,hyperion.ledCount)
# escape mode + power pellet
s = slice(3*random, 3*random+3)
shiftLED(ledData, increment, hyperion.ledCount - random, s)
# chase mode
shift = 3*(hyperion.ledCount - random)
ledData = ledDataChase[shift:]+ledDataChase[:shift]
shiftLED(ledData, -increment, 2*hyperion.ledCount-random)
time.sleep(sleepTime)
| 852 |
348 | {"nom":"Nostang","circ":"2ème circonscription","dpt":"Morbihan","inscrits":1147,"abs":652,"votants":495,"blancs":71,"nuls":26,"exp":398,"res":[{"nuance":"DIV","nom":"M. <NAME>","voix":218},{"nuance":"LR","nom":"M. <NAME>","voix":180}]} | 95 |
3,095 | /*
* Copyright (C) 2014 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pedrovgs.problem35;
import java.util.LinkedList;
import java.util.List;
/**
* Given an array of strings, can you write a method to return return just words that matches with
* a pattern containing the "*" regular expression.
*
* @author <NAME>.
*/
public class AsteriskRegularExpression {
/**
* Combination of iterative and recursive approaches to resolve this problem. The complexity
* order in time terms is O(N*M) where N is the number of elements in the input array and M the
* size of the word in the array. In space terms, the complexity order of this algorithm is O(N)
* because we are using an additional data structure to store the result.
*/
public String[] evaluate(String[] words, String pattern) {
if (words == null || pattern == null) {
throw new IllegalArgumentException("You can't use null instances as input.");
}
List<String> result = new LinkedList<String>();
for (String word : words) {
if (matchAsteriskRegularExpression(word, pattern)) {
result.add(word);
}
}
return result.toArray(new String[result.size()]);
}
/**
* The complexity order of this algorithm is more than O(N) but I don't know how to calculate it
* using this recursive version. Is O(N) approximately.
*/
private static boolean matchAsteriskRegularExpression(String word, String pattern) {
if (word.isEmpty() && pattern.isEmpty()) {
return true;
} else if (word.isEmpty() || pattern.isEmpty()) {
return false;
} else if (pattern.charAt(0) == '*') {
boolean matchRestOfWord = matchAsteriskRegularExpression(word.substring(1), pattern);
boolean matchRestOfPattern = matchAsteriskRegularExpression(word, pattern.substring(1));
return matchRestOfWord || matchRestOfPattern;
} else {
boolean partialMatch = word.charAt(0) == pattern.charAt(0);
return partialMatch && matchAsteriskRegularExpression(word.substring(1),
pattern.substring(1));
}
}
}
| 799 |
1,473 | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/unix/private/pipestream.h
// Purpose: Unix wxPipeInputStream and wxPipeOutputStream declarations
// Author: <NAME>
// Created: 2013-06-08 (extracted from wx/unix/pipe.h)
// Copyright: (c) 2013 <NAME> <<EMAIL>>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_UNIX_PRIVATE_PIPESTREAM_H_
#define _WX_UNIX_PRIVATE_PIPESTREAM_H_
#include "wx/wfstream.h"
class wxPipeInputStream : public wxFileInputStream
{
public:
wxEXPLICIT wxPipeInputStream(int fd) : wxFileInputStream(fd) { }
// return true if the pipe is still opened
bool IsOpened() const { return !Eof(); }
// return true if we have anything to read, don't block
virtual bool CanRead() const;
};
class wxPipeOutputStream : public wxFileOutputStream
{
public:
wxPipeOutputStream(int fd) : wxFileOutputStream(fd) { }
// Override the base class version to ignore "pipe full" errors: this is
// not an error for this class.
size_t OnSysWrite(const void *buffer, size_t size);
};
#endif // _WX_UNIX_PRIVATE_PIPESTREAM_H_
| 425 |
7,766 | package com.springboot.cloud.gateway.filter;
import com.springboot.cloud.gateway.config.SwaggerProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//@Component
@Slf4j
public class SwaggerHeaderFilter implements GlobalFilter, Ordered {
private static final String HEADER_NAME = "X-Forwarded-Prefix";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
return chain.filter(exchange);
}
String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
log.info("basePath: {}", basePath);
ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
return chain.filter(newExchange);
}
@Override
public int getOrder() {
return -200;
}
} | 504 |
933 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/traced/probes/ftrace/event_info_constants.h"
namespace perfetto {
using protozero::proto_utils::ProtoSchemaType;
namespace {
Field StaticField(const char* ftrace_name,
uint32_t proto_field_id,
ProtoSchemaType proto_field_type) {
Field field{};
field.ftrace_name = ftrace_name;
field.proto_field_id = proto_field_id;
field.proto_field_type = proto_field_type;
return field;
}
} // namespace
std::vector<Field> GetStaticCommonFieldsInfo() {
std::vector<Field> fields;
fields.push_back(StaticField("common_pid", 2, ProtoSchemaType::kInt32));
return fields;
}
bool SetTranslationStrategy(FtraceFieldType ftrace,
ProtoSchemaType proto,
TranslationStrategy* out) {
if (ftrace == kFtraceCommonPid32 && proto == ProtoSchemaType::kInt32) {
*out = kCommonPid32ToInt32;
} else if (ftrace == kFtraceCommonPid32 && proto == ProtoSchemaType::kInt64) {
*out = kCommonPid32ToInt64;
} else if (ftrace == kFtraceInode32 && proto == ProtoSchemaType::kUint64) {
*out = kInode32ToUint64;
} else if (ftrace == kFtraceInode64 && proto == ProtoSchemaType::kUint64) {
*out = kInode64ToUint64;
} else if (ftrace == kFtracePid32 && proto == ProtoSchemaType::kInt32) {
*out = kPid32ToInt32;
} else if (ftrace == kFtracePid32 && proto == ProtoSchemaType::kInt64) {
*out = kPid32ToInt64;
} else if (ftrace == kFtraceDevId32 && proto == ProtoSchemaType::kUint64) {
*out = kDevId32ToUint64;
} else if (ftrace == kFtraceDevId64 && proto == ProtoSchemaType::kUint64) {
*out = kDevId64ToUint64;
} else if (ftrace == kFtraceUint8 && proto == ProtoSchemaType::kUint32) {
*out = kUint8ToUint32;
} else if (ftrace == kFtraceUint8 && proto == ProtoSchemaType::kUint64) {
*out = kUint8ToUint64;
} else if (ftrace == kFtraceUint16 && proto == ProtoSchemaType::kUint32) {
*out = kUint16ToUint32;
} else if (ftrace == kFtraceUint16 && proto == ProtoSchemaType::kUint64) {
*out = kUint16ToUint64;
} else if (ftrace == kFtraceUint32 && proto == ProtoSchemaType::kUint32) {
*out = kUint32ToUint32;
} else if (ftrace == kFtraceUint32 && proto == ProtoSchemaType::kUint64) {
*out = kUint32ToUint64;
} else if (ftrace == kFtraceUint64 && proto == ProtoSchemaType::kUint64) {
*out = kUint64ToUint64;
} else if (ftrace == kFtraceInt8 && proto == ProtoSchemaType::kInt32) {
*out = kInt8ToInt32;
} else if (ftrace == kFtraceInt8 && proto == ProtoSchemaType::kInt64) {
*out = kInt8ToInt64;
} else if (ftrace == kFtraceInt16 && proto == ProtoSchemaType::kInt32) {
*out = kInt16ToInt32;
} else if (ftrace == kFtraceInt16 && proto == ProtoSchemaType::kInt64) {
*out = kInt16ToInt64;
} else if (ftrace == kFtraceInt32 && proto == ProtoSchemaType::kInt32) {
*out = kInt32ToInt32;
} else if (ftrace == kFtraceInt32 && proto == ProtoSchemaType::kInt64) {
*out = kInt32ToInt64;
} else if (ftrace == kFtraceInt64 && proto == ProtoSchemaType::kInt64) {
*out = kInt64ToInt64;
} else if (ftrace == kFtraceFixedCString &&
proto == ProtoSchemaType::kString) {
*out = kFixedCStringToString;
} else if (ftrace == kFtraceCString && proto == ProtoSchemaType::kString) {
*out = kCStringToString;
} else if (ftrace == kFtraceStringPtr && proto == ProtoSchemaType::kString) {
*out = kStringPtrToString;
} else if (ftrace == kFtraceBool && proto == ProtoSchemaType::kUint32) {
*out = kBoolToUint32;
} else if (ftrace == kFtraceBool && proto == ProtoSchemaType::kUint64) {
*out = kBoolToUint64;
} else if (ftrace == kFtraceDataLoc && proto == ProtoSchemaType::kString) {
*out = kDataLocToString;
} else if (ftrace == kFtraceSymAddr64 && proto == ProtoSchemaType::kUint64) {
*out = kFtraceSymAddr64ToUint64;
} else {
PERFETTO_DLOG("No translation strategy for '%s' -> '%s'", ToString(ftrace),
ProtoSchemaToString(proto));
return false;
}
return true;
}
} // namespace perfetto
| 1,845 |
473 | <reponame>pingjuiliao/cb-multios<filename>challenges/FaceMag/src/stickyposts.c
/*
Author: <NAME> <<EMAIL>>
Copyright (c) 2016 Cromulence LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "libcgc.h"
#include "cgc_stdlib.h"
#include "cgc_service.h"
#include "cgc_filesystem.h"
#include "cgc_stdio.h"
#include "cgc_string.h"
#include "cgc_input.h"
#include "cgc_malloc.h"
int cgc_sendStickPost( unsigned int postID ) {
fileHandleType fh;
int retcode;
unsigned char posterName[REALNAME_LEN+1];
unsigned char thePost[MAXPOST_LEN+1];
unsigned int count;
int i;
if ( postID > 15 ) {
return -1;
}
// this is a memory mapped file to the magic page of data
fh = cgc_openFile( "sticky.posts", ROOT_ID );
if ( fh < 0 ) {
cgc_printf("unable to open sticky posts\n");
return -1;
}
// each post is 160 bytes in size, jump to the offset of the post we want
cgc_fileReadPosition( fh, postID * 160 );
if (cgc_readFile( fh, (void *)posterName, REALNAME_LEN, 0, &count, ROOT_ID ) != 0) {
cgc_printf("error reading sticky post\n");
return -1;
}
if (count != REALNAME_LEN) {
cgc_printf("Error reading data for sticky post\n");
return -1;
}
posterName[REALNAME_LEN] = 0;
if ( cgc_readFile( fh, (void *)thePost, MAXPOST_LEN, 0, &count, ROOT_ID ) != 0 ) {
cgc_printf("error reading sticky post\n");
return -1;
}
if (count != MAXPOST_LEN) {
cgc_printf("Error reading data for sticky post\n");
return -1;
}
thePost[MAXPOST_LEN] = 0;
for (i=0; i < REALNAME_LEN; ++ i)
posterName[i] = (posterName[i] % 26) + 'A';
for (i=0; i < MAXPOST_LEN; ++ i)
thePost[i] = (thePost[i] % 26) + 'A';
count = REALNAME_LEN;
cgc_sendResponse( (void *)&count, sizeof(int) );
cgc_sendResponse( posterName, count );
count = MAXPOST_LEN;
cgc_sendResponse( (void *)&count, sizeof(int) );
cgc_sendResponse( thePost, count );
cgc_closeFile( fh );
return 0;
}
| 1,036 |
831 | /*
* Copyright (C) 2020 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.naveditor.dialogs;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ui.components.JBLabel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
@VisibleForTesting
public class AddArgumentDialogUI {
JPanel myContentPanel;
JCheckBox myNullableCheckBox;
JTextField myNameTextField;
JPanel myDefaultValuePanel;
JComboBox<String> myDefaultValueComboBox;
JTextField myDefaultValueTextField;
JBLabel myNullableLabel;
JComboBox<AddArgumentDialog.Type> myTypeComboBox;
JLabel myArrayLabel;
JCheckBox myArrayCheckBox;
}
| 402 |
988 | <gh_stars>100-1000
//------------------------------------------------------------------------------
// GB_iso_reduce_worker: reduce n entries, all equal to a, to the scalar s
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Some built-in monoids could be done in O(1) time, but this takes at most
// O(log (n)) time which is fast enough, even if n = 2^60, and it works for all
// monoids including user-defined ones.
#include "GB_reduce.h"
void GB_iso_reduce_worker
(
GB_void *restrict s, // output scalar
GxB_binary_function freduce, // reduction function
GB_void *restrict a, // iso value of A
uint64_t n, // number of entries in A to reduce
size_t zsize // size of s and a
)
{
if (n == 1)
{
memcpy (s, a, zsize) ;
}
else
{
// reduce floor (n/2) entries to the scalar s
GB_iso_reduce_worker (s, freduce, a, n/2, zsize) ;
// s = freduce (s, s)
freduce (s, s, s) ;
// if n is even, s is now the reduction of 2*floor(n/2) == n entries.
// if n is odd, s is now the reduction of 2*floor(n/2) == n-1 entries.
if (n & 1)
{
// n is odd, so add more more entry with s = freduce (s, a)
freduce (s, s, a) ;
}
}
}
| 633 |
734 | package com.cheikh.lazywaimai.ui.adapter;
import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import com.cheikh.lazywaimai.R;
import com.cheikh.lazywaimai.model.ShoppingCart;
import com.cheikh.lazywaimai.model.bean.Product;
import com.cheikh.lazywaimai.model.bean.ProductCategory;
import com.cheikh.lazywaimai.util.CollectionUtil;
import com.cheikh.lazywaimai.util.StringFetcher;
import com.cheikh.lazywaimai.widget.PicassoImageView;
import com.cheikh.lazywaimai.widget.ProperRatingBar;
import com.cheikh.lazywaimai.widget.ShoppingCountView;
import za.co.immedia.pinnedheaderlistview.SectionedBaseAdapter;
public class ProductItemAdapter extends SectionedBaseAdapter {
private LayoutInflater mInflater;
private List<ProductCategory> mCategories;
private View mAnimTargetView;
public ProductItemAdapter(Activity activity) {
mInflater = LayoutInflater.from(activity);
}
public void setAnimTargetView(View animTargetView) {
mAnimTargetView = animTargetView;
}
public void setItems(List<ProductCategory> categories) {
mCategories = categories;
notifyDataSetChanged();
}
@Override
public int getCountForSection(int section) {
if (mCategories != null) {
List<Product> products = mCategories.get(section).getProducts();
if (!CollectionUtil.isEmpty(products)) {
return products.size();
}
}
return 0;
}
@Override
public int getSectionCount() {
return mCategories != null ? mCategories.size() : 0;
}
@Override
public Product getItem(int section, int position) {
List<Product> products = mCategories.get(section).getProducts();
return products.get(position);
}
@Override
public long getItemId(int section, int position) {
return position;
}
@Override
public View getItemView(int section, int position, View convertView, ViewGroup viewGroup) {
final ItemViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.layout_product_item, null);
holder = new ItemViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ItemViewHolder) convertView.getTag();
}
Product product = getItem(section, position);
holder.photoImg.loadProductPhoto(product);
holder.nameTxt.setText(product.getName());
holder.priceTxt.setText(StringFetcher.getString(R.string.label_price, product.getPrice()));
holder.monthSalesTxt.setText(StringFetcher.getString(R.string.label_month_sales, product.getMonthSales()));
holder.rateRatingBar.setRating(product.getRate());
if (!TextUtils.isEmpty(product.getDescription())) {
holder.descriptionTxt.setVisibility(View.VISIBLE);
holder.descriptionTxt.setText(product.getDescription());
} else {
holder.descriptionTxt.setVisibility(View.GONE);
}
if (product.getLeftNum() > 0) {
final Product finalProduct = product;
int quantity = ShoppingCart.getInstance().getQuantityForProduct(finalProduct);
holder.shoppingCountView.setShoppingCount(quantity);
holder.shoppingCountView.setAnimTargetView(mAnimTargetView);
holder.shoppingCountView.setOnShoppingClickListener(new ShoppingCountView.ShoppingClickListener() {
@Override
public void onAddClick(int num) {
if (!ShoppingCart.getInstance().push(finalProduct)) {
// 添加失败则恢复数量
int oldQuantity = ShoppingCart.getInstance().getQuantityForProduct(finalProduct);
holder.shoppingCountView.setShoppingCount(oldQuantity);
showClearDialog();
}
}
@Override
public void onMinusClick(int num) {
if (!ShoppingCart.getInstance().pop(finalProduct)) {
// 减少失败则恢复数量
int oldQuantity = ShoppingCart.getInstance().getQuantityForProduct(finalProduct);
holder.shoppingCountView.setShoppingCount(oldQuantity);
}
}
});
holder.shoppingCountView.setVisibility(View.VISIBLE);
holder.leftNumTxt.setVisibility(View.GONE);
} else {
holder.leftNumTxt.setText(StringFetcher.getString(R.string.label_sold_out));
holder.leftNumTxt.setVisibility(View.VISIBLE);
holder.shoppingCountView.setVisibility(View.GONE);
}
return convertView;
}
@Override
public View getSectionHeaderView(int position, View convertView, ViewGroup viewGroup) {
HeaderViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.layout_product_header, viewGroup, false);
holder = new HeaderViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
ProductCategory productCategory = mCategories.get(position);
holder.titleTxt.setText(productCategory.getName());
if (!TextUtils.isEmpty(productCategory.getDescription())) {
holder.descText.setText(productCategory.getDescription());
holder.descText.setVisibility(View.VISIBLE);
} else {
holder.descText.setVisibility(View.GONE);
}
return convertView;
}
////////////////////////////////////////////
/// view holder ///
////////////////////////////////////////////
public static class HeaderViewHolder {
TextView titleTxt;
TextView descText;
HeaderViewHolder(View headerView) {
titleTxt = (TextView) headerView.findViewById(R.id.txt_title);
descText = (TextView) headerView.findViewById(R.id.txt_desc);
}
}
public static class ItemViewHolder {
PicassoImageView photoImg;
TextView nameTxt;
TextView priceTxt;
TextView descriptionTxt;
TextView monthSalesTxt;
ProperRatingBar rateRatingBar;
TextView leftNumTxt;
ShoppingCountView shoppingCountView;
ItemViewHolder(View itemView) {
photoImg = (PicassoImageView) itemView.findViewById(R.id.img_product_photo);
nameTxt = (TextView) itemView.findViewById(R.id.txt_product_name);
priceTxt = (TextView) itemView.findViewById(R.id.txt_product_price);
descriptionTxt = (TextView) itemView.findViewById(R.id.txt_product_description);
monthSalesTxt = (TextView) itemView.findViewById(R.id.txt_product_month_sales);
rateRatingBar = (ProperRatingBar) itemView.findViewById(R.id.rating_product_rate);
leftNumTxt = (TextView) itemView.findViewById(R.id.txt_product_left_num);
shoppingCountView = (ShoppingCountView) itemView.findViewById(R.id.shopping_count_view);
}
}
private void showClearDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mInflater.getContext());
builder.setTitle(R.string.dialog_shopping_cart_business_conflict_title);
builder.setMessage(R.string.dialog_shopping_cart_business_conflict_message);
builder.setNegativeButton(R.string.dialog_cancel, null);
builder.setPositiveButton(R.string.dialog_clear, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ShoppingCart.getInstance().clearAll();
}
});
builder.create().show();
}
} | 3,446 |
348 | {"nom":"Mont-le-Vignoble","circ":"5ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":296,"abs":116,"votants":180,"blancs":7,"nuls":1,"exp":172,"res":[{"nuance":"SOC","nom":"<NAME>","voix":114},{"nuance":"REM","nom":"<NAME>","voix":58}]} | 102 |
848 | // Copyright 2019 Xilinx Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//Host code to run the pre-processing pipeline
#include "common/xf_headers.hpp"
#include <sys/time.h>
#include <CL/cl.h>
#include "xcl2.hpp"
//Creating a class containing cl objects
extern "C"{
//PP Handle class
class PPHandle {
public:
cl::Context contxt;
cl::Kernel kernel;
cl_command_queue commands;
cl_program program;
cl_device_id device_id;
cl::Device device;
};
//Init function to Load xclbin and get cl kernel and context
int pp_kernel_init(PPHandle * &handle,
char *xclbin,
const char *kernelName,
int deviceIdx)
{
PPHandle *my_handle = new PPHandle;
handle = my_handle = (PPHandle *)my_handle;
//Enable Multiprocess mode
char mps_env[] = "XCL_MULTIPROCESS_MODE=1";
if (putenv(mps_env) != 0) {
std::cout << "putenv failed" << std::endl;
} //else
//Find xilinx device and create clContext
std::vector<cl::Device> devices = xcl::get_xil_devices();
cl::Device device = devices[deviceIdx];
cl::Context context(device);
//Load xclbin
unsigned fileBufSize;
std::string binaryFile = xclbin;
auto fileBuf = xcl::read_binary_file(binaryFile, fileBufSize);
cl::Program::Binaries bins{{fileBuf, fileBufSize}};
devices.resize(1);
//Check for device name
/* std::string dev_name ("xilinx_u200_xdma_201830_1");
if(dev_name.compare(devices[0].getInfo<CL_DEVICE_NAME>()) != 0){
std::cout << "Device Not Supported" << std::endl;
return -1;
}
*/
//Create clKernel and clProgram
cl_device_info info;
cl_int errr;
OCL_CHECK(errr,cl::Program program(context, devices, bins, NULL, &errr));
OCL_CHECK(errr,cl::Kernel krnl(program,kernelName,&errr));
my_handle->kernel = krnl;
my_handle->contxt = context;
my_handle->device = device;
if(errr == 0)
return 0;
else
return -1;
}
//pre-processing kernel execution
int preprocess(PPHandle * &handle, char *img_name, int *org_ht, int *org_wt, float *data_ptr)
{
//profiling Objects
// struct timeval start_,end_;
// struct timeval start_imread,end_imread;
// struct timeval start_fx2fl,end_fx2fl;
// double lat_ = 0.0f;
// double lat_imread = 0.0f;
// double lat_fx2fl = 0.0f;
// gettimeofday(&start_, 0);
//CV Mat to store input image and output data
cv::Mat img,result;
//Read input image
// gettimeofday(&start_imread, 0);
img = cv::imread(img_name, 1);
// gettimeofday(&end_imread, 0);
// lat_imread = (end_imread.tv_sec * 1e6 + end_imread.tv_usec) - (start_imread.tv_sec * 1e6 + start_imread.tv_usec);
// std::cout << "\n\n imread latency " << lat_imread / 1000 << "ms" << std::endl;
if(!img.data){
fprintf(stderr,"\n input image not found");
return -1;
}
int in_width,in_height;
int out_width,out_height;
in_width = img.cols;
in_height = img.rows;
*org_ht = in_height;
*org_wt = in_width;
//output image dimensions 224x224
out_height = 224;
out_width = 224;
result.create(cv::Size(224, 224),CV_32FC3);
//Params for quantization kernel
float params[9];
//Mean values
params[0] = 123.68;
params[1] = 116.78f;
params[2] = 103.94f;
// params[0] = 104.007f;
// params[1] = 116.669f;
// params[2] = 122.679f;
params[3] = params[4] = params[5] = 0.0;
int th1=255,th2=255;
int act_img_h, act_img_w;
/////////////////////////////////////// CL ///////////////////////////////////////
cl::Context context = handle->contxt;
cl::Kernel krnl = handle->kernel;
cl::Device device = handle->device;
//Buffer creation
cl::CommandQueue q(context, device,CL_QUEUE_PROFILING_ENABLE);
std::vector<cl::Memory> inBufVec, outBufVec, paramasbufvec;
cl::Buffer imageToDevice(context, CL_MEM_READ_ONLY, in_height*in_width*3);
cl::Buffer imageFromDevice(context,CL_MEM_WRITE_ONLY,out_height*out_width*3*4);
cl::Buffer paramsbuf(context, CL_MEM_READ_ONLY,9*4);
//Set kernel arguments
krnl.setArg(0, imageToDevice);
krnl.setArg(1, imageFromDevice);
krnl.setArg(2, in_height);
krnl.setArg(3, in_width);
krnl.setArg(4, out_height);
krnl.setArg(5, out_width);
krnl.setArg(6, paramsbuf);
krnl.setArg(7, th1);
krnl.setArg(8, th2);
//Copy data from host to FPGA
q.enqueueWriteBuffer(
imageToDevice,
CL_TRUE,
0,
in_height*in_width*3,
img.data);
q.enqueueWriteBuffer(
paramsbuf,
CL_TRUE,
0,
9*4,
params);
// Profiling Objects
cl_ulong start= 0;
cl_ulong end = 0;
double diff_prof = 0.0f;
cl::Event event_sp;
// Launch the kernel
q.enqueueTask(krnl,NULL,&event_sp);
clWaitForEvents(1, (const cl_event*) &event_sp);
//Copy data from device to Host
q.enqueueReadBuffer(
imageFromDevice,
CL_TRUE,
0,
out_height*out_width*3*4,
data_ptr);
// result.data);
//Profiling
// event_sp.getProfilingInfo(CL_PROFILING_COMMAND_START,&start);
// event_sp.getProfilingInfo(CL_PROFILING_COMMAND_END,&end);
// diff_prof = end-start;
// std::cout<<"kernel latency = "<<(diff_prof/1000000)<<"ms"<<std::endl;
q.finish();
/////////////////////////////////////// end of CL ///////////////////////////////////////
// gettimeofday(&end_, 0);
// lat_ = (end_.tv_sec * 1e6 + end_.tv_usec) - (start_.tv_sec * 1e6 + start_.tv_usec);
// std::cout << "\n\n Overall latency " << lat_ / 1000 << "ms" << std::endl;
return 0;
}
}
| 2,621 |
1,968 | /* See header file for license information. */
#include "tErrorLib.h"
#include <stdlib.h> /* for malloc */
#include <string.h>
#include <stdarg.h> /* for vasprintf */
#include <stdio.h> /* also for vasprintf and for printf family */
#include <stddef.h> /* size_t */
/**
* For string-only based usage, this implementation
* still expects an actual error number to be set.
* I am defining 1 as that error value. This might be changable,
* but it is untested. If you change this value, you must recompile
* the entire library. This can really be any integer except what
* TERROR_NOERROR_VALUE (in header) is set to.
*/
#define TERROR_ERROR_VALUE 1
#if defined(_WIN32) || defined(WINAPI_FAMILY)
#ifndef DONT_USE_VASPRINTF
#define DONT_USE_VASPRINTF
#endif
#endif
#ifdef DONT_USE_VASPRINTF
#define TERROR_DEFAULT_STRING_LENGTH 128
/* Visual Studio doesn't define snprintf but _snprintf */
#ifdef _MSC_VER
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
#endif
#if defined(_WIN32) && !defined(__CYGWIN32__)
#include <windows.h>
#include <winbase.h> /* For CreateMutex(), LockFile() */
static void* Internal_CreateMutex()
{
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
return (void*)CreateMutexExW(NULL, NULL, 0, SYNCHRONIZE);
#else
return (void*)CreateMutex(NULL, FALSE, NULL);
#endif
}
static void Internal_DestroyMutex(void* mutex)
{
if(NULL != mutex)
{
CloseHandle( (HANDLE)mutex );
}
}
/* This will return true if locking is successful, false if not.
*/
static int Internal_LockMutex(void* mutex)
{
return(
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
WaitForSingleObjectEx((HANDLE)mutex, INFINITE, FALSE) != WAIT_FAILED
#else
WaitForSingleObject((HANDLE)mutex, INFINITE) != WAIT_FAILED
#endif
);
}
static void Internal_UnlockMutex(void* mutex)
{
ReleaseMutex(
(HANDLE)mutex
);
}
size_t Internal_PlatformGetThreadID(void)
{
return((size_t)GetCurrentThreadId());
}
#else /* Assuming POSIX...maybe not a good assumption. */
#include <pthread.h>
static void* Internal_CreateMutex()
{
int ret_val;
pthread_mutex_t* m = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
if(NULL == m)
{
return NULL;
}
ret_val = pthread_mutex_init(m, NULL);
if(0 != ret_val)
{
free(m);
return NULL;
}
return((void*)m);
}
static void Internal_DestroyMutex(void* mutex)
{
if(NULL != mutex)
{
pthread_mutex_destroy((pthread_mutex_t*) (mutex));
free(mutex);
}
}
/* This will return true if locking is successful, false if not.
* (This is the opposite of pthread_mutex_lock which returns
* 0 for success.)
*/
static int Internal_LockMutex(void* mutex)
{
return(
pthread_mutex_lock(
(pthread_mutex_t*)mutex
) == 0
);
}
static void Internal_UnlockMutex(void* mutex)
{
pthread_mutex_unlock(
(pthread_mutex_t*)mutex
);
}
size_t Internal_PlatformGetThreadID()
{
/* Basically, we need to convert a pthread_t into an id number. */
return (size_t)pthread_self();
}
#endif
/**
* Copies a source string, potentially to a target string, and returns
* the pointer to the copied string.
* This function is a intended to be an efficient string copy function.
* It's purpose is to copy a string into a string with preallocated memory
* and avoid dynamic memory allocation if possible. If memory must
* be allocated, then the old string will be destroyed.
*
* This is only to be used where target_string was created with dynamic
* memory. This function will destroy the memory and allocate new memory
* if there is not enough space in the target string.
*
* @param target_string This is the string you would like to try
* to copy into. If there is not enough space, a new string will
* be created and the target_string will be freed. This string
* must have been created dynamically. This may be NULL if you
* wish for this function to dynamically create a new string
* for you.
*
* @param target_max_buffer_size This is a pointer that points to
* an address containing the size of the preallocated target_string.
* This size is the maximum buffer length which includes the '\\0'
* character as part of that count. This pointer may not be NULL.
* If you pass in NULL for the target_string (indicating you want
* a new string allocated for you), then the size should be set to 0.
* When the function completes, the size will be set to the new
* max buffer size of the string if the string needed to be reallocated.
*
* @param source_string This is the string you want to copy. If it's NULL,
* the target_string will have it's memory freed.
*
* @return Will return a pointer to the duplicated string. Be aware
* of several things:
* - The returned pointer address may not be the same address as the
* target string passed in (due to a possible reallocation).
* - If the pointer to the source and target string
* are the same, the pointer to the target string will be returned.
* - If the source string is NULL, the target string
* will be freed and will return NULL.
* - If an error occurs, NULL will be returned.
*
* Also note that the value at the address target_max_buffer_size points
* to will be filled with the new max buffer size for the string.
*
* Example:
* @code
*
* int main()
* {
* const char* original1 = "Hello World";
* const char* original2 = "Smaller";
* const char* original3 = "Good-Bye World";
* char* ret_val;
* char* target = NULL;
* size_t target_max_buffer_size = 0;
*
* ret_val = CopyDynamicString(target, &target_max_buffer_size, original1);
*
* if(ret_val)
* {
* fprintf(stderr, "Target is '%s' with max size = %d\n", ret_val, target_max_buffer_size);
* }
* else
* {
* fprintf(stderr, "Error in function\n");
* }
* target = ret_val;
*
* ret_val = CopyDynamicString(target, &target_max_buffer_size, original2);
* fprintf(stderr, "Target is '%s' with max size = %d\n", ret_val, target_max_buffer_size);
*
* target = ret_val; *
* ret_val = CopyDynamicString(target, &target_max_buffer_size, original3);
* fprintf(stderr, "Target is '%s' with max size = %d\n", ret_val, target_max_buffer_size);
*
* return 0;
* }
* @endcode
* This outputs:
* @code
* Target is 'Hello World' with max size = 12
* Target is 'Smaller' with max size = 12
* Target is 'Good-Bye World' with max size = 15
* @endcode
*/
static char* Internal_CopyDynamicString(char* target_string, size_t* target_max_buffer_size, const char* source_string)
{
/* If the pointers are the same, no copy is needed. */
if(source_string == target_string)
{
/* I don't feel like asserting if the sizes are the same. */
/* Return 1 instead of 0 because maybe this isn't an error?
*/
return target_string;
}
/* Make sure the size pointer is valid. */
if(NULL == target_max_buffer_size)
{
return NULL;
}
/* Yikes, if the string is NULL, should we make the target string NULL?
* For now, yes, we destroy the string. If you change this, realize that
* their is code that depends on this behavior.
*/
if(NULL == source_string)
{
*target_max_buffer_size = 0;
free(target_string);
target_string = NULL;
return NULL;
}
/* If target_string is NULL, the *target_max_buffer_size should also be 0.
* Technically, the user should set this and this would be an error,
* but I'll be nice for now. An alternate implementation might suggest
* that the size would be the desired size the user wants for a new string.
*/
if( (NULL == target_string) && (0 != *target_max_buffer_size) )
{
*target_max_buffer_size = 0;
}
/* If there is not enough preallocated memory in the target string,
* then we need to reallocate enough memory.
*/
if( *target_max_buffer_size < (strlen(source_string) + 1) )
{
*target_max_buffer_size = 0;
if(NULL != target_string)
{
free(target_string);
}
target_string = (char*)calloc( (strlen(source_string) + 1), sizeof(char) );
if(NULL == target_string)
{
return NULL;
}
*target_max_buffer_size = strlen(source_string) + 1;
}
/* At this point, there should be enough preallocated
* memory to call strncpy.
*/
strncpy(target_string, source_string, *target_max_buffer_size);
return target_string;
}
/**
* This is a structure that contains everything needed for an
* error message entry (per thread). The linked list stuff
* is fused in with it because I didn't want to write an entire
* linked list class.
*/
typedef struct TErrorMessageStructType
{
size_t threadID; /** ThreadID for associated message. */
int errorAvailable; /** 1 if an error has been set and not been checked. */
int errorNumber; /**< For the user error number. */
char* errorString; /**< For the user error message. */
size_t errorMaxStringLength; /**< Max size of string buffer including \\0. */
struct TErrorMessageStructType* nextItem; /**< Pointer to next error message in list. */
} TErrorMessage;
/**
* This is a private struct that contains all private data for an
* ErrorPool. Currently it is a linked list containing all error message
* structs for every thread.
*/
typedef struct
{
TErrorMessage* errorMessageListHead; /**< Head of the error list. */
TErrorMessage* lastErrorMessage; /**< Points to the last set element in the list for GetLastError. */
/* Mutex */
} TErrorPoolOpaqueData;
/**
* This is a private helper function that creates a new TErrorMessage
* and initializes all its values.
* @return Returns a pointer to a newly allocated and initialized
* TErrorMessage or NULL on failure.
*/
static TErrorMessage* Internal_CreateErrorMessageStructure()
{
TErrorMessage* new_message;
/* Use calloc to create a fully cleared structure,
* so I don't have to set/clear each member.
*/
new_message = (TErrorMessage*)calloc(1, sizeof(TErrorMessage));
if(NULL == new_message)
{
/* Very bad, but not sure what to do. */
return NULL;
}
new_message->errorNumber = TERROR_NOERROR_VALUE;
return new_message;
}
/**
* This is a private helper function that frees a TErrorMessage.
*
* @param err_mesg The pointer to the TErrorMessage to be freed.
*/
static void Internal_FreeErrorMessageStructure(TErrorMessage* err_mesg)
{
if(NULL == err_mesg)
{
return;
}
if(NULL != err_mesg->errorString)
{
free(err_mesg->errorString);
err_mesg->errorString = NULL;
}
err_mesg->nextItem = NULL;
free(err_mesg);
}
/**
* This is a private helper function that will search the error pool
* for the last set error message structure in the Linked list.
* If the last error message was on a different thread, the error
* data will be copied to the current thread's memory and the
* lastErrorMessage pointer will be set to the current thread's message.
* (This is because I expect this message to be marked as cleared/read.)
* This function does its own mutex locking.
*
* @param err_pool The error pool to be used.
* @return Returns the a pointer to the TErrorMessage if found,
* NULL if not found.
*/
static TErrorMessage* Internal_GetLastError(TErrorPool* err_pool)
{
size_t thread_id;
TErrorMessage* current_thread_err_mesg;
TErrorPoolOpaqueData* err_pool_data;
thread_id = Internal_PlatformGetThreadID();
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
if(NULL == err_pool_data->errorMessageListHead)
{
Internal_UnlockMutex(err_pool->mutexLock);
return NULL;
}
/* I think this is actually an assertion failure.
* I do the check here so I don't have to keep checking below.
*/
if(NULL == err_pool_data->lastErrorMessage)
{
Internal_UnlockMutex(err_pool->mutexLock);
return NULL;
}
/* We need to determine if the lastMessage pointer is pointing
* to data on the current thread. If it is we can just return it.
* Otherwise, we need to copy the message to the current thread's
* error message memory area.
* We should also update the lastMessage pointer to point
* to this message since it will likely be marked cleared once read.
*/
if(thread_id == err_pool_data->lastErrorMessage->threadID)
{
/* Not copy is needed. The last error message already
* points to the memory on the current thread.
* We can short-circuit and return.
*/
Internal_UnlockMutex(err_pool->mutexLock);
return err_pool_data->lastErrorMessage;
}
/* Sigh, I really should have a dedicated linked list structure,
* but I don't feel like writing it right now.
*/
for(current_thread_err_mesg = err_pool_data->errorMessageListHead; current_thread_err_mesg != NULL; current_thread_err_mesg = current_thread_err_mesg->nextItem)
{
/* First find the message (memory) for the current thread. */
if(thread_id == current_thread_err_mesg->threadID)
{
/* Now we need to copy the message data from the lastErrorMessage
* to this thread's message (memory).
*/
current_thread_err_mesg->errorNumber = err_pool_data->lastErrorMessage->errorNumber;
current_thread_err_mesg->errorAvailable = err_pool_data->lastErrorMessage->errorAvailable;
/* This will copy the string and set the new errorMaxStringLength as needed. */
current_thread_err_mesg->errorString = Internal_CopyDynamicString(current_thread_err_mesg->errorString, ¤t_thread_err_mesg->errorMaxStringLength, err_pool_data->lastErrorMessage->errorString);
/* Finally, change the last error message to point to
* the current thread since I expect the message to be
* marked cleared and we don't want to accidentally refetched
* the stale, uncleared entry.
*/
err_pool_data->lastErrorMessage = current_thread_err_mesg;
Internal_UnlockMutex(err_pool->mutexLock);
return current_thread_err_mesg;
}
}
Internal_UnlockMutex(err_pool->mutexLock);
return NULL;
}
/**
* This is a private helper function that will search the error pool
* for an error message structure in the Linked list (by thread ID)
* and return the pointer if found. This function does its own mutex
* locking.
* @param err_pool The error pool to be used.
* @return Returns the a pointer to the TErrorMessage if found,
* NULL if not found.
*/
static TErrorMessage* Internal_GetErrorOnCurrentThread(TErrorPool* err_pool)
{
size_t thread_id;
TErrorMessage* current_err_mesg;
TErrorPoolOpaqueData* err_pool_data;
thread_id = Internal_PlatformGetThreadID();
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
if(NULL == err_pool_data->errorMessageListHead)
{
Internal_UnlockMutex(err_pool->mutexLock);
return NULL;
}
/* Sigh, I really should have a dedicated linked list structure,
* but I don't feel like writing it right now.
*/
for(current_err_mesg = err_pool_data->errorMessageListHead; current_err_mesg != NULL; current_err_mesg = current_err_mesg->nextItem)
{
if(thread_id == current_err_mesg->threadID)
{
Internal_UnlockMutex(err_pool->mutexLock);
return current_err_mesg;
}
}
Internal_UnlockMutex(err_pool->mutexLock);
return NULL;
}
/**
* Given a specific TErrorMessage*, will set the lastErrorMessage pointer to
* the provided error message.
* This function locks.
*
* @param err_pool The error pool to be used.
* @param error_message The error message to set the lastErrorMessage pointer to
*/
static void Internal_SetLastErrorMessagePointerToErrorMessage(TErrorPool* err_pool, TErrorMessage* error_message)
{
TErrorPoolOpaqueData* err_pool_data;
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
err_pool_data->lastErrorMessage = error_message;
Internal_UnlockMutex(err_pool->mutexLock);
}
/**
* This is a private helper function that creates a new error message
* structure for the current thread.
* This currently does not check if an error already exists
* before creating a new entry. Call GetErrorOnCurrentThread first
* to make sure nothing exists or duplicate entries will be created.
* This function does its own mutex locking.
*
* @param err_pool The error pool to be used.
* @return Returns the a pointer to the TErrorMessage if found,
* NULL if there was an allocation error.
*/
static TErrorMessage* Internal_CreateErrorOnCurrentThread(TErrorPool* err_pool)
{
TErrorMessage* new_err_mesg;
TErrorPoolOpaqueData* err_pool_data;
new_err_mesg = Internal_CreateErrorMessageStructure();
if(NULL == new_err_mesg)
{
/* Serious problem, not sure what to do. */
return NULL;
}
/* Copy the thread id so we can distinguish between entries. */
new_err_mesg->threadID = Internal_PlatformGetThreadID();
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
/* Add the new message to the top of the list by making
* its next pointer point to the head of the current list.
* (A formal linked list implementation would make this feel
* less hacky.)
* This also (should) handle the case where errorMessageListHead
* is NULL.
*/
new_err_mesg->nextItem = err_pool_data->errorMessageListHead;
/* Now set the head of the list to the new message.
*/
err_pool_data->errorMessageListHead = new_err_mesg;
Internal_UnlockMutex(err_pool->mutexLock);
return new_err_mesg;
}
/**
* This is a private helper function that will clean up all the
* error message structures in the list. This function does its
* own locking.
* @param err_pool The error pool to be used.
*/
static void Internal_FreeErrorMessageList(TErrorPool* err_pool)
{
TErrorMessage* current_message = NULL;
TErrorMessage* next_message = NULL;
TErrorPoolOpaqueData* err_pool_data;
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
if(NULL == err_pool_data->errorMessageListHead)
{
Internal_UnlockMutex(err_pool->mutexLock);
return;
}
/* Sigh, I really should have a dedicated linked list structure,
* but I don't feel like writing it right now.
*/
for(current_message = err_pool_data->errorMessageListHead;
current_message != NULL;
current_message = next_message
)
{
next_message = current_message->nextItem;
Internal_FreeErrorMessageStructure(current_message);
}
err_pool_data->errorMessageListHead = NULL;
err_pool_data->lastErrorMessage = NULL;
Internal_UnlockMutex(err_pool->mutexLock);
}
/*
* API functions start below.
*
*/
void TError_DeleteEntryOnCurrentThread(TErrorPool* err_pool)
{
TErrorMessage* prev_message = NULL;
TErrorMessage* current_message = NULL;
TErrorMessage* next_message = NULL;
size_t thread_id;
TErrorPoolOpaqueData* err_pool_data;
thread_id = Internal_PlatformGetThreadID();
Internal_LockMutex(err_pool->mutexLock);
err_pool_data = err_pool->opaqueData;
if(NULL == err_pool_data->errorMessageListHead)
{
Internal_UnlockMutex(err_pool->mutexLock);
return;
}
/* Sigh, I really should have a dedicated linked list structure,
* but I don't feel like writing it right now.
*/
for(current_message = err_pool_data->errorMessageListHead;
current_message != NULL;
/* I'm not going to increment here because I
* may delete the item below which would probably
* cause bad things to happen here.
*/
/* current_message = current_message->nextItem */
)
{
next_message = current_message->nextItem;
if(thread_id == current_message->threadID)
{
/* Special case, current is only item in list:
* Both next and prev are NULL in this case.
* We should delete the item and set the errorMessageListHead
* to NULL.
*/
if((NULL == prev_message) && (NULL == next_message))
{
Internal_FreeErrorMessageStructure(current_message);
current_message = NULL;
err_pool_data->errorMessageListHead = NULL;
err_pool_data->lastErrorMessage = NULL;
}
/* Special case, current is at head:
* Prev is NULL but next is not NULL in this case.
* We should delete the item and set the errorMessageListHead
* to point to next.
* (The code for the above case would probably work for
* this case too, but for clarity, this remains.)
*/
else if(NULL == prev_message)
{
/* If the current message happened to be the last message
* set, we need to change the lastErrorMessage pointer
* so it is not dangling.
*/
if(current_message == err_pool_data->lastErrorMessage)
{
err_pool_data->lastErrorMessage = NULL;
}
Internal_FreeErrorMessageStructure(current_message);
current_message = NULL;
err_pool_data->errorMessageListHead = next_message;
}
/* Special case, current is at tail.
* Prev is not NULL, but next is NULL in this case.
* We should delete the item and set prev->next to NULL.
*/
else if(NULL == next_message)
{
/* If the current message happened to be the last message
* set, we need to change the lastErrorMessage pointer
* so it is not dangling.
*/
if(current_message == err_pool_data->lastErrorMessage)
{
err_pool_data->lastErrorMessage = NULL;
}
Internal_FreeErrorMessageStructure(current_message);
current_message = NULL;
prev_message->nextItem = NULL;
}
/* Normal case, current is somewhere in the middle of the list.
* The item should be deleted and
* the prev_message->next should connect to
* the next_message.
*/
else
{
/* If the current message happened to be the last message
* set, we need to change the lastErrorMessage pointer
* so it is not dangling.
*/
if(current_message == err_pool_data->lastErrorMessage)
{
err_pool_data->lastErrorMessage = NULL;
}
Internal_FreeErrorMessageStructure(current_message);
current_message = NULL;
prev_message->nextItem = next_message;
}
}
/* It's not this thread, so increment everything for the next loop. */
else
{
prev_message = current_message;
current_message = next_message;
}
} /* End for-loop */
Internal_UnlockMutex(err_pool->mutexLock);
}
void TError_GetLinkedVersion(TErrorVersion* ver)
{
/* Check the pointer */
if(NULL == ver)
{
/* Do nothing */
return;
}
ver->major = TERROR_MAJOR_VERSION;
ver->minor = TERROR_MINOR_VERSION;
ver->patch = TERROR_PATCH_VERSION;
}
#if 0
/* This is for global initialization, not pool initialization. */
int TError_Init()
{
/* initialize platform? */
/* initialize mutexes? */
}
#endif
TErrorPool* TError_CreateErrorPool()
{
TErrorPool* err_pool;
TErrorPoolOpaqueData* err_pool_data;
err_pool = (TErrorPool*)calloc(1, sizeof(TErrorPool));
if(NULL == err_pool)
{
/* Very bad, but not sure what to do here. */
return NULL;
}
err_pool_data = (TErrorPoolOpaqueData*)calloc(1, sizeof(TErrorPoolOpaqueData));
if(NULL == err_pool_data)
{
/* Very bad, but not sure what to do here. */
free(err_pool);
return NULL;
}
/* Create mutex */
err_pool->mutexLock = Internal_CreateMutex();
if(NULL == err_pool->mutexLock)
{
/* Very bad, but not sure what to do here. */
free(err_pool_data);
free(err_pool);
return NULL;
}
/* Attach the opaque data to the error pool. */
err_pool->opaqueData = err_pool_data;
/* The OpaqueData will hold the error message list, but it is
* allowed to be NULL for an empty list so we don't have to allocate
* it here.
*/
return err_pool;
}
/* There better not be any contention when this is called. */
void TError_FreeErrorPool(TErrorPool* err_pool)
{
if(NULL == err_pool)
{
return;
}
/* Free all the error messages for each thread.
* This locks and unlocks as it needs.
*/
Internal_FreeErrorMessageList(err_pool);
/* Free opaque data structure. */
free(err_pool->opaqueData);
/* Delete mutex after all locking functions. */
Internal_DestroyMutex(err_pool->mutexLock);
/* Free main data structure. */
free(err_pool);
}
void TError_SetError(TErrorPool* err_pool, int err_num, const char* err_str, ...)
{
va_list argp;
va_start(argp, err_str);
TError_SetErrorv(err_pool, err_num, err_str, argp);
va_end(argp);
}
void TError_SetErrorv(TErrorPool* err_pool, int err_num, const char* err_str, va_list argp)
{
TErrorMessage* error_message;
int ret_num_chars;
if(NULL == err_pool)
{
return;
}
error_message = Internal_GetErrorOnCurrentThread(err_pool);
/* If no error message was found, that means we must allocate
* a new entry for this entry.
*/
if(NULL == error_message)
{
error_message = Internal_CreateErrorOnCurrentThread(err_pool);
/* If this fails, this is bad...not sure what to do though. */
if(NULL == error_message)
{
return;
}
}
/*
* I don't think I have to lock here. The [Get|Create]ErrorOnCurrentThread
* functions lock err_pool as they need access. Here, I don't access
* err_pool (which is shared) and error_message should be unique for
* each thread so I don't think there is any contention. (Remember that
* simultaneous calls to SetError would only happen if they are in
* different threads.)
* There *might* be a problem with library calls (strncpy, calloc).
* I'm not sure if the various platforms are reentrant.
* I guess for now, I will assume they won't bite me.
*/
/* If the err_str is NULL, we need to free our current string
* for consistency. More aggressive optimizations to hold the
* memory might be considered in the future.
*/
if(NULL == err_str)
{
if(NULL != error_message->errorString)
{
free(error_message->errorString);
error_message->errorString = NULL;
error_message->errorMaxStringLength = 0;
}
}
/* Else, copy the string */
else
{
/* I am using vasprintf which is a GNU extension so it is not
* portable. However, vasprintf makes certain things possible
* which would not be otherwise, which is the reason for my
* use. The main benefit of asprintf/vasprintf is that you can
* create a string using printf style formatters without
* worrying about the buffer size. sprintf should never be
* used because of potential buffer overflows. snprintf
* is safer, but you are limited to a fixed size string
* which from time-to-time, I have exceeded unless you make
* the number really big.
* Furthermore, snprintf itself is not currently terribly portable
* because it is specified only for C99 which some compilers
* still have not have embraced.
* If you can't use the vasprintf implementation,
* you must add -DDONT_USE_VASPRINTF to your compile flags.
*/
#ifdef DONT_USE_VASPRINTF
/* This implementation uses vsnprintf instead of
* vasprintf. It is strongly recommended you use
* the vasprintf implmententation instead.
* Never use vsprintf unless you like
* buffer overflows and security exploits.
*/
/* If the string was set to NULL, we must reallocate memory first. */
if(NULL == error_message->errorString)
{
error_message->errorString = (char*)calloc(TERROR_DEFAULT_STRING_LENGTH, sizeof(char));
if(NULL == error_message->errorString)
{
/* Very bad...what should I do?
*/
error_message->errorMaxStringLength = 0;
}
else
{
error_message->errorMaxStringLength = TERROR_DEFAULT_STRING_LENGTH;
}
}
/* Because of the "Very Bad" situation directly above,
* I need to check again to make sure the string isn't NULL.
* This will let the very bad situation continue on so va_end
* can be called and the error_number still has a chance to be set.
*/
if(NULL != error_message->errorString)
{
ret_num_chars = vsnprintf(error_message->errorString,
error_message->errorMaxStringLength,
err_str,
argp
);
}
#else /* DONT_USE_VASPRINTF */
/* You might be wondering why the #ifdef logic assumes
* asprintf is available instead of requiring an explicit
* #define for that. The reason is because asprintf is the
* better option and I want you to realize that you are not
* using it. Typically, nobody knows or understands the build
* system and/or files get copied into new projects with a
* entirely new build system, so it is easy to forget to
* add a -D flag. So if you compile without asprintf,
* you are encouraged to explicitly know this.
*/
/* There may be a slight performance advantage to using snprintf
* over asprintf depending how asprintf is written. But this
* implementation will completely destroy and reallocate a
* string regardless if a string is set to NULL, so there will
* actually be no performance gains for these cases.
* (This could be optimized but some additional bookkeeping
* might be needed which might not be worth the effort and
* code clutter.)
* As for memory allocation safety, because new messages for
* different threads must be allocated dynamically, there is no
* way for this library to use purely static memory.
* So I don't believe there is anything to be gained using
* snprintf over asprintf and you lose out on arbitrary lengthed
* error messages.
* If memory allocation must be minimized, I recommend just
* using the error number interface by itself which
* will always keep the strings at NULL, and don't mess
* with the asprintf/sprintf code.
*/
if(NULL != error_message->errorString)
{
/* Need to free errorString from previous pass otherwise we leak.
* Maybe there is a smarter way to avoid the free/malloc,
* but this would probably require determining the length of the
* final string beforehand which probably implies two
* *printf calls which may or may not be better.
*/
free(error_message->errorString);
error_message->errorString = NULL;
}
ret_num_chars = vasprintf(&error_message->errorString, err_str, argp);
/* vasprintf returns -1 as an error */
if(-1 == ret_num_chars)
{
/* Very bad, but not sure what to do here. */
if(NULL != error_message->errorString)
{
free(error_message->errorString);
error_message->errorString = NULL;
error_message->errorMaxStringLength = 0;
/* Don't return here. Still need to va_end, and
* there is a chance that the err_num might work.
* Plus the availability needs to be set.
*/
}
}
/* else vasprint returns the number of characters in the string
* not including the \0 character.
*/
else
{
/* I actually don't know how much memory vasprintf allocated
* for the string. But it is at least ret_num_chars+1, so
* I will use that as my max string length (which is
* mainly used by CopyDynamicString() for efficiency
* which is becoming less used in this code).
*/
error_message->errorMaxStringLength = ret_num_chars+1;
}
#endif /* DONT_USE_VASPRINTF */
}
/* I'm allowing for a user to explicitly clear an error message by
* clearing both attributes.
*/
if((TERROR_NOERROR_VALUE == err_num) && (NULL == err_str))
{
error_message->errorNumber = TERROR_NOERROR_VALUE;
error_message->errorAvailable = 0;
}
/* This is the normal case, copy the error number
* and mark the error as unread.
*/
else
{
error_message->errorNumber = err_num;
error_message->errorAvailable = 1;
}
/* Now that the data is set, we also want to denote that this
* thread is the last error message. We need to lock for this
* since the lastError pointer is shared across threads.
*/
Internal_SetLastErrorMessagePointerToErrorMessage(err_pool, error_message);
}
void TError_SetErrorNoFormat(TErrorPool* err_pool, int err_num, const char* err_str)
{
TErrorMessage* error_message;
if(NULL == err_pool)
{
return;
}
error_message = Internal_GetErrorOnCurrentThread(err_pool);
/* If no error message was found, that means we must allocate
* a new entry for this entry.
*/
if(NULL == error_message)
{
error_message = Internal_CreateErrorOnCurrentThread(err_pool);
/* If this fails, this is bad...not sure what to do though. */
if(NULL == error_message)
{
return;
}
}
/*
* I don't think I have to lock here. The [Get|Create]ErrorOnCurrentThread
* functions lock err_pool as they need access. Here, I don't access
* err_pool (which is shared) and error_message should be unique for
* each thread so I don't think there is any contention. (Remember that
* simultaneous calls to SetError would only happen if they are in
* different threads.)
* There *might* be a problem with library calls (strncpy, calloc).
* I'm not sure if the various platforms are reentrant.
* I guess for now, I will assume they won't bite me.
*/
error_message->errorNumber = err_num;
/* This will copy the string and set the new errorMaxStringLength as needed. */
error_message->errorString = Internal_CopyDynamicString(error_message->errorString, &error_message->errorMaxStringLength, err_str);
/* I'm allowing for a user to explicitly clear an error message by
* clearing both attributes.
*/
if((TERROR_NOERROR_VALUE == err_num) && (NULL == err_str))
{
error_message->errorAvailable = 0;
}
else
{
error_message->errorAvailable = 1;
}
/* Now that the data is set, we also want to denote that this
* thread is the last error message. We need to lock for this
* since the lastError pointer is shared across threads.
*/
Internal_SetLastErrorMessagePointerToErrorMessage(err_pool, error_message);
}
void TError_SetErrorNum(TErrorPool* err_pool, int err_num)
{
TError_SetErrorNoFormat(err_pool, err_num, NULL);
}
void TError_SetErrorStr(TErrorPool* err_pool, const char* err_str, ...)
{
va_list argp;
va_start(argp, err_str);
if(NULL == err_str)
{
TError_SetErrorv(err_pool, TERROR_NOERROR_VALUE, err_str, argp);
}
else
{
TError_SetErrorv(err_pool, TERROR_ERROR_VALUE, err_str, argp);
}
va_end(argp);
}
void TError_SetErrorStrv(TErrorPool* err_pool, const char* err_str, va_list argp)
{
if(NULL == err_str)
{
TError_SetErrorv(err_pool, TERROR_NOERROR_VALUE, err_str, argp);
}
else
{
TError_SetErrorv(err_pool, TERROR_ERROR_VALUE, err_str, argp);
}
}
/* If a NULL string is set, then it is presumed no error actually occurred
* and this is a reset. So the err_num will be implicitly set to 0. Otherwise
* the err_num will be set to 1 (for internal consistency and conventions).
*/
void TError_SetErrorStrNoFormat(TErrorPool* err_pool, const char* err_str)
{
if(NULL == err_str)
{
TError_SetErrorNoFormat(err_pool, TERROR_NOERROR_VALUE, err_str);
}
else
{
TError_SetErrorNoFormat(err_pool, TERROR_ERROR_VALUE, err_str);
}
}
/* This currently returns 0 as a "no error found" value.
* This could potentially conflict with a user. For now, users
* shouldn't use 0 to represent an error. If this becomes a
* problem, we could introduce a magic number like -999999 and
* define TERROR_NO_ERROR_FOUND.
*/
int TError_GetErrorNumOnCurrentThread(TErrorPool* err_pool)
{
TErrorMessage* error_message;
error_message = Internal_GetErrorOnCurrentThread(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return 0;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return 0;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
return error_message->errorNumber;
}
const char* TError_GetErrorStrOnCurrentThread(TErrorPool* err_pool)
{
TErrorMessage* error_message;
error_message = Internal_GetErrorOnCurrentThread(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return 0;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return 0;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
return error_message->errorString;
}
TErrorStatus TError_GetErrorOnCurrentThread(TErrorPool* err_pool)
{
TErrorMessage* error_message;
TErrorStatus error_container;
error_container.errorNumber = TERROR_NOERROR_VALUE;
error_container.errorString = NULL;
error_message = Internal_GetErrorOnCurrentThread(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return error_container;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return error_container;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
error_container.errorNumber = error_message->errorNumber;
error_container.errorString = error_message->errorString;
return error_container;
}
/* This function is for alternative usage where you just want one error
* for all threads. The backend will still work the same, but when you
* call this function, it will look up the last set error, copy (with locking)
* the last error to the current thread's memory, and return the object.
* As always, since the returned object is only accessed on this thread, you
* don't have to worry about locking.
*/
TErrorStatus TError_GetLastError(TErrorPool* err_pool)
{
// Lock the error pool to get the lastMessage pointer
// if the lastMessage pointer is pointing to data on the current thread,
// we can just return it.
// Otherwise, we need to copy the message
TErrorMessage* error_message;
TErrorStatus error_container;
error_container.errorNumber = TERROR_NOERROR_VALUE;
error_container.errorString = NULL;
error_message = Internal_GetLastError(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return error_container;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return error_container;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
error_container.errorNumber = error_message->errorNumber;
error_container.errorString = error_message->errorString;
return error_container;
}
/* This currently returns 0 as a "no error found" value.
* This could potentially conflict with a user. For now, users
* shouldn't use 0 to represent an error. If this becomes a
* problem, we could introduce a magic number like -999999 and
* define TERROR_NO_ERROR_FOUND.
*/
int TError_GetLastErrorNum(TErrorPool* err_pool)
{
TErrorMessage* error_message;
error_message = Internal_GetLastError(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return 0;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return 0;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
return error_message->errorNumber;
}
const char* TError_GetLastErrorStr(TErrorPool* err_pool)
{
TErrorMessage* error_message;
error_message = Internal_GetLastError(err_pool);
/* If no error message was found for the thread. */
if(NULL == error_message)
{
return 0;
}
/* If an error message was found for the thread, but
* it has already been read/cleared.
*/
if(0 == error_message->errorAvailable)
{
return 0;
}
/* We found a legitimate error message, clear it and return it. */
error_message->errorAvailable = 0;
return error_message->errorString;
}
| 13,089 |
1,037 | package com.codekk.java.test.dynamicproxy;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.codekk.java.test.dynamicproxy.util.ProxyUtils;
/**
* Dynamic Proxy Demo
*
* @author <EMAIL>
*/
public class Main {
public static void main(String[] args) {
TimingInvocationHandler timingInvocationHandler = new TimingInvocationHandler(new OperateImpl());
Operate operate = (Operate)(Proxy.newProxyInstance(Operate.class.getClassLoader(), new Class[] {Operate.class},
timingInvocationHandler));
// call proxy instance method
operate.operateMethod1();
System.out.println();
operate.operateMethod2();
System.out.println();
operate.operateMethod3();
// print info of proxy class
System.out.println("proxy class is: " + operate.getClass().getName());
System.out.println("\r\nsuper class of proxy class is: " + operate.getClass().getSuperclass().getName());
System.out.println("\r\ninterfaces of proxy class are: ");
for (Class inter : operate.getClass().getInterfaces()) {
System.out.println("\t" + inter.getName());
}
System.out.println("\r\nmethods of proxy class are: ");
for (Method method : operate.getClass().getMethods()) {
System.out.println("\t" + method.getName());
}
// save proxy class to root of this project, you can use jd-gui to see content of the saved file
String saveFileName = "$Proxy0.class";
ProxyUtils.saveProxyClass(saveFileName, operate.getClass().getSimpleName(), operate.getClass().getInterfaces());
System.out.println("\r\nContent of " + operate.getClass().getSimpleName() + ".class has saved to file "
+ saveFileName + " at root of this project");
}
}
| 692 |
457 | <filename>sitl_config/ugv/cmdvel2gazebo/slros_busmsg_conversion.cpp
#include "slros_busmsg_conversion.h"
// Conversions between SL_Bus_cmdvel2gazebo_geometry_msgs_Twist and geometry_msgs::Twist
void convertFromBus(geometry_msgs::Twist* msgPtr, SL_Bus_cmdvel2gazebo_geometry_msgs_Twist const* busPtr)
{
const std::string rosMessageType("geometry_msgs/Twist");
convertFromBus(&msgPtr->angular, &busPtr->Angular);
convertFromBus(&msgPtr->linear, &busPtr->Linear);
}
void convertToBus(SL_Bus_cmdvel2gazebo_geometry_msgs_Twist* busPtr, geometry_msgs::Twist const* msgPtr)
{
const std::string rosMessageType("geometry_msgs/Twist");
convertToBus(&busPtr->Angular, &msgPtr->angular);
convertToBus(&busPtr->Linear, &msgPtr->linear);
}
// Conversions between SL_Bus_cmdvel2gazebo_geometry_msgs_Vector3 and geometry_msgs::Vector3
void convertFromBus(geometry_msgs::Vector3* msgPtr, SL_Bus_cmdvel2gazebo_geometry_msgs_Vector3 const* busPtr)
{
const std::string rosMessageType("geometry_msgs/Vector3");
msgPtr->x = busPtr->X;
msgPtr->y = busPtr->Y;
msgPtr->z = busPtr->Z;
}
void convertToBus(SL_Bus_cmdvel2gazebo_geometry_msgs_Vector3* busPtr, geometry_msgs::Vector3 const* msgPtr)
{
const std::string rosMessageType("geometry_msgs/Vector3");
busPtr->X = msgPtr->x;
busPtr->Y = msgPtr->y;
busPtr->Z = msgPtr->z;
}
// Conversions between SL_Bus_cmdvel2gazebo_std_msgs_Float64 and std_msgs::Float64
void convertFromBus(std_msgs::Float64* msgPtr, SL_Bus_cmdvel2gazebo_std_msgs_Float64 const* busPtr)
{
const std::string rosMessageType("std_msgs/Float64");
msgPtr->data = busPtr->Data;
}
void convertToBus(SL_Bus_cmdvel2gazebo_std_msgs_Float64* busPtr, std_msgs::Float64 const* msgPtr)
{
const std::string rosMessageType("std_msgs/Float64");
busPtr->Data = msgPtr->data;
}
| 722 |
777 | // 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 "chrome/browser/chromeos/session_length_limiter.h"
#include <memory>
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::NiceMock;
namespace chromeos {
namespace {
class MockSessionLengthLimiterDelegate : public SessionLengthLimiter::Delegate {
public:
MOCK_CONST_METHOD0(GetCurrentTime, const base::TimeTicks(void));
MOCK_METHOD0(StopSession, void(void));
};
} // namespace
class SessionLengthLimiterTest : public testing::Test {
protected:
SessionLengthLimiterTest();
// testing::Test:
void SetUp() override;
void TearDown() override;
void SetSessionUserActivitySeenPref(bool user_activity_seen);
void ClearSessionUserActivitySeenPref();
bool IsSessionUserActivitySeenPrefSet();
bool GetSessionUserActivitySeenPref();
void SetSessionStartTimePref(const base::TimeTicks& session_start_time);
void ClearSessionStartTimePref();
bool IsSessionStartTimePrefSet();
base::TimeTicks GetSessionStartTimePref();
void SetSessionLengthLimitPref(const base::TimeDelta& session_length_limit);
void ClearSessionLengthLimitPref();
void SetWaitForInitialUserActivityPref(bool wait_for_initial_user_activity);
void SimulateUserActivity();
void UpdateSessionStartTimeIfWaitingForUserActivity();
void ExpectStopSession();
void SaveSessionStopTime();
// Clears the session state by resetting |user_activity_| and
// |session_start_time_| and creates a new SessionLengthLimiter.
void CreateSessionLengthLimiter(bool browser_restarted);
void DestroySessionLengthLimiter();
scoped_refptr<base::TestMockTimeTaskRunner> runner_;
base::TimeTicks session_start_time_;
base::TimeTicks session_stop_time_;
private:
TestingPrefServiceSimple local_state_;
bool user_activity_seen_;
MockSessionLengthLimiterDelegate* delegate_; // Owned by
// session_length_limiter_.
std::unique_ptr<SessionLengthLimiter> session_length_limiter_;
};
SessionLengthLimiterTest::SessionLengthLimiterTest()
: user_activity_seen_(false),
delegate_(NULL) {
}
void SessionLengthLimiterTest::SetUp() {
TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);
SessionLengthLimiter::RegisterPrefs(local_state_.registry());
runner_ = new base::TestMockTimeTaskRunner;
runner_->FastForwardBy(base::TimeDelta::FromInternalValue(1000));
}
void SessionLengthLimiterTest::TearDown() {
session_length_limiter_.reset();
TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
}
void SessionLengthLimiterTest::SetSessionUserActivitySeenPref(
bool user_activity_seen) {
local_state_.SetUserPref(prefs::kSessionUserActivitySeen,
new base::FundamentalValue(user_activity_seen));
}
void SessionLengthLimiterTest::ClearSessionUserActivitySeenPref() {
local_state_.ClearPref(prefs::kSessionUserActivitySeen);
}
bool SessionLengthLimiterTest::IsSessionUserActivitySeenPrefSet() {
return local_state_.HasPrefPath(prefs::kSessionUserActivitySeen);
}
bool SessionLengthLimiterTest::GetSessionUserActivitySeenPref() {
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
return local_state_.GetBoolean(prefs::kSessionUserActivitySeen);
}
void SessionLengthLimiterTest::SetSessionStartTimePref(
const base::TimeTicks& session_start_time) {
local_state_.SetUserPref(
prefs::kSessionStartTime,
new base::StringValue(
base::Int64ToString(session_start_time.ToInternalValue())));
}
void SessionLengthLimiterTest::ClearSessionStartTimePref() {
local_state_.ClearPref(prefs::kSessionStartTime);
}
bool SessionLengthLimiterTest::IsSessionStartTimePrefSet() {
return local_state_.HasPrefPath(prefs::kSessionStartTime);
}
base::TimeTicks SessionLengthLimiterTest::GetSessionStartTimePref() {
EXPECT_TRUE(IsSessionStartTimePrefSet());
return base::TimeTicks::FromInternalValue(
local_state_.GetInt64(prefs::kSessionStartTime));
}
void SessionLengthLimiterTest::SetSessionLengthLimitPref(
const base::TimeDelta& session_length_limit) {
local_state_.SetUserPref(prefs::kSessionLengthLimit,
new base::FundamentalValue(
static_cast<int>(session_length_limit.InMilliseconds())));
UpdateSessionStartTimeIfWaitingForUserActivity();
}
void SessionLengthLimiterTest::ClearSessionLengthLimitPref() {
local_state_.RemoveUserPref(prefs::kSessionLengthLimit);
UpdateSessionStartTimeIfWaitingForUserActivity();
}
void SessionLengthLimiterTest::SetWaitForInitialUserActivityPref(
bool wait_for_initial_user_activity) {
UpdateSessionStartTimeIfWaitingForUserActivity();
local_state_.SetUserPref(
prefs::kSessionWaitForInitialUserActivity,
new base::FundamentalValue(wait_for_initial_user_activity));
}
void SessionLengthLimiterTest::SimulateUserActivity() {
if (session_length_limiter_)
session_length_limiter_->OnUserActivity(NULL);
UpdateSessionStartTimeIfWaitingForUserActivity();
user_activity_seen_ = true;
}
void SessionLengthLimiterTest::
UpdateSessionStartTimeIfWaitingForUserActivity() {
if (!user_activity_seen_ &&
local_state_.GetBoolean(prefs::kSessionWaitForInitialUserActivity)) {
session_start_time_ = runner_->NowTicks();
}
}
void SessionLengthLimiterTest::ExpectStopSession() {
Mock::VerifyAndClearExpectations(delegate_);
EXPECT_CALL(*delegate_, StopSession())
.Times(1)
.WillOnce(Invoke(this, &SessionLengthLimiterTest::SaveSessionStopTime));
}
void SessionLengthLimiterTest::SaveSessionStopTime() {
session_stop_time_ = runner_->NowTicks();
}
void SessionLengthLimiterTest::CreateSessionLengthLimiter(
bool browser_restarted) {
user_activity_seen_ = false;
session_start_time_ = runner_->NowTicks();
EXPECT_FALSE(delegate_);
delegate_ = new NiceMock<MockSessionLengthLimiterDelegate>;
ON_CALL(*delegate_, GetCurrentTime())
.WillByDefault(
Invoke(runner_.get(), &base::TestMockTimeTaskRunner::NowTicks));
EXPECT_CALL(*delegate_, StopSession()).Times(0);
session_length_limiter_.reset(
new SessionLengthLimiter(delegate_, browser_restarted));
}
void SessionLengthLimiterTest::DestroySessionLengthLimiter() {
session_length_limiter_.reset();
delegate_ = NULL;
}
// Verifies that when not instructed to wait for initial user activity, the
// session start time is set and the pref indicating user activity is cleared
// in local state during login.
TEST_F(SessionLengthLimiterTest, StartDoNotWaitForInitialUserActivity) {
// Pref indicating user activity not set. Session start time not set.
ClearSessionUserActivitySeenPref();
ClearSessionStartTimePref();
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time not set.
SetSessionUserActivitySeenPref(true);
ClearSessionStartTimePref();
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time in the future.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(session_start_time_ + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time in the future.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(session_start_time_ + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time valid.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(session_start_time_ - base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time valid.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(session_start_time_ - base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
}
// Verifies that when instructed to wait for initial user activity, the session
// start time and the pref indicating user activity are cleared in local state
// during login.
TEST_F(SessionLengthLimiterTest, StartWaitForInitialUserActivity) {
SetWaitForInitialUserActivityPref(true);
// Pref indicating user activity not set. Session start time not set.
ClearSessionUserActivitySeenPref();
ClearSessionStartTimePref();
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time not set.
SetSessionUserActivitySeenPref(true);
ClearSessionStartTimePref();
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time in the future.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time in the future.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time valid.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(runner_->NowTicks() - base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time valid.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(runner_->NowTicks() - base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
}
// Verifies that when not instructed to wait for initial user activity, local
// state is correctly updated during restart after a crash:
// * If no valid session start time is found in local state, the session start
// time is set and the pref indicating user activity is cleared.
// * If a valid session start time is found in local state, the session start
// time and the pref indicating user activity are *not* modified.
TEST_F(SessionLengthLimiterTest, RestartDoNotWaitForInitialUserActivity) {
// Pref indicating user activity not set. Session start time not set.
ClearSessionUserActivitySeenPref();
ClearSessionStartTimePref();
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time not set.
SetSessionUserActivitySeenPref(true);
ClearSessionStartTimePref();
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time in the future.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time in the future.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
DestroySessionLengthLimiter();
const base::TimeTicks stored_session_start_time =
runner_->NowTicks() - base::TimeDelta::FromHours(2);
// Pref indicating user activity not set. Session start time valid.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(stored_session_start_time);
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(stored_session_start_time, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time valid.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(stored_session_start_time);
CreateSessionLengthLimiter(true);
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(stored_session_start_time, GetSessionStartTimePref());
DestroySessionLengthLimiter();
}
// Verifies that when instructed to wait for initial user activity, local state
// is correctly updated during restart after a crash:
// * If no valid session start time is found in local state, the session start
// time and the pref indicating user activity are cleared.
// * If a valid session start time is found in local state, the session start
// time and the pref indicating user activity are *not* modified.
TEST_F(SessionLengthLimiterTest, RestartWaitForInitialUserActivity) {
SetWaitForInitialUserActivityPref(true);
// Pref indicating user activity not set. Session start time not set.
ClearSessionUserActivitySeenPref();
ClearSessionStartTimePref();
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time not set.
SetSessionUserActivitySeenPref(true);
ClearSessionStartTimePref();
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity not set. Session start time in the future.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time in the future.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(runner_->NowTicks() + base::TimeDelta::FromHours(2));
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
DestroySessionLengthLimiter();
const base::TimeTicks stored_session_start_time =
runner_->NowTicks() - base::TimeDelta::FromHours(2);
// Pref indicating user activity not set. Session start time valid.
ClearSessionUserActivitySeenPref();
SetSessionStartTimePref(stored_session_start_time);
CreateSessionLengthLimiter(true);
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(stored_session_start_time, GetSessionStartTimePref());
DestroySessionLengthLimiter();
// Pref indicating user activity set. Session start time valid.
SetSessionUserActivitySeenPref(true);
SetSessionStartTimePref(stored_session_start_time);
CreateSessionLengthLimiter(true);
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(stored_session_start_time, GetSessionStartTimePref());
DestroySessionLengthLimiter();
}
// Verifies that local state is correctly updated when waiting for initial user
// activity is toggled and no user activity has occurred yet.
TEST_F(SessionLengthLimiterTest, ToggleWaitForInitialUserActivity) {
CreateSessionLengthLimiter(false);
// Verify that the pref indicating user activity was not set and the session
// start time was set.
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Enable waiting for initial user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SetWaitForInitialUserActivityPref(true);
// Verify that the session start time was cleared and the pref indicating user
// activity was not set.
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
// Disable waiting for initial user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SetWaitForInitialUserActivityPref(false);
// Verify that the pref indicating user activity was not set and the session
// start time was.
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
}
// Verifies that local state is correctly updated when instructed not to wait
// for initial user activity and user activity occurs. Also verifies that once
// initial user activity has occurred, neither the session start time nor the
// pref indicating user activity change in local state anymore.
TEST_F(SessionLengthLimiterTest, UserActivityWhileNotWaiting) {
CreateSessionLengthLimiter(false);
// Verify that the pref indicating user activity was not set and the session
// start time was set.
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Simulate user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SimulateUserActivity();
// Verify that the pref indicating user activity and the session start time
// were set.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Simulate user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SimulateUserActivity();
// Verify that the pref indicating user activity and the session start time
// were not changed.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Enable waiting for initial user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SetWaitForInitialUserActivityPref(true);
// Verify that the pref indicating user activity and the session start time
// were not changed.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
}
// Verifies that local state is correctly updated when instructed to wait for
// initial user activity and user activity occurs. Also verifies that once
// initial user activity has occurred, neither the session start time nor the
// pref indicating user activity change in local state anymore.
TEST_F(SessionLengthLimiterTest, UserActivityWhileWaiting) {
SetWaitForInitialUserActivityPref(true);
CreateSessionLengthLimiter(false);
// Verify that the pref indicating user activity and the session start time
// were not set.
EXPECT_FALSE(IsSessionUserActivitySeenPrefSet());
EXPECT_FALSE(IsSessionStartTimePrefSet());
// Simulate user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SimulateUserActivity();
// Verify that the pref indicating user activity and the session start time
// were set.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Simulate user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SimulateUserActivity();
// Verify that the pref indicating user activity and the session start time
// were not changed.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Disable waiting for initial user activity.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
SetWaitForInitialUserActivityPref(false);
// Verify that the pref indicating user activity and the session start time
// were not changed.
EXPECT_TRUE(IsSessionUserActivitySeenPrefSet());
EXPECT_TRUE(GetSessionUserActivitySeenPref());
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
}
// Creates a SessionLengthLimiter without setting a limit. Verifies that the
// limiter does not start a timer.
TEST_F(SessionLengthLimiterTest, RunWithoutLimit) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
CreateSessionLengthLimiter(false);
// Verify that no timer fires to terminate the session.
runner_->FastForwardUntilNoTasksRemain();
}
// Creates a SessionLengthLimiter after setting a limit and instructs it not to
// wait for user activity. Verifies that the limiter starts a timer even if no
// user activity occurs and that when the session length reaches the limit, the
// session is terminated.
TEST_F(SessionLengthLimiterTest, RunWithoutUserActivityWhileNotWaiting) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Verify that the timer fires and the session is terminated when the session
// length limit is reached.
ExpectStopSession();
runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(session_start_time_ + base::TimeDelta::FromSeconds(60),
session_stop_time_);
}
// Creates a SessionLengthLimiter after setting a limit and instructs it to wait
// for initial user activity. Verifies that if no user activity occurs, the
// limiter does not start a timer.
TEST_F(SessionLengthLimiterTest, RunWithoutUserActivityWhileWaiting) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
SetWaitForInitialUserActivityPref(true);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionStartTimePrefSet());
// Verify that no timer fires to terminate the session.
runner_->FastForwardUntilNoTasksRemain();
}
// Creates a SessionLengthLimiter after setting a limit and instructs it not to
// wait for user activity. Verifies that the limiter starts a timer and that
// when the session length reaches the limit, the session is terminated. Also
// verifies that user activity does not affect the timer.
TEST_F(SessionLengthLimiterTest, RunWithUserActivityWhileNotWaiting) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Simulate user activity after 20 seconds.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(20));
SimulateUserActivity();
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Verify that the timer fires and the session is terminated when the session
// length limit is reached.
ExpectStopSession();
runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(session_start_time_ + base::TimeDelta::FromSeconds(60),
session_stop_time_);
}
// Creates a SessionLengthLimiter after setting a limit and instructs it to wait
// for initial user activity. Verifies that once user activity occurs, the
// limiter starts a timer and that when the session length reaches the limit,
// the session is terminated. Also verifies that further user activity does not
// affect the timer.
TEST_F(SessionLengthLimiterTest, RunWithUserActivityWhileWaiting) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
SetWaitForInitialUserActivityPref(true);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
EXPECT_FALSE(IsSessionStartTimePrefSet());
// Simulate user activity after 20 seconds.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(20));
SimulateUserActivity();
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Simulate user activity after 20 seconds.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(20));
SimulateUserActivity();
EXPECT_EQ(session_start_time_, GetSessionStartTimePref());
// Verify that the timer fires and the session is terminated when the session
// length limit is reached.
ExpectStopSession();
runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(session_start_time_ + base::TimeDelta::FromSeconds(60),
session_stop_time_);
}
// Creates a SessionLengthLimiter after setting a 60 second limit, allows 50
// seconds of session time to pass, then increases the limit to 90 seconds.
// Verifies that when the session time reaches the new 90 second limit, the
// session is terminated.
TEST_F(SessionLengthLimiterTest, RunAndIncreaseSessionLengthLimit) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
// Fast forward the time by 50 seconds, verifying that no timer fires to
// terminate the session.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(50));
// Increase the session length limit to 90 seconds.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(90));
// Verify that the the timer fires and the session is terminated when the
// session length limit is reached.
ExpectStopSession();
runner_->FastForwardUntilNoTasksRemain();
EXPECT_EQ(session_start_time_ + base::TimeDelta::FromSeconds(90),
session_stop_time_);
}
// Creates a SessionLengthLimiter after setting a 60 second limit, allows 50
// seconds of session time to pass, then decreases the limit to 40 seconds.
// Verifies that when the limit is decreased to 40 seconds after 50 seconds of
// session time have passed, the next timer tick causes the session to be
// terminated.
TEST_F(SessionLengthLimiterTest, RunAndDecreaseSessionLengthLimit) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
// Fast forward the time by 50 seconds, verifying that no timer fires to
// terminate the session.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(50));
// Verify that reducing the session length limit below the 50 seconds that
// have already elapsed causes the session to be terminated immediately.
ExpectStopSession();
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(40));
EXPECT_EQ(session_start_time_ + base::TimeDelta::FromSeconds(50),
session_stop_time_);
}
// Creates a SessionLengthLimiter after setting a 60 second limit, allows 50
// seconds of session time to pass, then removes the limit. Verifies that after
// the limit is removed, the session is not terminated when the session time
// reaches the original 60 second limit.
TEST_F(SessionLengthLimiterTest, RunAndRemoveSessionLengthLimit) {
base::ThreadTaskRunnerHandle runner_handler(runner_);
// Set a 60 second session time limit.
SetSessionLengthLimitPref(base::TimeDelta::FromSeconds(60));
CreateSessionLengthLimiter(false);
// Fast forward the time by 50 seconds, verifying that no timer fires to
// terminate the session.
runner_->FastForwardBy(base::TimeDelta::FromSeconds(50));
// Remove the session length limit.
ClearSessionLengthLimitPref();
// Verify that no timer fires to terminate the session.
runner_->FastForwardUntilNoTasksRemain();
}
} // namespace chromeos
| 8,489 |
585 | <gh_stars>100-1000
########################################################################
#
# Various utility functions.
#
########################################################################
#
# This file is part of FinanceOps:
#
# https://github.com/Hvass-Labs/FinanceOps
#
# Published under the MIT License. See the file LICENSE for details.
#
# Copyright 2021 by <NAME>
#
########################################################################
import numpy as np
########################################################################
def linear_map(x, x_lo, x_hi, y_lo, y_hi, clip=False):
"""
Linear map of input `x` to output `y` where:
- `x == x_lo` => `y == y_lo`
- `x == x_hi` => `y == y_hi`
Output `y` can optionally be clipped between `y_lo` and `y_hi`.
:param x: Array compatible with numpy.
:param x_lo: Scalar value. See function description.
:param x_hi: Scalar value. See function description.
:param y_lo: Scalar value. See function description.
:param y_hi: Scalar value. See function description.
:param clip:
Clip output. If set to the boolean value `True` or the string 'both',
then the output is clipped between both `y_lo` and `y_hi`.
If set to the string 'lo' then only clip the lower bound using `y_lo`.
If set to the string 'hi' then only clip the upper bound using `y_hi`.
:return: Array of same size as input `x`.
"""
# Parameters for the linear mapping.
a = (y_hi - y_lo) / (x_hi - x_lo)
b = y_lo - a * x_lo
# Linear mapping.
y = a * x + b
# Optional clipping.
if clip == 'both' or clip is True:
y = np.clip(y, y_lo, y_hi)
elif clip == 'lo':
y = np.maximum(y, y_lo)
elif clip == 'hi':
y = np.minimum(y, y_hi)
return y
########################################################################
| 634 |
5,279 | /*
* 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.beam.sdk.transforms.reflect;
import java.lang.reflect.Method;
import java.util.NoSuchElementException;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.reflect.DoFnSignatures.FnAnalysisContext;
import org.apache.beam.sdk.values.TypeDescriptor;
/** Utilities for use in {@link DoFnSignatures} tests. */
class DoFnSignaturesTestUtils {
/** An empty base {@link DoFn} class. */
static class FakeDoFn extends DoFn<Integer, String> {}
/** An error reporter. */
static DoFnSignatures.ErrorReporter errors() {
return new DoFnSignatures.ErrorReporter(null, "[test]");
}
/**
* A class for testing utilities that take {@link Method} objects. Use like this:
*
* <pre>{@code
* Method m = new AnonymousMethod() {
* SomeReturnValue method(SomeParameters...) { ... }
* }.getMethod(); // Will return the Method for "method".
* }</pre>
*/
static class AnonymousMethod {
final Method getMethod() throws Exception {
for (Method method : getClass().getDeclaredMethods()) {
if ("method".equals(method.getName())) {
return method;
}
}
throw new NoSuchElementException("No method named 'method' defined on " + getClass());
}
}
static DoFnSignature.ProcessElementMethod analyzeProcessElementMethod(AnonymousMethod method)
throws Exception {
return DoFnSignatures.analyzeProcessElementMethod(
errors(),
TypeDescriptor.of(FakeDoFn.class),
method.getMethod(),
TypeDescriptor.of(Integer.class),
TypeDescriptor.of(String.class),
FnAnalysisContext.create());
}
}
| 780 |
971 | package com.ucar.datalink.manager.core.utils.timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
/**
* Created by lubiao on 2016/12/12.
*/
public class SystemTimer implements Timer {
private static final Logger log = LoggerFactory.getLogger(SystemTimer.class);
private final String executorName;
private final Long tickMs;
private final Integer wheelSize;
private final Long startMs;
// timeout timer
private final ExecutorService taskExecutor;
private final DelayQueue<TimerTaskList> delayQueue;
private final AtomicInteger taskCounter;
private final TimingWheel timingWheel;
private final Consumer<TimerTaskEntry> reinsert = timerTaskEntry -> addTimerTaskEntry(timerTaskEntry);
// Locks used to protect data structures while ticking
private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
private final ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
public SystemTimer(String executorName, Long tickMs, Integer wheelSize, Long startMs) {
this.executorName = executorName;
this.tickMs = tickMs != null ? tickMs : 1L;
this.wheelSize = wheelSize != null ? wheelSize : 20;
this.startMs = startMs != null ? startMs : TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
this.taskExecutor = Executors.newFixedThreadPool(1, runnable -> {
Thread thread = new Thread(runnable, "executor-" + executorName);
thread.setDaemon(false);
thread.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught errors in thread '" + t.getName() + "':", e));
return thread;
});
this.delayQueue = new DelayQueue<>();
this.taskCounter = new AtomicInteger(0);
this.timingWheel = new TimingWheel(this.tickMs, this.wheelSize, this.startMs, taskCounter, delayQueue);
}
@Override
public void add(TimerTask timerTask) {
readLock.lock();
try {
addTimerTaskEntry(new TimerTaskEntry(timerTask, timerTask.getDelayMs() + TimeUnit.NANOSECONDS.toMillis(System.nanoTime())));
} finally {
readLock.unlock();
}
}
@Override
public Boolean advanceClock(Long timeoutMs) {
TimerTaskList bucket = null;
try {
bucket = delayQueue.poll(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.error("InterruptedException occurrs when execute advanceClock method", e);
}
if (bucket != null) {
writeLock.lock();
try {
while (bucket != null) {
timingWheel.advanceClock(bucket.getExpiration());
bucket.flush(reinsert);
bucket = delayQueue.poll();
}
} finally {
writeLock.unlock();
}
return true;
} else {
return false;
}
}
@Override
public Integer size() {
return taskCounter.get();
}
@Override
public void shutdown() {
taskExecutor.shutdown();
}
private void addTimerTaskEntry(TimerTaskEntry timerTaskEntry) {
if (!timingWheel.add(timerTaskEntry)) {
// Already expired or cancelled
if (!timerTaskEntry.cancelled()) {
taskExecutor.submit(timerTaskEntry.getTimerTask());
}
}
}
}
| 1,502 |
743 | <reponame>OyTao/corosync-src<filename>test/testtimer.c
/*
* Copyright (c) 2003-2004 MontaVista Software, Inc.
*
* All rights reserved.
*
* Author: <NAME> (<EMAIL>)
*
* This software licensed under BSD license, the text of which follows:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the MontaVista Software, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/poll.h>
#include "../exec/timer.h"
void timer_function (void *data)
{
printf ("timer %p\n", data);
}
int main (void)
{
int msec;
struct timer *timer;
int randomvalue;
int i;
printf ("adding timers\n");
for (i = 0; i < 1000; i++) {
timer = (struct timer *)malloc (sizeof (struct timer));
randomvalue = random()%5000;
timer->function = timer_function;
timer->data = (void *)randomvalue;
timer_add_msec_in_future (timer, randomvalue);
}
printf ("done adding timers\n");
for (;;) {
msec = timer_expire_get_msec();
// printf ("msec to next timer expire %d\n", msec);
if (msec == -1) {
printf ("no more timers\n");
break;
}
poll (0, 0, msec);
timer_expire ();
}
return (0);
}
| 829 |
443 | <reponame>Joshinn-io/augur<filename>augur/cli/_multicommand.py
#SPDX-License-Identifier: MIT
"""
Runs Augur with Gunicorn when called
"""
import os
import sys
import click
import importlib
import augur.application
CONTEXT_SETTINGS = dict(auto_envvar_prefix='AUGUR')
class AugurMultiCommand(click.MultiCommand):
def __commands_folder(self):
return os.path.abspath(os.path.dirname(__file__))
def list_commands(self, ctx):
rv = []
for filename in os.listdir(self.__commands_folder()):
if not filename.startswith('_') and filename.endswith('.py'):
rv.append(filename[:-3])
rv.sort()
return rv
def get_command(self, ctx, name):
try:
module = importlib.import_module('.' + name, 'augur.cli')
return module.cli
except ModuleNotFoundError as e:
pass
@click.command(cls=AugurMultiCommand, context_settings=CONTEXT_SETTINGS)
@click.pass_context
def run(ctx):
"""
Augur is an application for open source community health analytics
"""
return ctx
| 457 |
4,262 | <gh_stars>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.
*/
package org.apache.camel.builder.endpoint.dsl;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.PollingConsumerPollStrategy;
/**
* Query Couchbase Views with a poll strategy and/or perform various operations
* against Couchbase databases.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface CouchbaseEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the Couchbase component.
*/
public interface CouchbaseEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedCouchbaseEndpointConsumerBuilder advanced() {
return (AdvancedCouchbaseEndpointConsumerBuilder) this;
}
/**
* The bucket to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: common
*
* @param bucket the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder bucket(String bucket) {
doSetProperty("bucket", bucket);
return this;
}
/**
* The collection to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param collection the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder collection(String collection) {
doSetProperty("collection", collection);
return this;
}
/**
* The key to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param key the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder key(String key) {
doSetProperty("key", key);
return this;
}
/**
* The scope to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param scope the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder scope(String scope) {
doSetProperty("scope", scope);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Define the consumer Processed strategy to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: none
* Group: consumer
*
* @param consumerProcessedStrategy the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder consumerProcessedStrategy(
String consumerProcessedStrategy) {
doSetProperty("consumerProcessedStrategy", consumerProcessedStrategy);
return this;
}
/**
* Define if this operation is descending or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param descending the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder descending(boolean descending) {
doSetProperty("descending", descending);
return this;
}
/**
* Define if this operation is descending or not.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param descending the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder descending(String descending) {
doSetProperty("descending", descending);
return this;
}
/**
* The design document name to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: beer
* Group: consumer
*
* @param designDocumentName the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder designDocumentName(
String designDocumentName) {
doSetProperty("designDocumentName", designDocumentName);
return this;
}
/**
* If true consumer will return complete document instead data defined
* in view.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param fullDocument the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder fullDocument(
boolean fullDocument) {
doSetProperty("fullDocument", fullDocument);
return this;
}
/**
* If true consumer will return complete document instead data defined
* in view.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param fullDocument the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder fullDocument(
String fullDocument) {
doSetProperty("fullDocument", fullDocument);
return this;
}
/**
* The output limit to use.
*
* The option is a: <code>int</code> type.
*
* Default: -1
* Group: consumer
*
* @param limit the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder limit(int limit) {
doSetProperty("limit", limit);
return this;
}
/**
* The output limit to use.
*
* The option will be converted to a <code>int</code> type.
*
* Default: -1
* Group: consumer
*
* @param limit the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder limit(String limit) {
doSetProperty("limit", limit);
return this;
}
/**
* Define a range for the end key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param rangeEndKey the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder rangeEndKey(String rangeEndKey) {
doSetProperty("rangeEndKey", rangeEndKey);
return this;
}
/**
* Define a range for the start key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param rangeStartKey the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder rangeStartKey(
String rangeStartKey) {
doSetProperty("rangeStartKey", rangeStartKey);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder sendEmptyMessageWhenIdle(
boolean sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder sendEmptyMessageWhenIdle(
String sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* Define the skip to use.
*
* The option is a: <code>int</code> type.
*
* Default: -1
* Group: consumer
*
* @param skip the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder skip(int skip) {
doSetProperty("skip", skip);
return this;
}
/**
* Define the skip to use.
*
* The option will be converted to a <code>int</code> type.
*
* Default: -1
* Group: consumer
*
* @param skip the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder skip(String skip) {
doSetProperty("skip", skip);
return this;
}
/**
* The view name to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: brewery_beers
* Group: consumer
*
* @param viewName the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder viewName(String viewName) {
doSetProperty("viewName", viewName);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffErrorThreshold(
int backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffErrorThreshold(
String backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffIdleThreshold(
int backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffIdleThreshold(
String backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffMultiplier(
int backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder backoffMultiplier(
String backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option is a: <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder delay(long delay) {
doSetProperty("delay", delay);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder delay(String delay) {
doSetProperty("delay", delay);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder greedy(boolean greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder greedy(String greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option is a: <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder initialDelay(long initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder initialDelay(
String initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder repeatCount(long repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder repeatCount(String repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option is a:
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder runLoggingLevel(
LoggingLevel runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder runLoggingLevel(
String runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option is a:
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder scheduledExecutorService(
ScheduledExecutorService scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option will be converted to a
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder scheduledExecutorService(
String scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder scheduler(Object scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option will be converted to a
* <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder scheduler(String scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler.
*
* The option is a: <code>java.util.Map&lt;java.lang.String,
* java.lang.Object&gt;</code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder schedulerProperties(
String key,
Object value) {
doSetMultiValueProperty("schedulerProperties", "scheduler." + key, value);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler.
*
* The option is a: <code>java.util.Map&lt;java.lang.String,
* java.lang.Object&gt;</code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param values the values
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder schedulerProperties(Map values) {
doSetMultiValueProperties("schedulerProperties", "scheduler.", values);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder startScheduler(
boolean startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder startScheduler(
String startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option is a:
* <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder timeUnit(TimeUnit timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option will be converted to a
* <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder timeUnit(String timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder useFixedDelay(
boolean useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder useFixedDelay(
String useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* The password to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The username to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default CouchbaseEndpointConsumerBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Couchbase component.
*/
public interface AdvancedCouchbaseEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default CouchbaseEndpointConsumerBuilder basic() {
return (CouchbaseEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a:
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a:
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder pollStrategy(
PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option will be converted to a
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder pollStrategy(
String pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* The additional hosts.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param additionalHosts the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder additionalHosts(
String additionalHosts) {
doSetProperty("additionalHosts", additionalHosts);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder connectTimeout(
long connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder connectTimeout(
String connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder queryTimeout(
long queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointConsumerBuilder queryTimeout(
String queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
}
/**
* Builder for endpoint producers for the Couchbase component.
*/
public interface CouchbaseEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedCouchbaseEndpointProducerBuilder advanced() {
return (AdvancedCouchbaseEndpointProducerBuilder) this;
}
/**
* The bucket to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: common
*
* @param bucket the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder bucket(String bucket) {
doSetProperty("bucket", bucket);
return this;
}
/**
* The collection to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param collection the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder collection(String collection) {
doSetProperty("collection", collection);
return this;
}
/**
* The key to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param key the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder key(String key) {
doSetProperty("key", key);
return this;
}
/**
* The scope to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param scope the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder scope(String scope) {
doSetProperty("scope", scope);
return this;
}
/**
* Define if we want an autostart Id when we are doing an insert
* operation.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param autoStartIdForInserts the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder autoStartIdForInserts(
boolean autoStartIdForInserts) {
doSetProperty("autoStartIdForInserts", autoStartIdForInserts);
return this;
}
/**
* Define if we want an autostart Id when we are doing an insert
* operation.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param autoStartIdForInserts the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder autoStartIdForInserts(
String autoStartIdForInserts) {
doSetProperty("autoStartIdForInserts", autoStartIdForInserts);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to do.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: CCB_PUT
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Where to persist the data.
*
* The option is a: <code>int</code> type.
*
* Default: 0
* Group: producer
*
* @param persistTo the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder persistTo(int persistTo) {
doSetProperty("persistTo", persistTo);
return this;
}
/**
* Where to persist the data.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 0
* Group: producer
*
* @param persistTo the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder persistTo(String persistTo) {
doSetProperty("persistTo", persistTo);
return this;
}
/**
* Define the number of retry attempts.
*
* The option is a: <code>int</code> type.
*
* Default: 2
* Group: producer
*
* @param producerRetryAttempts the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder producerRetryAttempts(
int producerRetryAttempts) {
doSetProperty("producerRetryAttempts", producerRetryAttempts);
return this;
}
/**
* Define the number of retry attempts.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 2
* Group: producer
*
* @param producerRetryAttempts the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder producerRetryAttempts(
String producerRetryAttempts) {
doSetProperty("producerRetryAttempts", producerRetryAttempts);
return this;
}
/**
* Define the retry pause between different attempts.
*
* The option is a: <code>int</code> type.
*
* Default: 5000
* Group: producer
*
* @param producerRetryPause the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder producerRetryPause(
int producerRetryPause) {
doSetProperty("producerRetryPause", producerRetryPause);
return this;
}
/**
* Define the retry pause between different attempts.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 5000
* Group: producer
*
* @param producerRetryPause the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder producerRetryPause(
String producerRetryPause) {
doSetProperty("producerRetryPause", producerRetryPause);
return this;
}
/**
* Where to replicate the data.
*
* The option is a: <code>int</code> type.
*
* Default: 0
* Group: producer
*
* @param replicateTo the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder replicateTo(int replicateTo) {
doSetProperty("replicateTo", replicateTo);
return this;
}
/**
* Where to replicate the data.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 0
* Group: producer
*
* @param replicateTo the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder replicateTo(String replicateTo) {
doSetProperty("replicateTo", replicateTo);
return this;
}
/**
* Define the starting Id where we are doing an insert operation.
*
* The option is a: <code>long</code> type.
*
* Group: producer
*
* @param startingIdForInsertsFrom the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder startingIdForInsertsFrom(
long startingIdForInsertsFrom) {
doSetProperty("startingIdForInsertsFrom", startingIdForInsertsFrom);
return this;
}
/**
* Define the starting Id where we are doing an insert operation.
*
* The option will be converted to a <code>long</code> type.
*
* Group: producer
*
* @param startingIdForInsertsFrom the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder startingIdForInsertsFrom(
String startingIdForInsertsFrom) {
doSetProperty("startingIdForInsertsFrom", startingIdForInsertsFrom);
return this;
}
/**
* The password to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The username to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default CouchbaseEndpointProducerBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Couchbase component.
*/
public interface AdvancedCouchbaseEndpointProducerBuilder
extends
EndpointProducerBuilder {
default CouchbaseEndpointProducerBuilder basic() {
return (CouchbaseEndpointProducerBuilder) this;
}
/**
* The additional hosts.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param additionalHosts the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointProducerBuilder additionalHosts(
String additionalHosts) {
doSetProperty("additionalHosts", additionalHosts);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointProducerBuilder connectTimeout(
long connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointProducerBuilder connectTimeout(
String connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointProducerBuilder queryTimeout(
long queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointProducerBuilder queryTimeout(
String queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
}
/**
* Builder for endpoint for the Couchbase component.
*/
public interface CouchbaseEndpointBuilder
extends
CouchbaseEndpointConsumerBuilder,
CouchbaseEndpointProducerBuilder {
default AdvancedCouchbaseEndpointBuilder advanced() {
return (AdvancedCouchbaseEndpointBuilder) this;
}
/**
* The bucket to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: common
*
* @param bucket the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder bucket(String bucket) {
doSetProperty("bucket", bucket);
return this;
}
/**
* The collection to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param collection the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder collection(String collection) {
doSetProperty("collection", collection);
return this;
}
/**
* The key to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param key the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder key(String key) {
doSetProperty("key", key);
return this;
}
/**
* The scope to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param scope the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder scope(String scope) {
doSetProperty("scope", scope);
return this;
}
/**
* The password to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The username to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default CouchbaseEndpointBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint for the Couchbase component.
*/
public interface AdvancedCouchbaseEndpointBuilder
extends
AdvancedCouchbaseEndpointConsumerBuilder,
AdvancedCouchbaseEndpointProducerBuilder {
default CouchbaseEndpointBuilder basic() {
return (CouchbaseEndpointBuilder) this;
}
/**
* The additional hosts.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param additionalHosts the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointBuilder additionalHosts(
String additionalHosts) {
doSetProperty("additionalHosts", additionalHosts);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointBuilder connectTimeout(
long connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the timeoutconnect in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 30000
* Group: advanced
*
* @param connectTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointBuilder connectTimeout(
String connectTimeout) {
doSetProperty("connectTimeout", connectTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointBuilder queryTimeout(long queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
/**
* Define the operation timeout in milliseconds.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 2500
* Group: advanced
*
* @param queryTimeout the value to set
* @return the dsl builder
*/
default AdvancedCouchbaseEndpointBuilder queryTimeout(
String queryTimeout) {
doSetProperty("queryTimeout", queryTimeout);
return this;
}
}
public interface CouchbaseBuilders {
/**
* Couchbase (camel-couchbase)
* Query Couchbase Views with a poll strategy and/or perform various
* operations against Couchbase databases.
*
* Category: database,nosql
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-couchbase
*
* Syntax: <code>couchbase:protocol://hostname:port</code>
*
* Path parameter: protocol (required)
* The protocol to use
*
* Path parameter: hostname (required)
* The hostname to use
*
* Path parameter: port
* The port number to use
* Default value: 8091
*
* @param path protocol://hostname:port
* @return the dsl builder
*/
default CouchbaseEndpointBuilder couchbase(String path) {
return CouchbaseEndpointBuilderFactory.endpointBuilder("couchbase", path);
}
/**
* Couchbase (camel-couchbase)
* Query Couchbase Views with a poll strategy and/or perform various
* operations against Couchbase databases.
*
* Category: database,nosql
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-couchbase
*
* Syntax: <code>couchbase:protocol://hostname:port</code>
*
* Path parameter: protocol (required)
* The protocol to use
*
* Path parameter: hostname (required)
* The hostname to use
*
* Path parameter: port
* The port number to use
* Default value: 8091
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path protocol://hostname:port
* @return the dsl builder
*/
default CouchbaseEndpointBuilder couchbase(
String componentName,
String path) {
return CouchbaseEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static CouchbaseEndpointBuilder endpointBuilder(
String componentName,
String path) {
class CouchbaseEndpointBuilderImpl extends AbstractEndpointBuilder implements CouchbaseEndpointBuilder, AdvancedCouchbaseEndpointBuilder {
public CouchbaseEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new CouchbaseEndpointBuilderImpl(path);
}
} | 28,849 |
1,835 | <reponame>elan17/GamestonkTerminal
import asyncio
import discord
import discordbot.config_discordbot as cfg
from discordbot.run_discordbot import gst_bot, logger
from discordbot.stocks.screener.historical import historical_command
from discordbot.stocks.screener.overview import overview_command
from discordbot.stocks.screener.presets_custom import presets_custom_command
from discordbot.stocks.screener.presets_default import presets_default_command
from discordbot.stocks.screener.valuation import valuation_command
from discordbot.stocks.screener.financial import financial_command
from discordbot.stocks.screener.ownership import ownership_command
from discordbot.stocks.screener.performance import performance_command
from discordbot.stocks.screener.technical import technical_command
from discordbot.stocks.screener import screener_options as so
# pylint: disable=R0912
class ScreenerCommands(discord.ext.commands.Cog):
"""Screener menu"""
def __init__(self, bot: discord.ext.commands.Bot):
self.bot = bot
@discord.ext.commands.command(name="stocks.scr.presets_default")
async def presets_default(self, ctx: discord.ext.commands.Context):
"""Displays every available preset"""
logger.info("stocks.scr.presets_default")
await presets_default_command(ctx)
@discord.ext.commands.command(name="stocks.scr.presets_custom")
async def presets_custom(self, ctx: discord.ext.commands.Context):
"""Displays every available preset"""
logger.info("stocks.scr.presets_custom")
await presets_custom_command(ctx)
@discord.ext.commands.command(
name="stocks.scr.historical", usage="[signal] [start]"
)
async def historical(
self,
ctx: discord.ext.commands.Context,
signal="most_volatile",
start="",
):
"""Displays trades made by the congress/senate/house [quiverquant.com]
Parameters
-----------
signal: str
Signal. Default: most_volatile
start:
Starting date in YYYY-MM-DD format
"""
logger.info("stocks.scr.historical")
await historical_command(ctx, signal, start)
@discord.ext.commands.command(
name="stocks.scr.overview", usage="[preset] [sort] [limit] [ascend]"
)
async def overview(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays stocks with overview data such as Sector and Industry [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.overview")
await overview_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(
name="stocks.scr.valuation", usage="[preset] [sort] [limit] [ascend]"
)
async def valuation(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays results from chosen preset focusing on valuation metrics [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.valuation")
await valuation_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(
name="stocks.scr.financial", usage="[preset] [sort] [limit] [ascend]"
)
async def financial(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays returned results from preset by financial metrics [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.financial")
await financial_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(
name="stocks.scr.ownership", usage="[preset] [sort] [limit] [ascend]"
)
async def ownership(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays stocks based on own share float and ownership data [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.ownership")
await ownership_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(
name="stocks.scr.performance", usage="[preset] [sort] [limit] [ascend]"
)
async def performance(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays stocks and sort by performance categories [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.performance")
await performance_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(
name="stocks.scr.technical", usage="[preset] [sort] [limit] [ascend]"
)
async def technical(
self,
ctx: discord.ext.commands.Context,
preset="template",
sort="",
limit="5",
ascend="False",
):
"""Displays stocks according to chosen preset, sorting by technical factors [Finviz]
Parameters
-----------
preset: str
screener preset
sort: str
column to sort by
limit: int
number of stocks to display
ascend: boolean
whether it's sorted by ascending order or not. Default: False
"""
logger.info("stocks.scr.technical")
await technical_command(ctx, preset, sort, limit, ascend)
@discord.ext.commands.command(name="stocks.scr")
async def scr(self, ctx: discord.ext.commands.Context, preset=""):
"""Screener Context Menu
Run `!help ScreenerCommands` to see the list of available commands.
Returns
-------
Sends a message to the discord user with the commands from the screener context.
The user can then select a reaction to trigger a command.
"""
logger.info("!stocks.scr")
if preset != "" and preset not in so.all_presets:
raise Exception("Invalid preset selected!")
if preset:
text = (
"0️⃣ !stocks.scr.presets_default\n"
"1️⃣ !stocks.scr.presets_custom\n"
"2️⃣ !stocks.scr.historical <SIGNAL> <START>\n"
f"3️⃣ !stocks.scr.overview {preset} <SORT> <LIMIT> <ASCEND>\n"
f"4️⃣ !stocks.scr.valuation {preset} <SORT> <LIMIT> <ASCEND>\n"
f"5️⃣ !stocks.scr.financial {preset} <SORT> <LIMIT> <ASCEND>\n"
f"6️⃣ !stocks.scr.ownership {preset} <SORT> <LIMIT> <ASCEND>\n"
f"7️⃣ !stocks.scr.performance {preset} <SORT> <LIMIT> <ASCEND>\n"
f"8️⃣ !stocks.scr.technical {preset} <SORT> <LIMIT> <ASCEND>"
)
else:
text = (
"0️⃣ !stocks.scr.presets_default\n"
"1️⃣ !stocks.scr.presets_custom\n"
"2️⃣ !stocks.scr.historical <SIGNAL> <START>\n"
"3️⃣ !stocks.scr.overview <PRESET> <SORT> <LIMIT> <ASCEND>\n"
"4️⃣ !stocks.scr.valuation <PRESET> <SORT> <LIMIT> <ASCEND>\n"
"5️⃣ !stocks.scr.financial <PRESET> <SORT> <LIMIT> <ASCEND>\n"
"6️⃣ !stocks.scr.ownership <PRESET> <SORT> <LIMIT> <ASCEND>\n"
"7️⃣ !stocks.scr.performance <PRESET> <SORT> <LIMIT> <ASCEND>\n"
"8️⃣ !stocks.scr.technical <PRESET> <SORT> <LIMIT> <ASCEND>"
)
title = "Screener Menu"
embed = discord.Embed(title=title, description=text, colour=cfg.COLOR)
embed.set_author(
name=cfg.AUTHOR_NAME,
icon_url=cfg.AUTHOR_ICON_URL,
)
msg = await ctx.send(embed=embed)
emoji_list = ["0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣"]
for emoji in emoji_list:
await msg.add_reaction(emoji)
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in emoji_list
try:
reaction, _ = await gst_bot.wait_for(
"reaction_add", timeout=cfg.MENU_TIMEOUT, check=check
)
if reaction.emoji == "0️⃣":
logger.info("!stocks.scr. Reaction selected: 0")
await presets_default_command(ctx)
elif reaction.emoji == "1️⃣":
logger.info("!stocks.scr. Reaction selected: 1")
await presets_custom_command(ctx)
elif reaction.emoji == "2️⃣":
logger.info("!stocks.scr. Reaction selected: 2")
await historical_command(ctx, preset)
elif reaction.emoji == "3️⃣":
logger.info("!stocks.scr. Reaction selected: 3")
await overview_command(ctx, preset)
elif reaction.emoji == "4️⃣":
logger.info("!stocks.scr. Reaction selected: 4")
await valuation_command(ctx, preset)
elif reaction.emoji == "5️⃣":
logger.info("!stocks.scr. Reaction selected: 5")
await financial_command(ctx, preset)
elif reaction.emoji == "6️⃣":
logger.info("!stocks.scr. Reaction selected: 6")
await ownership_command(ctx, preset)
elif reaction.emoji == "7️⃣":
logger.info("!stocks.scr. Reaction selected: 7")
await performance_command(ctx, preset)
elif reaction.emoji == "8️⃣":
logger.info("!stocks.scr. Reaction selected: 8")
await technical_command(ctx, preset)
for emoji in emoji_list:
await msg.remove_reaction(emoji, ctx.bot.user)
except asyncio.TimeoutError:
for emoji in emoji_list:
await msg.remove_reaction(emoji, ctx.bot.user)
if cfg.DEBUG:
embed = discord.Embed(
description="Error timeout - you snooze you lose! 😋",
colour=cfg.COLOR,
title="TIMEOUT Screener Menu",
).set_author(
name=cfg.AUTHOR_NAME,
icon_url=cfg.AUTHOR_ICON_URL,
)
await ctx.send(embed=embed)
def setup(bot: discord.ext.commands.Bot):
gst_bot.add_cog(ScreenerCommands(bot))
| 5,582 |
432 | /* @(#)wwiomux.c 8.1 (Berkeley) 6/6/93 */
/* $NetBSD: wwiomux.c,v 1.14 2009/04/14 08:50:06 lukem Exp $ */
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* <NAME> at The University of California, Berkeley.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#if !defined(OLD_TTY) && !defined(TIOCPKT_DATA)
#include <sys/ioctl.h>
#endif
#include <sys/time.h>
#include <poll.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#include "ww.h"
/*
* Multiple window output handler.
* The idea is to copy window outputs to the terminal, via the
* display package. We try to give wwcurwin highest priority.
* The only return conditions are when there is keyboard input
* and when a child process dies.
* When there's nothing to do, we sleep in a select().
* The history of this routine is interesting.
*/
void
wwiomux(void)
{
struct ww *w;
nfds_t nfd;
int i;
int volatile dostdin; /* avoid longjmp clobbering */
char volatile c; /* avoid longjmp clobbering */
char *p;
int millis;
char noblock = 0;
static struct pollfd *pfd = NULL;
static nfds_t maxfds = 0;
c = 0; /* XXXGCC -Wuninitialized */
for (;;) {
if (wwinterrupt()) {
wwclrintr();
return;
}
nfd = 0;
for (w = wwhead.ww_forw; w != &wwhead; w = w->ww_forw) {
if (w->ww_pty < 0 || w->ww_obq >= w->ww_obe)
continue;
nfd++;
}
if (maxfds <= ++nfd) { /* One more for the fd=0 case below */
struct pollfd *npfd = pfd == NULL ?
malloc(sizeof(*pfd) * nfd) :
realloc(pfd, sizeof(*pfd) * nfd);
if (npfd == NULL) {
warn("will retry");
if (pfd)
free(pfd);
pfd = NULL;
maxfds = 0;
return;
}
pfd = npfd;
maxfds = nfd;
}
nfd = 0;
for (w = wwhead.ww_forw; w != &wwhead; w = w->ww_forw) {
if (w->ww_pty < 0)
continue;
if (w->ww_obq < w->ww_obe) {
pfd[nfd].fd = w->ww_pty;
pfd[nfd++].events = POLLIN;
}
if (w->ww_obq > w->ww_obp &&
!ISSET(w->ww_pflags, WWP_STOPPED))
noblock = 1;
}
if (wwibq < wwibe) {
dostdin = nfd;
pfd[nfd].fd = 0;
pfd[nfd++].events = POLLIN;
} else {
dostdin = -1;
}
if (!noblock) {
if (wwcurwin != 0)
wwcurtowin(wwcurwin);
wwupdate();
wwflush();
(void) setjmp(wwjmpbuf);
wwsetjmp = 1;
if (wwinterrupt()) {
wwsetjmp = 0;
wwclrintr();
return;
}
/* XXXX */
millis = 30000;
} else {
millis = 10;
}
wwnselect++;
i = poll(pfd, nfd, millis);
wwsetjmp = 0;
noblock = 0;
if (i < 0)
wwnselecte++;
else if (i == 0)
wwnselectz++;
else {
if (dostdin != -1 && (pfd[dostdin].revents & POLLIN) != 0)
wwrint();
nfd = 0;
for (w = wwhead.ww_forw; w != &wwhead; w = w->ww_forw) {
int n;
if (w->ww_pty < 0)
continue;
if (w->ww_pty != pfd[nfd].fd)
continue;
if ((pfd[nfd++].revents & POLLIN) == 0)
continue;
wwnwread++;
p = w->ww_obq;
if (w->ww_type == WWT_PTY) {
if (p == w->ww_ob) {
w->ww_obp++;
w->ww_obq++;
} else
p--;
c = *p;
}
n = read(w->ww_pty, p, w->ww_obe - p);
if (n < 0) {
wwnwreade++;
(void) close(w->ww_pty);
w->ww_pty = -1;
} else if (n == 0) {
wwnwreadz++;
(void) close(w->ww_pty);
w->ww_pty = -1;
} else if (w->ww_type != WWT_PTY) {
wwnwreadd++;
wwnwreadc += n;
w->ww_obq += n;
} else if (*p == TIOCPKT_DATA) {
n--;
wwnwreadd++;
wwnwreadc += n;
w->ww_obq += n;
} else {
wwnwreadp++;
if (*p & TIOCPKT_STOP)
SET(w->ww_pflags, WWP_STOPPED);
if (*p & TIOCPKT_START)
CLR(w->ww_pflags, WWP_STOPPED);
if (*p & TIOCPKT_FLUSHWRITE) {
CLR(w->ww_pflags, WWP_STOPPED);
w->ww_obq = w->ww_obp =
w->ww_ob;
}
}
if (w->ww_type == WWT_PTY)
*p = c;
}
}
/*
* Try the current window first, if there is output
* then process it and go back to the top to try again.
* This can lead to starvation of the other windows,
* but presumably that what we want.
* Update will eventually happen when output from wwcurwin
* dies down.
*/
if ((w = wwcurwin) != NULL && w->ww_pty >= 0 &&
w->ww_obq > w->ww_obp &&
!ISSET(w->ww_pflags, WWP_STOPPED)) {
int n = wwwrite(w, w->ww_obp, w->ww_obq - w->ww_obp);
if ((w->ww_obp += n) == w->ww_obq)
w->ww_obq = w->ww_obp = w->ww_ob;
noblock = 1;
continue;
}
for (w = wwhead.ww_forw; w != &wwhead; w = w->ww_forw)
if (w->ww_pty >= 0 && w->ww_obq > w->ww_obp &&
!ISSET(w->ww_pflags, WWP_STOPPED)) {
int n = wwwrite(w, w->ww_obp,
w->ww_obq - w->ww_obp);
if ((w->ww_obp += n) == w->ww_obq)
w->ww_obq = w->ww_obp = w->ww_ob;
if (wwinterrupt())
break;
}
}
}
| 2,943 |
634 | <reponame>halotroop2288/consulo
/*
* Copyright 2013-2020 consulo.io
*
* 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 consulo.ui.desktop.internal.image;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.JBUI;
import consulo.awt.TargetAWT;
import consulo.ui.image.Image;
import consulo.ui.color.ColorValue;
import javax.annotation.Nonnull;
import javax.swing.*;
import java.awt.*;
/**
* @author VISTALL
* @since 2020-08-09
*/
public class DesktopColorizeImageImpl extends JBUI.CachingScalableJBIcon<DesktopColorizeImageImpl> implements Image {
private final Icon myBaseImage;
private final ColorValue myColorValue;
public DesktopColorizeImageImpl(Icon baseImage, ColorValue colorValue) {
myBaseImage = baseImage;
myColorValue = colorValue;
}
@Nonnull
@Override
protected DesktopColorizeImageImpl copy() {
return new DesktopColorizeImageImpl(myBaseImage, myColorValue);
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
IconUtil.colorize(myBaseImage, TargetAWT.to(myColorValue)).paintIcon(c, g, x, y);
}
@Override
public int getIconWidth() {
return myBaseImage.getIconWidth();
}
@Override
public int getIconHeight() {
return myBaseImage.getIconHeight();
}
@Override
public int getHeight() {
return getIconHeight();
}
@Override
public int getWidth() {
return getIconWidth();
}
}
| 605 |
852 | #ifndef HLTJetCollectionsFilter_h
#define HLTJetCollectionsFilter_h
#include "HLTrigger/HLTcore/interface/HLTFilter.h"
#include "DataFormats/HLTReco/interface/TriggerFilterObjectWithRefs.h"
#include "DataFormats/HLTReco/interface/TriggerTypeDefs.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/InputTag.h"
namespace edm {
class ConfigurationDescriptions;
}
//
// class declaration
//
template <typename jetType>
class HLTJetCollectionsFilter : public HLTFilter {
public:
explicit HLTJetCollectionsFilter(const edm::ParameterSet&);
~HLTJetCollectionsFilter() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
bool hltFilter(edm::Event&,
const edm::EventSetup&,
trigger::TriggerFilterObjectWithRefs& filterproduct) const override;
private:
edm::InputTag inputTag_; // input tag identifying jet collections
edm::InputTag originalTag_; // input tag original jet collection
double minJetPt_; // jet pt threshold in GeV
double maxAbsJetEta_; // jet |eta| range
unsigned int minNJets_; // number of required jets passing cuts after cleaning
int triggerType_;
edm::EDGetTokenT<std::vector<
edm::RefVector<std::vector<jetType>, jetType, edm::refhelper::FindUsingAdvance<std::vector<jetType>, jetType>>>>
m_theJetToken;
};
#endif //HLTJetCollectionsFilter_h
| 525 |
3,913 | <filename>yudao-admin-server/src/main/java/cn/iocoder/yudao/adminserver/modules/system/controller/logger/vo/operatelog/SysOperateLogExcelVO.java
package cn.iocoder.yudao.adminserver.modules.system.controller.logger.vo.operatelog;
import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat;
import cn.iocoder.yudao.framework.excel.core.convert.DictConvert;
import cn.iocoder.yudao.adminserver.modules.system.enums.SysDictTypeConstants;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.util.Date;
/**
* 操作日志 Excel 导出响应 VO
*/
@Data
public class SysOperateLogExcelVO {
@ExcelProperty("日志编号")
private Long id;
@ExcelProperty("操作模块")
private String module;
@ExcelProperty("操作名")
private String name;
@ExcelProperty(value = "操作类型", converter = DictConvert.class)
@DictFormat(SysDictTypeConstants.OPERATE_TYPE)
private String type;
@ExcelProperty("操作人")
private String userNickname;
@ExcelProperty(value = "操作结果") // 成功 or 失败
private String successStr;
@ExcelProperty("操作日志")
private Date startTime;
@ExcelProperty("执行时长")
private Integer duration;
}
| 517 |
310 | <filename>gear/software/e/ed.json
{
"name": "ed",
"description": "A line text editor for Unix.",
"url": "https://en.wikipedia.org/wiki/Ed_(text_editor)"
} | 59 |
463 | # pylint: disable=missing-class-docstring,too-few-public-methods,pointless-statement,expression-not-assigned
"""
Checks that class used in a subscript supports subscription
(i.e. defines __class_getitem__ method).
"""
import typing
class Subscriptable:
def __class_getitem__(cls, params):
pass
Subscriptable[0]
Subscriptable()[0] # [unsubscriptable-object]
a: typing.List[int]
| 137 |
380 | package n10s;
import n10s.graphconfig.RDFParserConfig;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFParseException;
public abstract class ConfiguredStatementHandler implements RDFHandler {
public abstract RDFParserConfig getParserConfig();
public class TripleLimitReached extends RDFParseException {
public TripleLimitReached(String s) {
super(s);
}
}
}
| 137 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.