repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
allansrc/fuchsia
|
src/media/playback/mediaplayer/fidl/fidl_video_renderer.h
|
<filename>src/media/playback/mediaplayer/fidl/fidl_video_renderer.h
// Copyright 2018 The Fuchsia 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 SRC_MEDIA_PLAYBACK_MEDIAPLAYER_FIDL_FIDL_VIDEO_RENDERER_H_
#define SRC_MEDIA_PLAYBACK_MEDIAPLAYER_FIDL_FIDL_VIDEO_RENDERER_H_
#include <fuchsia/media/cpp/fidl.h>
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async/cpp/wait.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <queue>
#include <fbl/array.h>
#include "src/lib/ui/base_view/base_view.h"
#include "src/media/playback/mediaplayer/metrics/packet_timing_tracker.h"
#include "src/media/playback/mediaplayer/render/video_renderer.h"
namespace media_player {
// VideoRenderer that renders video via FIDL services.
class FidlVideoRenderer : public VideoRenderer, public ServiceProvider {
public:
static std::shared_ptr<FidlVideoRenderer> Create(sys::ComponentContext* component_context);
FidlVideoRenderer(sys::ComponentContext* component_context);
~FidlVideoRenderer() override;
// VideoRenderer implementation.
const char* label() const override;
void Dump(std::ostream& os) const override;
void ConfigureConnectors() override;
void OnInputConnectionReady(size_t input_index) override;
void OnNewInputSysmemToken(size_t output_index) override;
void FlushInput(bool hold_frame, size_t input_index, fit::closure callback) override;
void PutInputPacket(PacketPtr packet, size_t input_index) override;
const std::vector<std::unique_ptr<StreamTypeSet>>& GetSupportedStreamTypes() override {
return supported_stream_types_;
}
void SetStreamType(const StreamType& stream_type) override;
void Prime(fit::closure callback) override;
fuchsia::math::Size video_size() const override;
fuchsia::math::Size pixel_aspect_ratio() const override;
// ServiceProvider implementation.
void ConnectToService(std::string service_path, zx::channel channel) override;
// Registers a callback that's called when the values returned by |video_size|
// or |pixel_aspect_ratio| change.
void SetGeometryUpdateCallback(fit::closure callback);
// Creates a view.
void CreateView(fuchsia::ui::views::ViewToken view_token);
protected:
// Renderer overrides.
void OnTimelineTransition() override;
private:
static constexpr uint32_t kPacketDemand = 3;
// Used to determine when all the |ImagePipe|s have released a buffer.
class ReleaseTracker : public fbl::RefCounted<ReleaseTracker> {
public:
// Constructs a |ReleaseTracker|. |packet| and |renderer| are both required.
ReleaseTracker(PacketPtr packet, std::shared_ptr<FidlVideoRenderer> renderer);
~ReleaseTracker();
private:
PacketPtr packet_;
std::shared_ptr<FidlVideoRenderer> renderer_;
};
struct Image {
Image();
// Called when |release_fence_| is released.
void WaitHandler(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status,
const zx_packet_signal_t* signal);
uint32_t buffer_index_;
uint32_t image_id_;
// If the |ImagePipe| channel closes unexpectedly, all the |Images|
// associated with the view are deleted, so this |release_tracker_| no
// longer prevents the renderer from releaseing the packet.
fbl::RefPtr<ReleaseTracker> release_tracker_;
zx::event release_fence_;
// |release_fence_| owns the handle that |wait_| references so it's
// important that |wait_| be destroyed first when the destructor runs.
// Members are destroyed bottom to top, so |wait_| must be below
// |release_fence_|.
async::WaitMethod<Image, &Image::WaitHandler> wait_;
};
class View : public scenic::BaseView {
public:
View(scenic::ViewContext context, std::shared_ptr<FidlVideoRenderer> renderer);
~View() override;
void AddBufferCollection(uint32_t buffer_collection_id,
fuchsia::sysmem::BufferCollectionTokenPtr token);
void RemoveBufferCollection(uint32_t buffer_collection_id);
// Adds the black image to the image pipe.
void AddBlackImage(uint32_t image_id, uint32_t buffer_collection_id, uint32_t buffer_index,
fuchsia::sysmem::ImageFormat_2 image_format);
// Removes the old images from the image pipe, if images were added previously, and adds new
// images. |image_count| images are added with buffer indexes starting with 0 and image ids
// starting with |image_id_base|.
void UpdateImages(uint32_t image_id_base, uint32_t image_count, uint32_t buffer_collection_id,
fuchsia::sysmem::ImageFormat_2 image_format);
// Presents the black image using the |ImagePipe|.
void PresentBlackImage(uint32_t image_id, uint64_t presentation_time);
// Presents an image using the |ImagePipe|.
void PresentImage(uint32_t buffer_index, uint64_t presentation_time,
fbl::RefPtr<ReleaseTracker> release_tracker, async_dispatcher_t* dispatcher);
private:
// |scenic::BaseView|
void OnSceneInvalidated(fuchsia::images::PresentationInfo presentation_info) override;
// |scenic::SessionListener|
void OnScenicError(std::string error) override { FX_LOGS(ERROR) << "Scenic Error " << error; }
std::shared_ptr<FidlVideoRenderer> renderer_;
scenic::EntityNode entity_node_;
scenic::ShapeNode image_pipe_node_;
scenic::Material image_pipe_material_;
fuchsia::images::ImagePipe2Ptr image_pipe_;
uint32_t image_width_;
uint32_t image_height_;
uint32_t display_width_;
uint32_t display_height_;
fbl::Array<Image> images_;
bool black_image_added_ = false;
// Disallow copy, assign and move.
View(const View&) = delete;
View(View&&) = delete;
View& operator=(const View&) = delete;
View& operator=(View&&) = delete;
};
// Alocates a buffer for a black image.
void AllocateBlackBuffer();
// Updates the images added to the image pipes associated with the views.
void UpdateImages();
// Presents a black image immediately.
void PresentBlackImage();
// Present |packet| at |scenic_presentation_time|.
void PresentPacket(PacketPtr packet, int64_t scenic_presentation_time);
// Called when all image pipes have released an image that was submitted for
// presentation.
void PacketReleased(PacketPtr packet);
// Completes a pending flush if all packets (except maybe the held frame) are
// released.
void MaybeCompleteFlush();
// Checks |packet| for a revised stream type and updates state accordingly.
void CheckForRevisedStreamType(const PacketPtr& packet);
// Determines whether we need more packets.
bool need_more_packets() const {
return !flushed_ && !end_of_stream_pending() &&
(presented_packets_not_released_ + packets_awaiting_presentation_.size()) <
kPacketDemand;
}
bool have_valid_image_format() {
return image_format_.coded_width != 0 && image_format_.coded_height != 0;
}
sys::ComponentContext* component_context_;
fuchsia::ui::scenic::ScenicPtr scenic_;
std::vector<std::unique_ptr<StreamTypeSet>> supported_stream_types_;
bool input_connection_ready_ = false;
zx::vmo black_image_vmo_;
fuchsia::sysmem::ImageFormat_2 image_format_{.coded_width = 0,
.coded_height = 0,
.pixel_aspect_ratio_width = 1,
.pixel_aspect_ratio_height = 1};
uint32_t presented_packets_not_released_ = 0;
bool flushed_ = true;
fit::closure flush_callback_;
bool flush_hold_frame_;
bool initial_packet_presented_ = false;
std::queue<PacketPtr> packets_awaiting_presentation_;
std::unique_ptr<View> view_;
fit::closure prime_callback_;
fit::closure geometry_update_callback_;
uint32_t image_id_base_ = 2; // 1 is reserved for the black image.
uint32_t next_image_id_base_ = 2;
fuchsia::sysmem::BufferCollectionPtr black_image_buffer_collection_;
fuchsia::sysmem::BufferCollectionTokenPtr black_image_buffer_collection_token_;
fuchsia::sysmem::BufferCollectionTokenPtr black_image_buffer_collection_token_for_pipe_;
int64_t prev_scenic_presentation_time_ = 0;
PacketTimingTracker arrivals_;
// Disallow copy, assign and move.
FidlVideoRenderer(const FidlVideoRenderer&) = delete;
FidlVideoRenderer(FidlVideoRenderer&&) = delete;
FidlVideoRenderer& operator=(const FidlVideoRenderer&) = delete;
FidlVideoRenderer& operator=(FidlVideoRenderer&&) = delete;
};
} // namespace media_player
#endif // SRC_MEDIA_PLAYBACK_MEDIAPLAYER_FIDL_FIDL_VIDEO_RENDERER_H_
|
niklas/Tirade
|
lib/tasks/globalize.rake
|
namespace :tirade do
namespace :locales do
desc <<-EODESC
Initialize the given locale with the data already saved in the real content types.
EODESC
task :init, [:locale] => [:environment] do |task, args|
locale = args.locale
if locale.blank?
STDERR.puts "please give a locale to initialize"
exit
end
I18n.locale = locale = locale.to_sym
Tirade::ActiveRecord::Content.classes.each do |klass|
next unless klass.respond_to?(:globalize_options)
STDERR.puts "Initializing locale #{locale} for #{klass.name}"
klass.without_timestamps do
klass.all.each do |record|
unless record.translated_locales.include?(locale)
record.update_attributes record.attributes
end
end
end
end
end
end
end
|
vmarc/knooppuntnet
|
server/src/main/scala/kpn/server/api/analysis/pages/location/LocationChangesPageBuilder.scala
|
<reponame>vmarc/knooppuntnet
package kpn.server.api.analysis.pages.location
import kpn.api.common.Language
import kpn.api.common.location.LocationChangesPage
import kpn.api.common.location.LocationChangesParameters
import kpn.api.custom.LocationKey
trait LocationChangesPageBuilder {
def build(language: Language, locationKey: LocationKey, parameters: LocationChangesParameters): Option[LocationChangesPage]
}
|
Enderderder/SonyEngine
|
PS4Engine/PS4Engine/api_gnm/basic-sample/basic-sample.cpp
|
/* SIE CONFIDENTIAL
PlayStation(R)4 Programmer Tool Runtime Library Release 05.008.001
* Copyright (C) 2016 Sony Interactive Entertainment Inc.
* All Rights Reserved.
*/
#include "../framework/sample_framework.h"
#include "../framework/simple_mesh.h"
#include "../framework/gnf_loader.h"
#include "../framework/frame.h"
#include "std_cbuffer.h"
#include <vector>
using namespace sce;
namespace
{
Framework::GnmSampleFramework framework;
}
int main(int argc, const char *argv[])
{
framework.processCommandLine(argc, argv);
framework.m_config.m_lightingIsMeaningful = true;
framework.initialize( "Basic",
"Sample code to demonstrate rendering a torus.",
"This sample program displays a torus with per-pixel albedo and normal.");
class Frame
{
public:
sce::Gnmx::GnmxGfxContext m_commandBuffer;
Constants *m_constants;
};
Frame frames[3];
SCE_GNM_ASSERT(framework.m_config.m_buffers <= 3);
for(unsigned buffer = 0; buffer < framework.m_config.m_buffers; ++buffer)
{
Frame *frame = &frames[buffer];
createCommandBuffer(&frame->m_commandBuffer,&framework,buffer);
framework.m_allocators.allocate((void**)&frame->m_constants,SCE_KERNEL_WB_ONION,sizeof(*frame->m_constants),4,Gnm::kResourceTypeConstantBufferBaseAddress,"Buffer %d Command Buffer",buffer);
}
int error = 0;
Framework::VsShader vertexShader;
Framework::PsShader pixelShader;
Gnm::Texture textures[2];
error = Framework::LoadVsMakeFetchShader(&vertexShader, Framework::ReadFile("/app0/basic-sample/shader_vv.sb"), &framework.m_allocators);
error = Framework::LoadPsShader(&pixelShader, Framework::ReadFile("/app0/basic-sample/shader_p.sb"), &framework.m_allocators);
error = Framework::loadTextureFromGnf(&textures[0], Framework::ReadFile("/app0/assets/icelogo-color.gnf"), 0, &framework.m_allocators);
SCE_GNM_ASSERT(error == Framework::kGnfErrorNone);
error = Framework::loadTextureFromGnf(&textures[1], Framework::ReadFile("/app0/assets/icelogo-normal.gnf"), 0, &framework.m_allocators);
SCE_GNM_ASSERT(error == Framework::kGnfErrorNone);
textures[0].setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // this texture is never bound as an RWTexture, so it's OK to mark it as read-only.
textures[1].setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // this texture is never bound as an RWTexture, so it's OK to mark it as read-only.
Gnm::Sampler trilinearSampler;
trilinearSampler.init();
trilinearSampler.setMipFilterMode(Gnm::kMipFilterModeLinear);
trilinearSampler.setXyFilterMode(Gnm::kFilterModeBilinear, Gnm::kFilterModeBilinear);
Framework::SimpleMesh torusMesh;
BuildTorusMesh(&framework.m_allocators, "Torus", &torusMesh, 0.8f, 0.2f, 64, 32, 4, 1);
while (!framework.m_shutdownRequested)
{
Framework::GnmSampleFramework::Buffer *bufferCpuIsWriting = framework.m_buffer + framework.getIndexOfBufferCpuIsWriting();
Frame *frame = frames + framework.getIndexOfBufferCpuIsWriting();
Gnmx::GnmxGfxContext *gfxc = &frame->m_commandBuffer;
gfxc->reset();
framework.BeginFrame(*gfxc);
// Render the scene:
Gnm::PrimitiveSetup primSetupReg;
primSetupReg.init();
primSetupReg.setCullFace(Gnm::kPrimitiveSetupCullFaceBack);
primSetupReg.setFrontFace(Gnm::kPrimitiveSetupFrontFaceCcw);
gfxc->setPrimitiveSetup(primSetupReg);
// Clear
Gnmx::Toolkit::SurfaceUtil::clearRenderTarget(*gfxc, &bufferCpuIsWriting->m_renderTarget, framework.getClearColor());
Gnmx::Toolkit::SurfaceUtil::clearDepthTarget(*gfxc, &bufferCpuIsWriting->m_depthTarget, 1.f);
gfxc->setRenderTargetMask(0xF);
gfxc->setActiveShaderStages(Gnm::kActiveShaderStagesVsPs);
gfxc->setRenderTarget(0, &bufferCpuIsWriting->m_renderTarget);
gfxc->setDepthRenderTarget(&bufferCpuIsWriting->m_depthTarget);
Gnm::DepthStencilControl dsc;
dsc.init();
dsc.setDepthControl(Gnm::kDepthControlZWriteEnable, Gnm::kCompareFuncLess);
dsc.setDepthEnable(true);
gfxc->setDepthStencilControl(dsc);
gfxc->setupScreenViewport(0, 0, bufferCpuIsWriting->m_renderTarget.getWidth(), bufferCpuIsWriting->m_renderTarget.getHeight(), 0.5f, 0.5f);
gfxc->setVsShader(vertexShader.m_shader, 0, vertexShader.m_fetchShader, &vertexShader.m_offsetsTable);
gfxc->setPsShader(pixelShader.m_shader, &pixelShader.m_offsetsTable);
torusMesh.SetVertexBuffer(*gfxc, Gnm::kShaderStageVs);
const float radians = framework.GetSecondsElapsedApparent() * 0.5f;
const Matrix4 m = Matrix4::rotationZYX(Vector3(radians,radians,0.f));
Constants *constants = frame->m_constants;
constants->m_modelView = transpose(framework.m_worldToViewMatrix*m);
constants->m_modelViewProjection = transpose(framework.m_viewProjectionMatrix*m);
constants->m_lightPosition = framework.getLightPositionInViewSpace();
constants->m_lightColor = framework.getLightColor();
constants->m_ambientColor = framework.getAmbientColor();
constants->m_lightAttenuation = Vector4(1, 0, 0, 0);
Gnm::Buffer constantBuffer;
constantBuffer.initAsConstantBuffer(constants, sizeof(Constants));
constantBuffer.setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // it's a constant buffer, so read-only is OK
gfxc->setConstantBuffers(Gnm::kShaderStageVs, 0, 1, &constantBuffer);
gfxc->setConstantBuffers(Gnm::kShaderStagePs, 0, 1, &constantBuffer);
gfxc->setTextures(Gnm::kShaderStagePs, 0, 2, textures);
gfxc->setSamplers(Gnm::kShaderStagePs, 0, 1, &trilinearSampler);
gfxc->setPrimitiveType(torusMesh.m_primitiveType);
gfxc->setIndexSize(torusMesh.m_indexType);
gfxc->drawIndex(torusMesh.m_indexCount, torusMesh.m_indexBuffer);
framework.EndFrame(*gfxc);
}
Frame *frame = frames + framework.getIndexOfBufferCpuIsWriting();
Gnmx::GnmxGfxContext *gfxc = &frame->m_commandBuffer;
framework.terminate(*gfxc);
return 0;
}
|
clh161/douban_movie
|
src/app/routes.js
|
<filename>src/app/routes.js<gh_stars>1-10
const HOT = 'hot';
export default {
HOT,
};
|
zeiq-co/zeiq-base
|
packages/web/src/components/forms/ContactForm.js
|
import 'twin.macro';
import React from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
import PropTypes from 'prop-types';
import Button from '../atoms/Button';
import TextInputGroup from '../elements/TextInputGroup';
import TextAreaGroup from '../elements/TextAreaGroup';
const formId = 'ContactForm';
const ContactForm = ({
values,
touched,
errors,
isSubmitting,
handleSubmit,
handleChange,
handleBlur,
}) => {
return (
<form tw="flex flex-wrap" onSubmit={handleSubmit} id={formId}>
<div tw="p-2 w-full">
<TextInputGroup
label="Your Name"
name="name"
value={values.name}
onChange={handleChange}
onBlur={handleBlur}
error={errors.name && touched.name ? errors.name : undefined}
/>
</div>
<div tw="p-2 w-full">
<TextInputGroup
label="Your Email"
name="email"
type="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
error={errors.email && touched.email ? errors.email : undefined}
/>
</div>
<div tw="p-2 w-full">
<TextAreaGroup
label="Your Message"
name="message"
type="message"
value={values.message}
onChange={handleChange}
onBlur={handleBlur}
error={errors.message && touched.message ? errors.message : undefined}
/>
</div>
<div tw="p-2 w-full">
<Button type="submit" form={formId} isLoading={isSubmitting}>
Submit
</Button>
</div>
</form>
);
};
ContactForm.defaultProps = {
enableReinitialize: true,
initialValues: {},
onSubmit: () => {},
};
ContactForm.propTypes = {
enableReinitialize: PropTypes.bool,
initialValues: PropTypes.object,
onSubmit: PropTypes.func,
};
export default withFormik({
mapPropsToValues: () => ({
name: '',
email: '',
message: '',
}),
validationSchema: Yup.object().shape({
name: Yup.string().required('Name is required!'),
email: Yup.string()
.email('Invalid email address')
.required('Email is required!'),
message: Yup.string().required('Message is required!'),
}),
handleSubmit: (values, { setSubmitting, props }) => {
console.log('handleSubmit', values);
props.onSubmit(values).finally(() => {
setSubmitting(false);
});
},
displayName: formId, // helps with React DevTools
})(ContactForm);
|
le520/MelonAccoutingBackend
|
src/main/java/com/nwpu/melonbookkeeping/util/TokenProvider.java
|
<reponame>le520/MelonAccoutingBackend<gh_stars>0
package com.nwpu.melonbookkeeping.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.nwpu.melonbookkeeping.entity.User;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import java.security.Signature;
/**
* Token工具类,用于生成和验证token
*/
public class TokenProvider {
private static final String key = "<KEY>";
/**
* 获取一个Token
*
* @param user 用户
* @return token
*/
public static String getToken(User user) {
return JWT.create()
.withSubject(user.getUserName())
.withClaim("userId", user.getId())
.sign(Algorithm.HMAC256(key));
}
/**
* 验证一个token
*
* @param token 要验证的token
* @return 验证结果
*/
public static boolean verifyToken(String token) {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(key))
.build();
try {
jwtVerifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 获取token存储的用户的id
*
* @param token token
* @return 用户的id
*/
public static int getUserId(String token) {
if (verifyToken(token)) {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("userId").asInt();
} else {
return -1;
}
}
}
|
sdslabs/gctl
|
client/fetchError.go
|
<gh_stars>10-100
package openapi
import (
"encoding/json"
)
func fetchError(b []byte) string {
var res InlineResponse400
if err := json.Unmarshal(b, &res); err != nil {
return "Error in fetching errors"
}
return res.Error
}
|
AutonomicPerfectionist/myrobotlab
|
src/org/myrobotlab/arduino/DeviceSummary.java
|
package org.myrobotlab.arduino;
import java.io.Serializable;
public class DeviceSummary implements Serializable {
private static final long serialVersionUID = 1L;
String name;
Integer id;
String type;
Integer typeId;
public DeviceSummary(String name, int id, String type, int typeId){
this.name = name;
this.id = id;
this.type = type;
this.typeId = typeId;
}
}
|
navikt/sykefravaer
|
js/landingsside/din-situasjon/BekreftFeilLeder.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { Knapp } from 'nav-frontend-knapper';
import { getHtmlLedetekst, getLedetekst } from '../../digisyfoNpm';
import { naermesteLeder as naermesteLederPt } from '../../propTypes/index';
import Feilstripe from '../../components/Feilstripe';
export const LederAvkreftet = ({ onLukk }) => {
return (
<div>
<h3 className="hode hode--suksess panel__tittel">{getLedetekst('sykefravaer.endre-naermeste-leder.kvittering.tittel')}</h3>
<div className="knapperad">
<Knapp
className="knapp js-lukk"
onClick={(e) => {
e.preventDefault();
onLukk();
}}
>
Lukk
</Knapp>
</div>
</div>
);
};
LederAvkreftet.propTypes = {
onLukk: PropTypes.func,
};
const BekreftFeilLeder = ({
leder, onAvbryt, avkreftLeder, avkrefter, avkreftFeilet,
}) => {
const knappClassName = 'knapp knapp--fare blokk--s js-bekreft';
return (
<div>
<div className={avkreftFeilet ? 'blokk' : ''}>
<h3 className="modal__tittel">{getLedetekst('sykefravaer.endre-naermeste-leder.tittel')}</h3>
<div dangerouslySetInnerHTML={getHtmlLedetekst('sykefravaer.endre-naermeste-leder.melding', {
'%LEDER%': leder.navn,
'%ARBEIDSGIVER%': leder.organisasjonsnavn,
})} />
</div>
<Feilstripe vis={avkreftFeilet} />
<div className="knapperad">
<Knapp
htmlType="button"
disabled={avkrefter}
className={knappClassName}
spinner={avkrefter}
onClick={() => {
avkreftLeder(leder.orgnummer);
}}>
Ja, jeg er sikker
</Knapp>
<p>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<a
className="lenke js-avbryt"
href="#"
role="button"
onClick={(e) => {
e.preventDefault();
onAvbryt();
}}>
Avbryt
</a>
</p>
</div>
</div>
);
};
BekreftFeilLeder.propTypes = {
leder: naermesteLederPt,
onAvbryt: PropTypes.func,
avkreftLeder: PropTypes.func,
avkrefter: PropTypes.bool,
avkreftFeilet: PropTypes.bool,
};
export default BekreftFeilLeder;
|
NickNichollsCitrix/ShareFile-ObjectiveC
|
ShareFileSDK/ShareFileSDK/Generated Code/Models/SFAsyncOperation.h
|
<filename>ShareFileSDK/ShareFileSDK/Generated Code/Models/SFAsyncOperation.h
//
// SFAsyncOperation.h
//
// Autogenerated by a tool
// Copyright (c) 2016 Citrix ShareFile. All rights reserved.
//
#import "SFODataObject.h"
@class SFAccount;
@class SFZone;
@class SFItem;
@class SFUser;
@interface SFAsyncOperation : SFODataObject
{
}
/**
Operation type
*/
@property (nonatomic, strong) NSString *Operation;
/**
ShareFile Account
*/
@property (nonatomic, strong) SFAccount *Account;
/**
Represents the Zone that is driving the asynchronous operation process. It
may be null if the operation is driven by the control plane.
*/
@property (nonatomic, strong) SFZone *AuthorityZone;
/**
Source Item for the operation.
*/
@property (nonatomic, strong) SFItem *Source;
/**
User that initiated the operation
*/
@property (nonatomic, strong) SFUser *User;
/**
Operation creation date
*/
@property (nonatomic, strong) NSDate *CreationDate;
/**
Operation state. States 'Created' and 'Scheduled' indicate the operation is
in progress; States 'Success' and 'Failure' indicate the operatoin is finalized
*/
@property (nonatomic, strong) NSString *State;
/**
Last time the operation state was modified
*/
@property (nonatomic, strong) NSDate *UpdateDate;
/**
Target Item for the operation.
*/
@property (nonatomic, strong) SFItem *Target;
/**
Batch Identifier for an asynchronous operation that includes multiple Items - for
example, a recursive Copy will create a single AsyncOp instance per file, all sharing
the same BatchID
*/
@property (nonatomic, strong) NSString *BatchID;
/**
Item ID used as source for the Batch operation
*/
@property (nonatomic, strong) NSString *BatchSourceID;
/**
Item ID used as target for the Batch operation
*/
@property (nonatomic, strong) NSString *BatchTargetID;
/**
BatchProgress indicates the progress of the Batch operation
*/
@property (nonatomic, strong) NSNumber *BatchProgress;
/**
Batch Operation state. State 'Scheduled' indicate the operation is
in progress; States 'Success' and 'Failure' indicate the operation is finalized
*/
@property (nonatomic, strong) NSString *BatchState;
@property (nonatomic, strong) NSNumber *BatchTotal;
@end
|
hadjri/evergreen
|
vendor/github.com/evergreen-ci/shrub/operations_test.go
|
<filename>vendor/github.com/evergreen-ci/shrub/operations_test.go<gh_stars>0
package shrub
import (
"errors"
"fmt"
"testing"
)
func TestWellformedOperations(t *testing.T) {
cases := map[string]Command{
"subprocess.exec": CmdExec{},
"shell.exec": CmdExecShell{},
"subprocess.scripting": CmdSubprocessScripting{},
"s3Copy.copy": CmdS3Copy{},
"s3.get": CmdS3Get{},
"s3.put": CmdS3Put{AWSKey: "foo", AWSSecret: "bar", LocalFile: "baz"},
"s3.push": CmdS3Push{},
"s3.pull": CmdS3Pull{},
"git.get_project": CmdGetProject{},
"attach.artifacts": CmdAttachArtifacts{},
"attach.results": CmdResultsJSON{},
"attach.xunit_results": CmdResultsXunit{},
"gotest.parse_files": CmdResultsGoTest{LegacyFormat: true},
"gotest.parse_json": CmdResultsGoTest{JSONFormat: true},
"archive.zip_pack": CmdArchiveCreate{Format: ZIP},
"archive.targz_pack": CmdArchiveCreate{Format: TARBALL},
"archive.zip_extract": CmdArchiveExtract{Format: ZIP},
"archive.targz_extract": CmdArchiveExtract{Format: TARBALL},
"archive.auto_extract": CmdArchiveExtract{Format: ArchiveFormat("auto")},
"host.create": CmdHostCreate{},
"host.list": CmdHostList{},
"expansions.update": CmdExpansionsUpdate{},
"expansions.write": CmdExpansionsWrite{},
"json.send": CmdJSONSend{},
"perf.send": CmdPerfSend{},
"timeout.update": CmdTimeoutUpdate{},
}
for name, cmd := range cases {
t.Run("Validate_"+name, func(t *testing.T) {
assert(t, cmd.Validate() == nil, fmt.Sprintf("validation for %T (%s)", cmd, name))
})
t.Run("Resolve_"+name, func(t *testing.T) {
defer catch(t, name, "resolve")
rcmd := cmd.Resolve()
require(t, rcmd != nil, fmt.Sprintf("resolution for %T (%s)", cmd, name))
assert(t, rcmd.CommandName == name, name, "not equal to", rcmd.FunctionName)
})
}
}
type unmarshableCmd struct {
name string
}
func (u unmarshableCmd) Name() string { return "foo" }
func (u unmarshableCmd) Validate() error { return nil }
func (u unmarshableCmd) Resolve() *CommandDefinition { panic("always") }
func (u unmarshableCmd) MarshalJSON() ([]byte, error) {
return nil, errors.New("always")
}
func TestPoorlyFormedOperations(t *testing.T) {
cases := map[string]Command{
"s3put.empty": CmdS3Put{},
"s3put.nocreds": CmdS3Put{LocalFile: "baz"},
"s3put.nofile": CmdS3Put{AWSKey: "foo", AWSSecret: "bar"},
"s3put.nosecret": CmdS3Put{AWSKey: "foo", LocalFile: "baz"},
"s3put.nokey": CmdS3Put{AWSSecret: "bar", LocalFile: "baz"},
"gotest.empty": CmdResultsGoTest{},
"gotest.both": CmdResultsGoTest{JSONFormat: true, LegacyFormat: true},
"archive.create_auto": CmdArchiveCreate{Format: ArchiveFormat("auto")},
"archive.invalid": CmdArchiveExtract{Format: ArchiveFormat("bleh")},
}
for name, cmd := range cases {
t.Run("ValidateFailsFor_"+name, func(t *testing.T) {
assert(t, cmd.Validate() != nil, name)
})
t.Run("ResolvePanicsFor_"+name, func(t *testing.T) {
defer expect(t, name)
rcmd := cmd.Resolve()
assert(t, rcmd == nil)
})
}
t.Run("AlwaysPanicsWhenCannotMarshal", func(t *testing.T) {
defer expect(t, "marshaling")
res := exportCmd(unmarshableCmd{name: "sad"})
assert(t, res == nil)
})
}
|
amoodie/DeltaMetrics
|
docs/source/pyplots/plot/document_variableset.py
|
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import deltametrics as dm
vs = dm.plot.VariableSet()
N = 256
gradient = np.linspace(0, 1, N)
gradient = np.vstack((gradient, gradient))
def over_coordinates(ax_lims):
tri_low = np.array([[0, 0],
[0 - 10, 0.5],
[0, 1]])
tri_high = np.array([[N, 0],
[N + 10, 0.5],
[N, 1]])
name_xy = np.array([-240, 0.8])
label_xy = np.array([-240, 0.4])
return tri_low, tri_high, name_xy, label_xy
def show_an_info(Info, ax):
"""Show a specific info.
"""
ax_lims = ax.get_position().get_points()
tri_low, tri_high, name_xy, label_xy = over_coordinates(ax_lims)
ax.imshow(gradient, aspect='auto', cmap=Info.cmap)
if not Info.norm:
ax.set_xticks([])
else:
ax.set_xticks([Info.vmin])
ax.add_patch(mpl.patches.Polygon(tri_low, closed=True,
color=Info.cmap._rgba_over, clip_on=False))
ax.add_patch(mpl.patches.Polygon(tri_high, closed=True,
color=Info.cmap._rgba_over, clip_on=False))
ax.text(name_xy[0], name_xy[1], 'name: ' + Info.name, fontsize=8,
horizontalalignment='left', verticalalignment='bottom')
ax.text(label_xy[0], label_xy[1], 'label: ' + Info.label, fontsize=8,
horizontalalignment='left', verticalalignment='bottom')
ax.set_yticks([])
ax.set_ylim([0, 1])
ax.tick_params(labelsize=8)
nvi = len(vs.known_list)
fig, ax = plt.subplots(nvi, 1, figsize=(8, 8))
plt.tight_layout()
plt.subplots_adjust(left=0.487, right=0.95)
ax = ax.flatten()
for i, v in enumerate(vs.known_list):
show_an_info(vs[v], ax[i])
plt.show()
|
kirschmackey/Arduino_Core_STM32
|
libraries/SrcWrapper/src/LL/stm32yyxx_ll_pka.c
|
<reponame>kirschmackey/Arduino_Core_STM32
#ifdef STM32L4xx
#include "stm32l4xx_ll_pka.c"
#endif
#ifdef STM32WBxx
#include "stm32wbxx_ll_pka.c"
#endif
|
VINichkov/JobsGalore
|
lib/server_dictionary.rb
|
require 'singleton'
class ServerDictionary
include Singleton
attr_accessor :arr_word
def initialize
Rails.logger.debug("ServerDictionary::initialize: load dictionary")
@arr_word = index(File.open('db/dictionary.txt').map{|file| file.delete("\n")})
end
def where(query=nil, arg={limit:10})
Rails.logger.debug("ServerDictionary::where query = \'#{query}\' limit = \'#{arg[:limit]}\'")
rez=[]
if query
i=0
list_of_words = @arr_word[:"#{query[0]}"]
if list_of_words.present?
list_of_words.each do |name|
if i<arg[:limit]
if name >=query
rez<<{id: i,name:name}
i+=1
end
else
break;
end
end
else
rez<<{id: i,name:query}
end
end
rez
end
private
def index(arg)
Rails.logger.debug("ServerDictionary::index: add index")
index = {}
arg.each do |word|
index[:"#{word[0]}"] ? index[:"#{word[0]}"] << word : index[:"#{word[0]}"] = [word]
end
index
end
end
|
qinkai2060/Moya-MVVM
|
WARProfile/Classes/UserEvent/JournalFriendCycle/FeedList/View/WARFeedPopUpView.h
|
<reponame>qinkai2060/Moya-MVVM
//
// WARFeedPopUpView.h
// WARControl
//
// Created by helaf on 2018/4/28.
//
#import <UIKit/UIKit.h>
@protocol WARFeedPopUpViewDelegate <NSObject>
- (CGFloat)currentValueOffset; //expects value in the range 0.0 - 1.0
- (void)animationDidStart;
@end
@interface WARFeedPopUpView : UIView
@property (weak, nonatomic) id <WARFeedPopUpViewDelegate> delegate;
- (UIColor *)color;
- (void)setColor:(UIColor *)color;
- (UIColor *)opaqueColor;
- (void)setTextColor:(UIColor *)textColor;
- (void)setFont:(UIFont *)font;
- (void)setString:(NSString *)string;
- (void)setAnimatedColors:(NSArray *)animatedColors;
- (void)setAnimationOffset:(CGFloat)offset;
- (void)setArrowCenterOffset:(CGFloat)offset;
- (CGSize)popUpSizeForString:(NSString *)string;
- (void)show;
- (void)hide;
@end
|
prince776/CodeBook
|
kactl/stress-tests/number-theory/ModSum.cpp
|
#include "../utilities/template.h"
#include "../../content/number-theory/ModSum.h"
ll rmod(ll x, ll m) {
x %= m;
return x < 0 ? x + m : x;
}
ll rdiv(ll x, ll y) {
x -= rmod(x, y);
return x / y;
}
ll modsum_naive(ll to, ll c, ll k, ll m) {
ll res = 0;
for (int i = 0; i < (int)to; ++i)
res += rmod(c + k * i, m);
return res;
}
ll divsum_naive(ll to, ll c, ll k, ll m) {
ll res = 0;
for (int i = 0; i < (int)to; ++i)
res += rdiv(c + k * i, m);
return res;
}
void compare() {
rep(to,0,30) {
rep(c,-30,30) {
rep(k,-30,30) {
rep(m,1,30) {
ll a = modsum(to, c, k, m);
ll b = modsum_naive(to, c, k, m);
if (a != b) {
cout << "differ! " << to << ' ' << c << ' ' << k << ' ' << m << ": " << a << " vs " << b << endl;
assert(false);
}
}
}
}
}
}
void compare2() {
rep(to,0,30) {
rep(c,0,30) {
rep(k,0,30) {
rep(m,1,30) {
ll a = divsum(to, c, k, m);
ll b = divsum_naive(to, c, k, m);
if (a != b) {
cout << "differ! " << to << ' ' << c << ' ' << k << ' ' << m << ": " << a << " vs " << b << endl;
assert(false);
}
}
}
}
}
}
int main() {
compare(); compare2();
assert(modsum((ll)1e18, 1, 2, 3) == (ll)1e18);
rep(i,0,50) {
ll t = (ll)rand() << 3;
ll c = (ll)rand() << 2;
ll k = (ll)rand() << 2;
ll m = (ll)rand() >> 2;
assert(abs(modsum(t, c, k, m) / ((long double)m/2 * t) - 1)<1e-5);
}
cout<<"Tests passed!"<<endl;
return 0;
}
|
DirectXceriD/gridgain
|
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/tree/io/PagePartitionMetaIO.java
|
/*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*
*/
package org.apache.ignite.internal.processors.cache.persistence.tree.io;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.pagemem.PageUtils;
import org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState;
import org.apache.ignite.internal.util.GridStringBuilder;
/**
* IO for partition metadata pages.
*/
public class PagePartitionMetaIO extends PageMetaIO {
/** */
private static final int SIZE_OFF = PageMetaIO.END_OF_PAGE_META;
/** */
private static final int UPDATE_CNTR_OFF = SIZE_OFF + 8;
/** */
private static final int GLOBAL_RMV_ID_OFF = UPDATE_CNTR_OFF + 8;
/** */
private static final int PARTITION_STATE_OFF = GLOBAL_RMV_ID_OFF + 8;
/** */
private static final int NEXT_PART_META_PAGE_OFF = PARTITION_STATE_OFF + 1;
/** End of page partition meta. */
static final int END_OF_PARTITION_PAGE_META = NEXT_PART_META_PAGE_OFF + 8;
/** */
public static final IOVersions<PagePartitionMetaIO> VERSIONS = new IOVersions<>(
new PagePartitionMetaIO(1),
new PagePartitionMetaIOV2(2)
);
/** {@inheritDoc} */
@Override public void initNewPage(long pageAddr, long pageId, int pageSize) {
super.initNewPage(pageAddr, pageId, pageSize);
setSize(pageAddr, 0);
setUpdateCounter(pageAddr, 0);
setGlobalRemoveId(pageAddr, 0);
setPartitionState(pageAddr, (byte)-1);
setCountersPageId(pageAddr, 0);
}
/**
* @param ver Version.
*/
public PagePartitionMetaIO(int ver) {
super(T_PART_META, ver);
}
/**
* @param pageAddr Page address.
* @return Partition size.
*/
public long getSize(long pageAddr) {
return PageUtils.getLong(pageAddr, SIZE_OFF);
}
/**
* @param pageAddr Page address.
* @param size Partition size.
*/
public boolean setSize(long pageAddr, long size) {
if (getSize(pageAddr) == size)
return false;
PageUtils.putLong(pageAddr, SIZE_OFF, size);
return true;
}
/**
* @param pageAddr Page address.
* @return Partition update counter.
*/
public long getUpdateCounter(long pageAddr) {
return PageUtils.getLong(pageAddr, UPDATE_CNTR_OFF);
}
/**
* @param pageAddr Page address.
* @param cntr Partition update counter.
*/
public boolean setUpdateCounter(long pageAddr, long cntr) {
if (getUpdateCounter(pageAddr) == cntr)
return false;
PageUtils.putLong(pageAddr, UPDATE_CNTR_OFF, cntr);
return true;
}
/**
* @param pageAddr Page address.
* @return Global remove ID.
*/
public long getGlobalRemoveId(long pageAddr) {
return PageUtils.getLong(pageAddr, GLOBAL_RMV_ID_OFF);
}
/**
* @param pageAddr Page address.
* @param rmvId Global remove ID.
*/
public boolean setGlobalRemoveId(long pageAddr, long rmvId) {
if (getGlobalRemoveId(pageAddr) == rmvId)
return false;
PageUtils.putLong(pageAddr, GLOBAL_RMV_ID_OFF, rmvId);
return true;
}
/**
* @param pageAddr Page address.
*/
public byte getPartitionState(long pageAddr) {
return PageUtils.getByte(pageAddr, PARTITION_STATE_OFF);
}
/**
* @param pageAddr Partition metadata page address.
* @param state State.
*/
public boolean setPartitionState(long pageAddr, byte state) {
if (getPartitionState(pageAddr) == state)
return false;
PageUtils.putByte(pageAddr, PARTITION_STATE_OFF, state);
return true;
}
/**
* Returns partition counters page identifier, page with caches in cache group sizes.
*
* @param pageAddr Partition metadata page address.
* @return Next meta partial page ID or {@code 0} if it does not exist.
*/
public long getCountersPageId(long pageAddr) {
return PageUtils.getLong(pageAddr, NEXT_PART_META_PAGE_OFF);
}
/**
* Sets new reference to partition counters page (logical cache sizes).
*
* @param pageAddr Partition metadata page address.
* @param cntrsPageId New cache sizes page ID.
*/
public void setCountersPageId(long pageAddr, long cntrsPageId) {
PageUtils.putLong(pageAddr, NEXT_PART_META_PAGE_OFF, cntrsPageId);
}
/**
* Returns partition pending tree root. Pending tree is used to tracking expiring entries.
*
* @param pageAddr Page address.
* @return Pending Tree root page.
*/
public long getPendingTreeRoot(long pageAddr) {
throw new UnsupportedOperationException("Per partition pending tree is not supported by " +
"this PagePartitionMetaIO version: ver=" + getVersion());
}
/**
* Sets new partition pending tree root.
*
* @param pageAddr Page address.
* @param treeRoot Pending Tree root
*/
public void setPendingTreeRoot(long pageAddr, long treeRoot) {
throw new UnsupportedOperationException("Per partition pending tree is not supported by " +
"this PagePartitionMetaIO version: ver=" + getVersion());
}
/** {@inheritDoc} */
@Override protected void printPage(long pageAddr, int pageSize, GridStringBuilder sb) throws IgniteCheckedException {
super.printPage(pageAddr, pageSize, sb);
byte state = getPartitionState(pageAddr);
sb.a(",\nPagePartitionMeta[\n\tsize=").a(getSize(pageAddr))
.a(",\n\tupdateCounter=").a(getUpdateCounter(pageAddr))
.a(",\n\tglobalRemoveId=").a(getGlobalRemoveId(pageAddr))
.a(",\n\tpartitionState=").a(state).a("(").a(GridDhtPartitionState.fromOrdinal(state)).a(")")
.a(",\n\tcountersPageId=").a(getCountersPageId(pageAddr))
.a("\n]");
}
}
|
ysp2000/tju-solutions
|
2404 Bin Packing/Main.java
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
}
BufferedReader in;
int N;
int L;
int[] l;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
N = nextInt();
L = nextInt();
l = new int [N];
for (int i = 0; i < N; i++)
l[i] = nextInt();
Arrays.sort(l);
int ans = N;
int i = 0;
int j = N - 1;
while (i < j) {
if (l[i] + l[j] <= L) {
ans--;
i++;
}
j--;
}
System.out.println(ans);
}
int nextInt() throws IOException {
int n, c;
for (c = in.read(); c < '0' || c > '9'; c = in.read());
for (n = 0; '0' <= c && c <= '9'; c = in.read())
n = n * 10 + c - '0';
return n;
}
}
|
PepperCode1/canvas
|
src/main/java/grondag/canvas/pipeline/BufferDebug.java
|
<filename>src/main/java/grondag/canvas/pipeline/BufferDebug.java<gh_stars>1-10
/*
* Copyright © Contributing Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional copyright and licensing notices may apply for content that was
* included from other projects. For more information, see ATTRIBUTION.md.
*/
package grondag.canvas.pipeline;
import org.lwjgl.glfw.GLFW;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.network.chat.TextComponent;
import grondag.canvas.CanvasMod;
import grondag.canvas.config.Configurator;
import grondag.canvas.pipeline.config.ImageConfig;
import grondag.canvas.pipeline.config.PipelineConfig;
import grondag.canvas.varia.GFX;
public class BufferDebug {
private static final int NONE = 0;
private static final int SHIFT = 1;
private static final int ALT = 2;
private static final int MENU = 3;
private static final int CTL = 4;
private static final String[] PREFIX = {"none: ", "shift: ", "alt: ", "menu: ", "ctl: "};
private static int[] VIEWS = new int[5];
private static int viewCount;
private static int[] glIds;
private static int[] lods;
private static int[] layers;
private static String[] labels;
private static boolean[] isDepth;
private static boolean[] isArray;
private static int keyOption;
private static boolean enabled = false;
static void init(PipelineConfig config) {
int imageCount = 0;
for (final ImageConfig img : config.images) {
imageCount += img.lod + 1 * img.depth;
}
glIds = new int[imageCount];
lods = new int[imageCount];
labels = new String[imageCount];
layers = new int[imageCount];
isDepth = new boolean[imageCount];
isArray = new boolean[imageCount];
int i = 0;
for (final ImageConfig img : config.images) {
final int glId = Pipeline.getImage(img.name).glId();
for (int lod = 0; lod <= img.lod; ++lod) {
for (int layer = 0; layer < img.depth; ++layer) {
labels[i] = img.name + " lod=" + lod + " layer=" + layer;
glIds[i] = glId;
lods[i] = lod;
layers[i] = layer;
isDepth[i] = img.pixelFormat == GFX.GL_DEPTH_COMPONENT;
isArray[i] = img.target == GFX.GL_TEXTURE_2D_ARRAY;
++i;
}
}
}
if (viewCount != imageCount) {
viewCount = imageCount;
VIEWS[NONE] = 0;
VIEWS[SHIFT] = Math.min(1, imageCount - 1);
VIEWS[ALT] = Math.min(2, imageCount - 1);
VIEWS[CTL] = Math.min(3, imageCount - 1);
VIEWS[MENU] = Math.min(4, imageCount - 1);
}
}
/**
* Don't call unless enabled - doesn't check.
*/
@SuppressWarnings("resource")
public static void render() {
while (CanvasMod.DEBUG_TOGGLE.consumeClick()) {
enabled = !enabled;
Minecraft.getInstance().player.displayClientMessage(new TextComponent("Buffer Debug Mode Toggle: " + (enabled ? "ON" : "OFF")), true);
}
if (!enabled) {
return;
}
final long handle = Minecraft.getInstance().getWindow().getWindow();
if (InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_LEFT_SHIFT) || InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_RIGHT_SHIFT)) {
keyOption = SHIFT;
} else if (InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_LEFT_ALT) || InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_RIGHT_ALT)) {
keyOption = ALT;
} else if (InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_LEFT_CONTROL) || InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_RIGHT_CONTROL)) {
keyOption = CTL;
} else if (InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_LEFT_SUPER) || InputConstants.isKeyDown(handle, GLFW.GLFW_KEY_RIGHT_SUPER)) {
keyOption = MENU;
} else {
keyOption = NONE;
}
while (CanvasMod.DEBUG_PREV.consumeClick()) {
VIEWS[keyOption] = (VIEWS[keyOption] + viewCount - 1) % viewCount;
Minecraft.getInstance().player.displayClientMessage(new TextComponent(labels[VIEWS[keyOption]]), true);
}
while (CanvasMod.DEBUG_NEXT.consumeClick()) {
VIEWS[keyOption] = (VIEWS[keyOption] + viewCount + 1) % viewCount;
Minecraft.getInstance().player.displayClientMessage(new TextComponent(labels[VIEWS[keyOption]]), true);
}
final int n = VIEWS[keyOption];
PipelineManager.renderDebug(glIds[n], lods[n], layers[n], isDepth[n], isArray[n]);
}
public static void renderOverlay(PoseStack matrices, Font fontRenderer) {
if (!enabled || !Configurator.enableBufferDebug) {
return;
}
for (int i = 0; i < 5; ++i) {
String string = PREFIX[i] + labels[VIEWS[i]];
int forecolor = 0xC0C0C0;
int backcolor = 0x60606060;
if (i == keyOption) {
forecolor = 0xFFFF80;
backcolor = 0xFF000000;
string += " (selected)";
}
final int k = fontRenderer.width(string);
final int m = 100 + 12 * i;
GuiComponent.fill(matrices, 20, m - 1, 22 + k + 1, m + 9, backcolor);
fontRenderer.draw(matrices, string, 21, m, forecolor);
}
}
}
|
demonpratapdemon/CodingDSA
|
src/dynamic_programming/GoldMine.java
|
<gh_stars>0
/**
*
*/
package dynamic_programming;
/**
* @author PRATAP
*
*/
public class GoldMine {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] M = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } };
int ans = maxGold(M.length, M[0].length, M);
System.out.println(ans);
}
static int[][] neighbs = { { -1, -1 }, { 0, -1 }, { 1, -1 } };
static int maxGold(int n, int m, int M[][]) {
// code here
int max = Integer.MIN_VALUE;
int[][] dp = new int[n][m];
for (int i = 0; i < n; i++)
dp[i][0] = M[i][0];
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
for (int k = 0; k < neighbs.length; k++) {
int currI = i + neighbs[k][0];
int currJ = j + neighbs[k][1];
if (currI >= 0 && currI < n && currJ >= 0 && currJ < m) {
dp[i][j] = Math.max(dp[i][j], M[i][j] + dp[currI][currJ]);
}
}
}
}
for (int i = 0; i < n; i++)
max = Math.max(max, dp[i][m - 1]);
return max;
}
}
|
TheSench/solr-streams-dsl
|
src/main/java/com/github/thesench/solr/dsl/stream/expr/sources/Search.java
|
package com.github.thesench.solr.dsl.stream.expr.sources;
import com.github.thesench.solr.dsl.stream.expr.params.SearchParameter;
import org.apache.solr.client.solrj.io.stream.expr.StreamExpression;
public class Search {
private Search() {}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-source-reference.html#search">Stream Source Reference: search</a>
* @param collectionName
* @param params
* @return
*/
public static StreamExpression search(String collectionName, SearchParameter ...params) {
StreamExpression searchExpression = new StreamExpression("search").withParameter(collectionName);
for (SearchParameter param : params) {
searchExpression.addParameter(param);
}
return searchExpression;
}
}
|
inaand/compass
|
components/director/internal/labelfilter/labelfilter.go
|
<filename>components/director/internal/labelfilter/labelfilter.go<gh_stars>10-100
package labelfilter
import "github.com/kyma-incubator/compass/components/director/pkg/graphql"
// LabelFilter missing godoc
type LabelFilter struct {
Key string
Query *string
}
// FromGraphQL missing godoc
func FromGraphQL(in *graphql.LabelFilter) *LabelFilter {
return &LabelFilter{
Key: in.Key,
Query: in.Query,
}
}
// MultipleFromGraphQL missing godoc
func MultipleFromGraphQL(in []*graphql.LabelFilter) []*LabelFilter {
filters := make([]*LabelFilter, 0, len(in))
for _, f := range in {
filters = append(filters, FromGraphQL(f))
}
return filters
}
// NewForKey missing godoc
func NewForKey(key string) *LabelFilter {
return &LabelFilter{key, nil}
}
// NewForKeyWithQuery missing godoc
func NewForKeyWithQuery(key, query string) *LabelFilter {
return &LabelFilter{key, &query}
}
|
bjorndm/prebake
|
code/src/org/prebake/js/SandboxingWrapFactory.java
|
// Copyright 2010, <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 org.prebake.js;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.WrapFactory;
class SandboxingWrapFactory extends WrapFactory {
@Override
public Object wrap(
Context cx, Scriptable scope, Object javaObject, Class<?> staticType) {
// Deny reflective access up front. This should not be triggered due
// to getter filtering, but let's be paranoid.
if (javaObject != null
&& (javaObject instanceof Class<?>
|| javaObject instanceof ClassLoader
|| "java.lang.reflect".equals(
javaObject.getClass().getPackage().getName()))) {
return Context.getUndefinedValue();
}
// Make java arrays behave like native JS arrays.
// This breaks EQ, but is better than the alternative.
if (javaObject instanceof Object[]) {
Object[] javaArray = (Object[]) javaObject;
int n = javaArray.length;
Object[] wrappedElements = new Object[n];
Class<?> compType = javaArray.getClass().getComponentType();
for (int i = n; --i >= 0;) {
wrappedElements[i] = wrap(cx, scope, javaArray[i], compType);
}
NativeArray jsArray = new NativeArray(wrappedElements);
jsArray.setPrototype(ScriptableObject.getClassPrototype(scope, "Array"));
jsArray.setParentScope(scope);
return jsArray;
}
return super.wrap(cx, scope, javaObject, staticType);
}
@Override
public Scriptable wrapAsJavaObject(
Context cx, Scriptable scope, Object javaObject, Class<?> staticType) {
return new WrappedJavaObject(scope, javaObject, staticType);
}
private static final class WrappedJavaObject extends NativeJavaObject {
WrappedJavaObject(
Scriptable scope, Object javaObject, Class<?> staticType) {
super(scope, javaObject, staticType);
}
@Override
public Object get(String name, Scriptable start) {
// Deny access to all members of the base Object class since
// some of them enable reflection, and the others are mostly for
// serialization and timing which should not be accessible.
// The codeutopia implementation only blacklists getClass.
if (RhinoExecutor.OBJECT_CLASS_MEMBERS.contains(name)) {
return NOT_FOUND;
}
return super.get(name, start);
}
}
}
|
Otanikotani/pulumi-aws
|
sdk/python/pulumi_aws/dms/event_subscription.py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__all__ = ['EventSubscription']
class EventSubscription(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
enabled: Optional[pulumi.Input[bool]] = None,
event_categories: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
name: Optional[pulumi.Input[str]] = None,
sns_topic_arn: Optional[pulumi.Input[str]] = None,
source_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
source_type: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Provides a DMS (Data Migration Service) event subscription resource.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
example = aws.dms.EventSubscription("example",
enabled=True,
event_categories=[
"creation",
"failure",
],
sns_topic_arn=aws_sns_topic["example"]["arn"],
source_ids=[aws_dms_replication_task["example"]["replication_task_id"]],
source_type="replication-task",
tags={
"Name": "example",
})
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] enabled: Whether the event subscription should be enabled.
:param pulumi.Input[Sequence[pulumi.Input[str]]] event_categories: List of event categories to listen for, see `DescribeEventCategories` for a canonical list.
:param pulumi.Input[str] name: Name of event subscription.
:param pulumi.Input[str] sns_topic_arn: SNS topic arn to send events on.
:param pulumi.Input[Sequence[pulumi.Input[str]]] source_ids: Ids of sources to listen to.
:param pulumi.Input[str] source_type: Type of source for events. Valid values: `replication-instance` or `replication-task`
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['enabled'] = enabled
if event_categories is None:
raise TypeError("Missing required property 'event_categories'")
__props__['event_categories'] = event_categories
__props__['name'] = name
if sns_topic_arn is None:
raise TypeError("Missing required property 'sns_topic_arn'")
__props__['sns_topic_arn'] = sns_topic_arn
__props__['source_ids'] = source_ids
__props__['source_type'] = source_type
__props__['tags'] = tags
__props__['arn'] = None
super(EventSubscription, __self__).__init__(
'aws:dms/eventSubscription:EventSubscription',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
arn: Optional[pulumi.Input[str]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
event_categories: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
name: Optional[pulumi.Input[str]] = None,
sns_topic_arn: Optional[pulumi.Input[str]] = None,
source_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
source_type: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None) -> 'EventSubscription':
"""
Get an existing EventSubscription resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] enabled: Whether the event subscription should be enabled.
:param pulumi.Input[Sequence[pulumi.Input[str]]] event_categories: List of event categories to listen for, see `DescribeEventCategories` for a canonical list.
:param pulumi.Input[str] name: Name of event subscription.
:param pulumi.Input[str] sns_topic_arn: SNS topic arn to send events on.
:param pulumi.Input[Sequence[pulumi.Input[str]]] source_ids: Ids of sources to listen to.
:param pulumi.Input[str] source_type: Type of source for events. Valid values: `replication-instance` or `replication-task`
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["arn"] = arn
__props__["enabled"] = enabled
__props__["event_categories"] = event_categories
__props__["name"] = name
__props__["sns_topic_arn"] = sns_topic_arn
__props__["source_ids"] = source_ids
__props__["source_type"] = source_type
__props__["tags"] = tags
return EventSubscription(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def arn(self) -> pulumi.Output[str]:
return pulumi.get(self, "arn")
@property
@pulumi.getter
def enabled(self) -> pulumi.Output[Optional[bool]]:
"""
Whether the event subscription should be enabled.
"""
return pulumi.get(self, "enabled")
@property
@pulumi.getter(name="eventCategories")
def event_categories(self) -> pulumi.Output[Sequence[str]]:
"""
List of event categories to listen for, see `DescribeEventCategories` for a canonical list.
"""
return pulumi.get(self, "event_categories")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Name of event subscription.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="snsTopicArn")
def sns_topic_arn(self) -> pulumi.Output[str]:
"""
SNS topic arn to send events on.
"""
return pulumi.get(self, "sns_topic_arn")
@property
@pulumi.getter(name="sourceIds")
def source_ids(self) -> pulumi.Output[Optional[Sequence[str]]]:
"""
Ids of sources to listen to.
"""
return pulumi.get(self, "source_ids")
@property
@pulumi.getter(name="sourceType")
def source_type(self) -> pulumi.Output[Optional[str]]:
"""
Type of source for events. Valid values: `replication-instance` or `replication-task`
"""
return pulumi.get(self, "source_type")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "tags")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
|
JohanJacobs/Head_First_Design_Patterns
|
Chapter6_Command_Pattern/src/RemoteControl/RemoteTest.h
|
<gh_stars>0
#pragma once
#include <memory>
#include "Commands/CommandInterface.h"
namespace Remote
{
class RemoteTest
{
public:
RemoteTest()
{
}
void SetCommand(std::shared_ptr<Commands::CommandInterface> command)
{
m_Command = command;
}
void buttonWasPressed()
{
m_Command->Execute();
}
private:
std::shared_ptr<Commands::CommandInterface> m_Command;
};
}
|
stephanebachelier/next-auth
|
dist/server/routes/signout.js
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = signout;
var cookie = _interopRequireWildcard(require("../lib/cookie"));
var _dispatchEvent = _interopRequireDefault(require("../lib/dispatch-event"));
var _errorHandler = _interopRequireDefault(require("../../adapters/error-handler"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
async function signout(req, res) {
const {
adapter,
cookies,
events,
jwt,
callbackUrl,
logger
} = req.options;
const useJwtSession = req.options.session.jwt;
const sessionToken = req.cookies[cookies.sessionToken.name];
if (useJwtSession) {
try {
const decodedJwt = await jwt.decode({ ...jwt,
token: sessionToken
});
await (0, _dispatchEvent.default)(events.signOut, decodedJwt);
} catch (error) {}
} else {
const {
getSession,
deleteSession
} = (0, _errorHandler.default)(await adapter.getAdapter(req.options), logger);
try {
const session = await getSession(sessionToken);
await (0, _dispatchEvent.default)(events.signOut, session);
} catch (error) {}
try {
await deleteSession(sessionToken);
} catch (error) {
logger.error("SIGNOUT_ERROR", error);
}
}
cookie.set(res, cookies.sessionToken.name, "", { ...cookies.sessionToken.options,
maxAge: 0
});
return res.redirect(callbackUrl);
}
|
vunicjovan/xws
|
frontend/main-front/src/store/modules/chat.js
|
<filename>frontend/main-front/src/store/modules/chat.js
import chatApi from "@/api/Chat.js";
const state = {
messages: [],
};
const getters = {
getChat: (state) => state.messages,
};
const actions = {
getMessages({ commit }, userId) {
return new Promise((resolve, reject) => {
chatApi
.getMessages(userId)
.then((messages) => {
commit("setMessages", messages);
resolve();
})
.catch((error) => reject(error));
});
},
sendMessage({ commit }, message) {
return new Promise((resolve, reject) => {
chatApi
.sendMessage(message)
.then((data) => {
resolve(data);
})
.catch((error) => reject(error));
});
},
deleteMessage({ commit }, message) {
return new Promise((resolve, reject) => {
chatApi
.deleteMessage(message)
.then((data) => {
resolve(data);
})
.catch((error) => reject(error));
});
},
};
const mutations = {
setMessages: (state, messages) => (state.messages = messages),
};
export default {
state,
getters,
actions,
mutations,
};
|
imxiangpeng/webrtc
|
base/testutils.h
|
<reponame>imxiangpeng/webrtc
/*
* Copyright 2004 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_BASE_TESTUTILS_H__
#define WEBRTC_BASE_TESTUTILS_H__
// Utilities for testing rtc infrastructure in unittests
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
// X defines a few macros that stomp on types that gunit.h uses.
#undef None
#undef Bool
#endif
#include <algorithm>
#include <map>
#include <memory>
#include <vector>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/asyncsocket.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/nethelpers.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
#include "webrtc/base/stringencode.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/base/thread.h"
namespace testing {
using namespace rtc;
///////////////////////////////////////////////////////////////////////////////
// StreamSink - Monitor asynchronously signalled events from StreamInterface
// or AsyncSocket (which should probably be a StreamInterface.
///////////////////////////////////////////////////////////////////////////////
// Note: Any event that is an error is treaded as SSE_ERROR instead of that
// event.
enum StreamSinkEvent {
SSE_OPEN = SE_OPEN,
SSE_READ = SE_READ,
SSE_WRITE = SE_WRITE,
SSE_CLOSE = SE_CLOSE,
SSE_ERROR = 16
};
class StreamSink : public sigslot::has_slots<> {
public:
void Monitor(StreamInterface* stream) {
stream->SignalEvent.connect(this, &StreamSink::OnEvent);
events_.erase(stream);
}
void Unmonitor(StreamInterface* stream) {
stream->SignalEvent.disconnect(this);
// In case you forgot to unmonitor a previous object with this address
events_.erase(stream);
}
bool Check(StreamInterface* stream, StreamSinkEvent event, bool reset = true) {
return DoCheck(stream, event, reset);
}
int Events(StreamInterface* stream, bool reset = true) {
return DoEvents(stream, reset);
}
void Monitor(AsyncSocket* socket) {
socket->SignalConnectEvent.connect(this, &StreamSink::OnConnectEvent);
socket->SignalReadEvent.connect(this, &StreamSink::OnReadEvent);
socket->SignalWriteEvent.connect(this, &StreamSink::OnWriteEvent);
socket->SignalCloseEvent.connect(this, &StreamSink::OnCloseEvent);
// In case you forgot to unmonitor a previous object with this address
events_.erase(socket);
}
void Unmonitor(AsyncSocket* socket) {
socket->SignalConnectEvent.disconnect(this);
socket->SignalReadEvent.disconnect(this);
socket->SignalWriteEvent.disconnect(this);
socket->SignalCloseEvent.disconnect(this);
events_.erase(socket);
}
bool Check(AsyncSocket* socket, StreamSinkEvent event, bool reset = true) {
return DoCheck(socket, event, reset);
}
int Events(AsyncSocket* socket, bool reset = true) {
return DoEvents(socket, reset);
}
private:
typedef std::map<void*,int> EventMap;
void OnEvent(StreamInterface* stream, int events, int error) {
if (error) {
events = SSE_ERROR;
}
AddEvents(stream, events);
}
void OnConnectEvent(AsyncSocket* socket) {
AddEvents(socket, SSE_OPEN);
}
void OnReadEvent(AsyncSocket* socket) {
AddEvents(socket, SSE_READ);
}
void OnWriteEvent(AsyncSocket* socket) {
AddEvents(socket, SSE_WRITE);
}
void OnCloseEvent(AsyncSocket* socket, int error) {
AddEvents(socket, (0 == error) ? SSE_CLOSE : SSE_ERROR);
}
void AddEvents(void* obj, int events) {
EventMap::iterator it = events_.find(obj);
if (events_.end() == it) {
events_.insert(EventMap::value_type(obj, events));
} else {
it->second |= events;
}
}
bool DoCheck(void* obj, StreamSinkEvent event, bool reset) {
EventMap::iterator it = events_.find(obj);
if ((events_.end() == it) || (0 == (it->second & event))) {
return false;
}
if (reset) {
it->second &= ~event;
}
return true;
}
int DoEvents(void* obj, bool reset) {
EventMap::iterator it = events_.find(obj);
if (events_.end() == it)
return 0;
int events = it->second;
if (reset) {
it->second = 0;
}
return events;
}
EventMap events_;
};
///////////////////////////////////////////////////////////////////////////////
// StreamSource - Implements stream interface and simulates asynchronous
// events on the stream, without a network. Also buffers written data.
///////////////////////////////////////////////////////////////////////////////
class StreamSource : public StreamInterface {
public:
StreamSource() {
Clear();
}
void Clear() {
readable_data_.clear();
written_data_.clear();
state_ = SS_CLOSED;
read_block_ = 0;
write_block_ = SIZE_UNKNOWN;
}
void QueueString(const char* data) {
QueueData(data, strlen(data));
}
void QueueStringF(const char* format, ...) {
va_list args;
va_start(args, format);
char buffer[1024];
size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
RTC_CHECK(len < sizeof(buffer) - 1);
va_end(args);
QueueData(buffer, len);
}
void QueueData(const char* data, size_t len) {
readable_data_.insert(readable_data_.end(), data, data + len);
if ((SS_OPEN == state_) && (readable_data_.size() == len)) {
SignalEvent(this, SE_READ, 0);
}
}
std::string ReadData() {
std::string data;
// avoid accessing written_data_[0] if it is undefined
if (written_data_.size() > 0) {
data.insert(0, &written_data_[0], written_data_.size());
}
written_data_.clear();
return data;
}
void SetState(StreamState state) {
int events = 0;
if ((SS_OPENING == state_) && (SS_OPEN == state)) {
events |= SE_OPEN;
if (!readable_data_.empty()) {
events |= SE_READ;
}
} else if ((SS_CLOSED != state_) && (SS_CLOSED == state)) {
events |= SE_CLOSE;
}
state_ = state;
if (events) {
SignalEvent(this, events, 0);
}
}
// Will cause Read to block when there are pos bytes in the read queue.
void SetReadBlock(size_t pos) { read_block_ = pos; }
// Will cause Write to block when there are pos bytes in the write queue.
void SetWriteBlock(size_t pos) { write_block_ = pos; }
virtual StreamState GetState() const { return state_; }
virtual StreamResult Read(void* buffer, size_t buffer_len,
size_t* read, int* error) {
if (SS_CLOSED == state_) {
if (error) *error = -1;
return SR_ERROR;
}
if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
return SR_BLOCK;
}
size_t count = std::min(buffer_len, readable_data_.size() - read_block_);
memcpy(buffer, &readable_data_[0], count);
size_t new_size = readable_data_.size() - count;
// Avoid undefined access beyond the last element of the vector.
// This only happens when new_size is 0.
if (count < readable_data_.size()) {
memmove(&readable_data_[0], &readable_data_[count], new_size);
}
readable_data_.resize(new_size);
if (read) *read = count;
return SR_SUCCESS;
}
virtual StreamResult Write(const void* data, size_t data_len,
size_t* written, int* error) {
if (SS_CLOSED == state_) {
if (error) *error = -1;
return SR_ERROR;
}
if (SS_OPENING == state_) {
return SR_BLOCK;
}
if (SIZE_UNKNOWN != write_block_) {
if (written_data_.size() >= write_block_) {
return SR_BLOCK;
}
if (data_len > (write_block_ - written_data_.size())) {
data_len = write_block_ - written_data_.size();
}
}
if (written) *written = data_len;
const char* cdata = static_cast<const char*>(data);
written_data_.insert(written_data_.end(), cdata, cdata + data_len);
return SR_SUCCESS;
}
virtual void Close() { state_ = SS_CLOSED; }
private:
typedef std::vector<char> Buffer;
Buffer readable_data_, written_data_;
StreamState state_;
size_t read_block_, write_block_;
};
///////////////////////////////////////////////////////////////////////////////
// SocketTestClient
// Creates a simulated client for testing. Works on real and virtual networks.
///////////////////////////////////////////////////////////////////////////////
class SocketTestClient : public sigslot::has_slots<> {
public:
SocketTestClient() { Init(nullptr, AF_INET); }
SocketTestClient(AsyncSocket* socket) {
Init(socket, socket->GetLocalAddress().family());
}
SocketTestClient(const SocketAddress& address) {
Init(nullptr, address.family());
socket_->Connect(address);
}
AsyncSocket* socket() { return socket_.get(); }
void QueueString(const char* data) {
QueueData(data, strlen(data));
}
void QueueStringF(const char* format, ...) {
va_list args;
va_start(args, format);
char buffer[1024];
size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
RTC_CHECK(len < sizeof(buffer) - 1);
va_end(args);
QueueData(buffer, len);
}
void QueueData(const char* data, size_t len) {
send_buffer_.insert(send_buffer_.end(), data, data + len);
if (Socket::CS_CONNECTED == socket_->GetState()) {
Flush();
}
}
std::string ReadData() {
std::string data(&recv_buffer_[0], recv_buffer_.size());
recv_buffer_.clear();
return data;
}
bool IsConnected() const {
return (Socket::CS_CONNECTED == socket_->GetState());
}
bool IsClosed() const {
return (Socket::CS_CLOSED == socket_->GetState());
}
private:
typedef std::vector<char> Buffer;
void Init(AsyncSocket* socket, int family) {
if (!socket) {
socket = Thread::Current()->socketserver()
->CreateAsyncSocket(family, SOCK_STREAM);
}
socket_.reset(socket);
socket_->SignalConnectEvent.connect(this,
&SocketTestClient::OnConnectEvent);
socket_->SignalReadEvent.connect(this, &SocketTestClient::OnReadEvent);
socket_->SignalWriteEvent.connect(this, &SocketTestClient::OnWriteEvent);
socket_->SignalCloseEvent.connect(this, &SocketTestClient::OnCloseEvent);
}
void Flush() {
size_t sent = 0;
while (sent < send_buffer_.size()) {
int result = socket_->Send(&send_buffer_[sent],
send_buffer_.size() - sent);
if (result > 0) {
sent += result;
} else {
break;
}
}
size_t new_size = send_buffer_.size() - sent;
memmove(&send_buffer_[0], &send_buffer_[sent], new_size);
send_buffer_.resize(new_size);
}
void OnConnectEvent(AsyncSocket* socket) {
if (!send_buffer_.empty()) {
Flush();
}
}
void OnReadEvent(AsyncSocket* socket) {
char data[64 * 1024];
int result = socket_->Recv(data, arraysize(data), nullptr);
if (result > 0) {
recv_buffer_.insert(recv_buffer_.end(), data, data + result);
}
}
void OnWriteEvent(AsyncSocket* socket) {
if (!send_buffer_.empty()) {
Flush();
}
}
void OnCloseEvent(AsyncSocket* socket, int error) {
}
std::unique_ptr<AsyncSocket> socket_;
Buffer send_buffer_, recv_buffer_;
};
///////////////////////////////////////////////////////////////////////////////
// SocketTestServer
// Creates a simulated server for testing. Works on real and virtual networks.
///////////////////////////////////////////////////////////////////////////////
class SocketTestServer : public sigslot::has_slots<> {
public:
SocketTestServer(const SocketAddress& address)
: socket_(Thread::Current()->socketserver()
->CreateAsyncSocket(address.family(), SOCK_STREAM))
{
socket_->SignalReadEvent.connect(this, &SocketTestServer::OnReadEvent);
socket_->Bind(address);
socket_->Listen(5);
}
virtual ~SocketTestServer() {
clear();
}
size_t size() const { return clients_.size(); }
SocketTestClient* client(size_t index) const { return clients_[index]; }
SocketTestClient* operator[](size_t index) const { return client(index); }
void clear() {
for (size_t i=0; i<clients_.size(); ++i) {
delete clients_[i];
}
clients_.clear();
}
private:
void OnReadEvent(AsyncSocket* socket) {
AsyncSocket* accepted = static_cast<AsyncSocket*>(socket_->Accept(nullptr));
if (!accepted)
return;
clients_.push_back(new SocketTestClient(accepted));
}
std::unique_ptr<AsyncSocket> socket_;
std::vector<SocketTestClient*> clients_;
};
///////////////////////////////////////////////////////////////////////////////
// Unittest predicates which are similar to STREQ, but for raw memory
///////////////////////////////////////////////////////////////////////////////
inline AssertionResult CmpHelperMemEq(const char* expected_expression,
const char* expected_length_expression,
const char* actual_expression,
const char* actual_length_expression,
const void* expected,
size_t expected_length,
const void* actual,
size_t actual_length)
{
if ((expected_length == actual_length)
&& (0 == memcmp(expected, actual, expected_length))) {
return AssertionSuccess();
}
Message msg;
msg << "Value of: " << actual_expression
<< " [" << actual_length_expression << "]";
if (true) { //!actual_value.Equals(actual_expression)) {
size_t buffer_size = actual_length * 2 + 1;
char* buffer = STACK_ARRAY(char, buffer_size);
hex_encode(buffer, buffer_size,
reinterpret_cast<const char*>(actual), actual_length);
msg << "\n Actual: " << buffer << " [" << actual_length << "]";
}
msg << "\nExpected: " << expected_expression
<< " [" << expected_length_expression << "]";
if (true) { //!expected_value.Equals(expected_expression)) {
size_t buffer_size = expected_length * 2 + 1;
char* buffer = STACK_ARRAY(char, buffer_size);
hex_encode(buffer, buffer_size,
reinterpret_cast<const char*>(expected), expected_length);
msg << "\nWhich is: " << buffer << " [" << expected_length << "]";
}
return AssertionFailure(msg);
}
#define EXPECT_MEMEQ(expected, expected_length, actual, actual_length) \
EXPECT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
actual, actual_length)
#define ASSERT_MEMEQ(expected, expected_length, actual, actual_length) \
ASSERT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
actual, actual_length)
///////////////////////////////////////////////////////////////////////////////
// Helpers for initializing constant memory with integers in a particular byte
// order
///////////////////////////////////////////////////////////////////////////////
#define BYTE_CAST(x) static_cast<uint8_t>((x)&0xFF)
// Declare a N-bit integer as a little-endian sequence of bytes
#define LE16(x) BYTE_CAST(((uint16_t)x) >> 0), BYTE_CAST(((uint16_t)x) >> 8)
#define LE32(x) \
BYTE_CAST(((uint32_t)x) >> 0), BYTE_CAST(((uint32_t)x) >> 8), \
BYTE_CAST(((uint32_t)x) >> 16), BYTE_CAST(((uint32_t)x) >> 24)
#define LE64(x) \
BYTE_CAST(((uint64_t)x) >> 0), BYTE_CAST(((uint64_t)x) >> 8), \
BYTE_CAST(((uint64_t)x) >> 16), BYTE_CAST(((uint64_t)x) >> 24), \
BYTE_CAST(((uint64_t)x) >> 32), BYTE_CAST(((uint64_t)x) >> 40), \
BYTE_CAST(((uint64_t)x) >> 48), BYTE_CAST(((uint64_t)x) >> 56)
// Declare a N-bit integer as a big-endian (Internet) sequence of bytes
#define BE16(x) BYTE_CAST(((uint16_t)x) >> 8), BYTE_CAST(((uint16_t)x) >> 0)
#define BE32(x) \
BYTE_CAST(((uint32_t)x) >> 24), BYTE_CAST(((uint32_t)x) >> 16), \
BYTE_CAST(((uint32_t)x) >> 8), BYTE_CAST(((uint32_t)x) >> 0)
#define BE64(x) \
BYTE_CAST(((uint64_t)x) >> 56), BYTE_CAST(((uint64_t)x) >> 48), \
BYTE_CAST(((uint64_t)x) >> 40), BYTE_CAST(((uint64_t)x) >> 32), \
BYTE_CAST(((uint64_t)x) >> 24), BYTE_CAST(((uint64_t)x) >> 16), \
BYTE_CAST(((uint64_t)x) >> 8), BYTE_CAST(((uint64_t)x) >> 0)
// Declare a N-bit integer as a this-endian (local machine) sequence of bytes
#ifndef BIG_ENDIAN
#define BIG_ENDIAN 1
#endif // BIG_ENDIAN
#if BIG_ENDIAN
#define TE16 BE16
#define TE32 BE32
#define TE64 BE64
#else // !BIG_ENDIAN
#define TE16 LE16
#define TE32 LE32
#define TE64 LE64
#endif // !BIG_ENDIAN
///////////////////////////////////////////////////////////////////////////////
// Helpers for determining if X/screencasting is available (on linux).
#define MAYBE_SKIP_SCREENCAST_TEST() \
if (!testing::IsScreencastingAvailable()) { \
LOG(LS_WARNING) << "Skipping test, since it doesn't have the requisite " \
<< "X environment for screen capture."; \
return; \
} \
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
struct XDisplay {
XDisplay() : display_(XOpenDisplay(nullptr)) {}
~XDisplay() { if (display_) XCloseDisplay(display_); }
bool IsValid() const { return display_ != nullptr; }
operator Display*() { return display_; }
private:
Display* display_;
};
#endif
// Returns true if screencasting is available. When false, anything that uses
// screencasting features may fail.
inline bool IsScreencastingAvailable() {
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
XDisplay display;
if (!display.IsValid()) {
LOG(LS_WARNING) << "No X Display available.";
return false;
}
int ignored_int, major_version, minor_version;
if (!XRRQueryExtension(display, &ignored_int, &ignored_int) ||
!XRRQueryVersion(display, &major_version, &minor_version) ||
major_version < 1 ||
(major_version < 2 && minor_version < 3)) {
LOG(LS_WARNING) << "XRandr version: " << major_version << "."
<< minor_version;
LOG(LS_WARNING) << "XRandr is not supported or is too old (pre 1.3).";
return false;
}
#endif
return true;
}
} // namespace testing
#endif // WEBRTC_BASE_TESTUTILS_H__
|
cornhundred/clustergrammer
|
clustergrammer1/src/sidebar/set_up_opacity_slider.js
|
module.exports = function set_up_opacity_slider(sidebar){
var slider_container = sidebar
.append('div')
.classed('opacity_slider_container', true)
.style('margin-top', '5px')
.style('padding-left', '10px')
.style('padding-right', '10px');
slider_container
.append('div')
.classed('sidebar_text', true)
.classed('opacity_slider_text', true)
.style('margin-bottom', '3px')
.text('Opacity Slider');
slider_container
.append('div')
.classed('slider', true)
.classed('opacity_slider', true);
};
|
daid/SeriousProton2
|
src/graphics/gui/layout/layout.cpp
|
#include <sp2/graphics/gui/layout/layout.h>
namespace sp {
namespace gui {
LayoutClassRegistry* LayoutClassRegistry::first;
SP_REGISTER_LAYOUT("default", Layout);
void Layout::updateLoop(P<Widget> container, Rect2d rect)
{
do
{
int repeat_counter = 10;
require_repeat = false;
update(container, rect);
if (--repeat_counter < 1)
{
LOG(Warning, "Possible infinite loop in gui layout.");
return;
}
} while(require_repeat);
}
void Layout::update(P<Widget> container, Rect2d rect)
{
for(P<Widget> w : container->getChildren())
{
if (!w || !w->isVisible())
continue;
basicLayout(rect, *w);
}
}
void Layout::basicLayout(Rect2d rect, Widget* widget)
{
Vector2d result_position;
Vector2d result_size;
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::BottomLeft:
case Alignment::Left:
result_position.x = rect.position.x + widget->layout.position.x + widget->layout.margin.left;
if (widget->layout.fill_width)
result_size.x = rect.size.x - widget->layout.margin.left - widget->layout.margin.right + widget->layout.position.x;
else
result_size.x = widget->layout.size.x;
break;
case Alignment::Top:
case Alignment::Center:
case Alignment::Bottom:
if (widget->layout.fill_width)
result_size.x = rect.size.x - widget->layout.margin.left - widget->layout.margin.right;
else
result_size.x = widget->layout.size.x;
result_position.x = rect.position.x + rect.size.x / 2.0f - result_size.x / 2.0f;
break;
case Alignment::TopRight:
case Alignment::Right:
case Alignment::BottomRight:
result_position.x = rect.position.x + widget->layout.position.x + widget->layout.margin.left;
if (widget->layout.fill_width)
result_size.x = rect.size.x - widget->layout.margin.left - widget->layout.margin.right + widget->layout.position.x;
else
result_size.x = widget->layout.size.x;
result_position.x = rect.position.x + rect.size.x - widget->layout.margin.right + widget->layout.position.x - result_size.x;
break;
}
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::Top:
case Alignment::TopRight:
result_position.y = rect.position.y - widget->layout.position.y + widget->layout.margin.top;
if (widget->layout.fill_height)
result_size.y = rect.size.y - widget->layout.margin.top - widget->layout.margin.bottom - widget->layout.position.y;
else
result_size.y = widget->layout.size.y;
result_position.y = rect.position.y + rect.size.y - widget->layout.margin.top - widget->layout.position.y - result_size.y;
break;
case Alignment::Left:
case Alignment::Center:
case Alignment::Right:
if (widget->layout.fill_height)
result_size.y = rect.size.y - widget->layout.margin.top - widget->layout.margin.bottom;
else
result_size.y = widget->layout.size.y;
result_position.y = rect.position.y + rect.size.y / 2.0f - result_size.y / 2.0f;
break;
case Alignment::BottomLeft:
case Alignment::Bottom:
case Alignment::BottomRight:
result_position.y = rect.position.y - widget->layout.position.y + widget->layout.margin.bottom;
if (widget->layout.fill_height)
result_size.y = rect.size.y - widget->layout.margin.top - widget->layout.margin.bottom - widget->layout.position.y;
else
result_size.y = widget->layout.size.y;
break;
}
if (widget->layout.lock_aspect_ratio)
{
double aspect = widget->layout.size.x / widget->layout.size.y;
if (widget->layout.fill_height && widget->layout.fill_width)
{
double current_aspect = result_size.x / result_size.y;
if (current_aspect > aspect)
{
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::Left:
case Alignment::BottomLeft:
break;
case Alignment::Top:
case Alignment::Center:
case Alignment::Bottom:
result_position.x += (result_size.x - result_size.y * aspect) * 0.5;
break;
case Alignment::TopRight:
case Alignment::Right:
case Alignment::BottomRight:
result_position.x += result_size.x - result_size.y * aspect;
break;
}
result_size.x = result_size.y * aspect;
}
else
{
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::Top:
case Alignment::TopRight:
result_position.y += result_size.y - result_size.x / aspect;
break;
case Alignment::Left:
case Alignment::Center:
case Alignment::Right:
result_position.y += (result_size.y - result_size.x / aspect) * 0.5;
break;
case Alignment::BottomLeft:
case Alignment::Bottom:
case Alignment::BottomRight:
break;
}
result_size.y = result_size.x / aspect;
}
}
else if (widget->layout.fill_height)
{
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::Left:
case Alignment::BottomLeft:
break;
case Alignment::Top:
case Alignment::Center:
case Alignment::Bottom:
result_position.x += (result_size.x - result_size.y * aspect) * 0.5;
break;
case Alignment::TopRight:
case Alignment::Right:
case Alignment::BottomRight:
result_position.x += result_size.x - result_size.y * aspect;
break;
}
result_size.x = result_size.y * aspect;
}
else if (widget->layout.fill_width)
{
switch(widget->layout.alignment)
{
case Alignment::TopLeft:
case Alignment::Top:
case Alignment::TopRight:
result_position.y += result_size.y - result_size.x / aspect;
break;
case Alignment::Left:
case Alignment::Center:
case Alignment::Right:
result_position.y += (result_size.y - result_size.x / aspect) * 0.5;
break;
case Alignment::BottomLeft:
case Alignment::Bottom:
case Alignment::BottomRight:
break;
}
result_size.y = result_size.x / aspect;
}
}
sp::Vector2d pre_layout_size = widget->layout.size;
widget->updateLayout(result_position, result_size);
if (pre_layout_size != widget->layout.size)
{
require_repeat = true;
}
}
}//namespace gui
}//namespace sp
|
ArakniD/InvenTree
|
InvenTree/label/apps.py
|
<reponame>ArakniD/InvenTree
from django.apps import AppConfig
class LabelConfig(AppConfig):
name = 'label'
|
code-review-doctor/orchestra
|
orchestra/utils/tests/test_choices_enum.py
|
<reponame>code-review-doctor/orchestra
from orchestra.tests.helpers import OrchestraTestCase
from orchestra.utils.models import ChoicesEnum
class ModelUtilsTests(OrchestraTestCase):
def test_choices_enum(self):
class TestEnum(ChoicesEnum):
val0 = 'desc0'
val1 = 'desc1'
val2 = 'desc2'
self.assertEqual(TestEnum.val0.description, 'desc0')
self.assertEqual(TestEnum.val1.description, 'desc1')
self.assertEqual(TestEnum.val2.description, 'desc2')
self.assertEqual(TestEnum.val0.value, 0)
self.assertEqual(TestEnum.val1.value, 1)
self.assertEqual(TestEnum.val2.value, 2)
self.assertEqual(TestEnum.val0.name, 'val0')
self.assertEqual(TestEnum.val1.name, 'val1')
self.assertEqual(TestEnum.val2.name, 'val2')
expected_choices = [
(0, 'desc0'),
(1, 'desc1'),
(2, 'desc2'),
]
self.assertEqual(TestEnum.choices(), expected_choices)
expected_data = {
'val0': {
'description': 'desc0',
'value': 0
},
'val1': {
'description': 'desc1',
'value': 1
},
'val2': {
'description': 'desc2',
'value': 2
},
}
self.assertEqual(TestEnum.serialize(), expected_data)
|
M1TDoPHOT/DoPHOT_C
|
structs/imdev_struct.h
|
#ifndef IMDEV_STRUCT_H
#define IMDEV_STRUCT_H
struct
{
float** dxemp;
float** dyemp;
int** emp;
}imdev_;
//DXEMP[2*IHSIDE][2*IHSIDE]
//DYEMP[2*IHSIDE][2*IHSIDE]
//EMP[2*IHSIDE+1][2*IHSIDE+1]
#endif
|
kumarvgit/python3
|
ProgramFlow/tkinter/screen.py
|
<gh_stars>0
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
import os
mainWindow = tkinter.Tk()
mainWindow.title("Grid Demo")
mainWindow.geometry('640x480-8-200')
mainWindow['padx'] = 8
label= tkinter.Label(mainWindow, text="Tkinter Grid Demo")
label.grid(row=0, column=0, columnspan=3)
mainWindow.columnconfigure(0, weight=100)
mainWindow.columnconfigure(1, weight=1)
mainWindow.columnconfigure(2, weight=1000)
mainWindow.columnconfigure(3, weight=600)
mainWindow.columnconfigure(4, weight=1000)
mainWindow.rowconfigure(0, weight=1)
mainWindow.rowconfigure(1, weight=10)
mainWindow.rowconfigure(2, weight=1)
mainWindow.rowconfigure(3, weight=3)
mainWindow.rowconfigure(4, weight=3)
fileList = tkinter.Listbox(mainWindow)
fileList.grid(row=1, column=0, sticky='nsew', rowspan=2)
fileList.config(border=2, relief='sunken')
for zone in os.listdir('/usr/bin'): # '/Windows/System32'
fileList.insert(tkinter.END, zone)
listScroll = tkinter.Scrollbar(mainWindow, orient=tkinter.VERTICAL, command=fileList.yview)
listScroll.grid(row=1, column=1, sticky='nsw', rowspan=2)
fileList['yscrollcommand'] = listScroll.set
# frame for the radio buttons
optionFrame = tkinter.LabelFrame(mainWindow, text="File Details")
optionFrame.grid(row=1, column=2, sticky='ne')
rbValue = tkinter.IntVar()
rbValue.set(1)
# Radio buttons
radio1 = tkinter.Radiobutton(optionFrame, text="Filename", value=1, variable=rbValue)
radio2 = tkinter.Radiobutton(optionFrame, text="Path", value=2, variable=rbValue)
radio3 = tkinter.Radiobutton(optionFrame, text="Timestamp", value=3, variable=rbValue)
radio1.grid(row=0, column=0, sticky='w')
radio2.grid(row=1, column=0, sticky='w')
radio3.grid(row=2, column=0, sticky='w')
# Widget to display the result
resultLabel = tkinter.Label(mainWindow, text="Result")
resultLabel.grid(row=2, column=2, sticky='nw')
result = tkinter.Entry(mainWindow)
result.grid(row=2, column=2, sticky='sw')
# Frame for the time spinners
timeFrame = tkinter.LabelFrame(mainWindow, text="Time")
timeFrame.grid(row=3, column=0, sticky='new')
# Time spinners
hourSpinner = tkinter.Spinbox(timeFrame, width=2, values=tuple(range(0, 24)))
minuteSpinner = tkinter.Spinbox(timeFrame, width=2, from_=0, to=59)
secondSpinner = tkinter.Spinbox(timeFrame, width=2, from_=0, to=59)
hourSpinner.grid(row=0, column=0)
tkinter.Label(timeFrame, text=':').grid(row=0, column=1)
minuteSpinner.grid(row=0, column=2)
tkinter.Label(timeFrame, text=':').grid(row=0, column=3)
secondSpinner.grid(row=0, column=4)
timeFrame['padx'] = 36
# Frame for the date spinners
dateFrame = tkinter.Frame(mainWindow)
dateFrame.grid(row=4, column=0, sticky='new')
# Date labels
dayLabel = tkinter.Label(dateFrame, text="Day")
monthLabel = tkinter.Label(dateFrame, text="Month")
yearLabel = tkinter.Label(dateFrame, text="Year")
dayLabel.grid(row=0, column=0, sticky='w')
monthLabel.grid(row=0, column=1, sticky='w')
yearLabel.grid(row=0, column=2, sticky='w')
# Date spinners
daySpin = tkinter.Spinbox(dateFrame, width=5, from_=1, to=31)
monthSpin = tkinter.Spinbox(dateFrame, width=5, values=("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
yearSpin = tkinter.Spinbox(dateFrame, width=5, from_=2000, to=2099)
daySpin.grid(row=1, column=0)
monthSpin.grid(row=1, column=1)
yearSpin.grid(row=1, column=2)
# Buttons
okButton = tkinter.Button(mainWindow, text="OK")
cancelButton = tkinter.Button(mainWindow, text="Cancel", command=mainWindow.destroy)
okButton.grid(row=4, column=3, sticky='e')
cancelButton.grid(row=4, column=4, sticky='w')
mainWindow.mainloop()
print(rbValue.get())
|
mysky528/juttle
|
lib/runtime/procs/stoke/stoke.js
|
'use strict';
/**
stoke --
basic stochastic functions implemented in terms of an underlying fixed
random sample indexed by time. This allows us random access by time to
series derived from these, at arbitrary specified granularity, with
repeatable results.
There are two distinct styles of time-indexed randomness:
1) always return the same value for a given t (a Stoke object), and
2) successive draws at given t return a sequence of random values
which can be re-played by calling a reset function (a StokeSequence)
*/
var _ = require('underscore');
var util = require('./util');
var seedrandom = require('seedrandom');
var primes = require('./primes');
var FIFOCache = require('tiny-fifo-cache');
var errors = require('../../../errors');
var MarkovCache = new FIFOCache(50000);
class Stoke {
// Stoke: stoke.func(t) always returns the same value
// for a given t.
constructor(seed, dt) {
// seed: integer. Different seeds produce different random
// sequences.
// dt: float: time-granularity of simulated stochastic
// process. invocations separated in time by less than dt
// will return the same value.
this.seed = seed || 13;
this.dt = dt || 1;
this.stride = primes[this.seed % primes.length];
this.stride2 = primes[(this.seed + 1) % primes.length];
this.i = 0;
this.sequential = 0; // when > 0, successive calls at t yield a sequence
}
clone(sequential) {
var stoke = new Stoke(this.seed, this.dt);
stoke.sequential = (sequential === undefined)? this.sequential : sequential;
return stoke;
}
bump(sequential) {
// increment the seed and return a fresh copy.
var stoke = new Stoke(++this.seed, this.dt);
stoke.sequential = (sequential === undefined)? this.sequential : sequential;
return stoke;
}
reset() {
// reset the sequence counter, for successive calls with the same
// t when sequential > 0;
this.i = 0;
this.last_t = null;
return this;
}
step(t) {
// bump the sequence counter, for successive calls with the
// same t when sequential > 0; Note: This resets when t
// changes, because we do not track states for all t's in
// concurrent use, and because it is really what you wanted.
if (t === this.last_t) {
this.i += this.stride2;
} else {
this.i = 0 ;
this.last_t = t;
}
return this;
}
push_sequential() {
// temporarily begin sequential behavior. balance with a call to
// pop_sequential() to restore original behavior when done.
this.sequential ++;
}
pop_sequential() {
if (--this.sequential === 0) {
this.reset() ;
}
}
uniform(T) {
// return a uniform random number between 0..1. If !this.sequential, always
// return the same number for a given t, else return a repeatable sequence
// for successive calls at t.
// if called with no argument, behave as if sequential with t=0
var t = (T && T.seconds) ? T.seconds() : (T || 0);
if (this.sequential || T === undefined) {
this.step(t);
}
var n = Math.floor(Math.abs(t / this.dt - this.seed));
var idx = (n * this.stride + this.i) % _uniform_samples.length;
return _uniform_samples[idx];
}
boxmuller(t) {
// return a pair of Box-Muller approximate normals, indexed by t
this.push_sequential();
var u = 2 * this.uniform(t) - 1;
var v = 2 * this.uniform(t) - 1;
var r = u*u + v*v;
if (r === 0 || r > 1) {
// out of bounds, try again
var result = this.boxmuller(t);
this.pop_sequential();
return result;
}
var c = Math.sqrt(-2*Math.log(r)/r);
this.pop_sequential();
return [u*c, v*c];
}
normal(T) {
// return a N(0,1) random number. If !this.sequential, always
// return the same number for a given t, else return a
// repeatable sequence for successive calls at t.
// if called with no argument, behave as if sequential with t=0
var t = (T && T.seconds) ? T.seconds() : (T || 0);
if (this.sequential || T === undefined) {
this.step(t);
}
var n = Math.floor(Math.abs(t / this.dt - this.seed));
var idx = (n * this.stride + this.i) % _normal_samples.length;
return _normal_samples[idx];
}
integer(t, min, max) {
// choose an integer uniformly from min..max inclusive.
var x = this.uniform(t);
return Math.floor((max - min + 1) * x) + min;
}
ip(t) {
var ipnum = Math.floor(this.uniform(t)*Math.pow(2,32));
return ( [
Math.floor( ipnum / 16777216 ) % 256,
Math.floor( ipnum / 65536 ) % 256,
Math.floor( ipnum / 256 ) % 256,
Math.floor( ipnum ) % 256
]).join('.');
}
noisy(t, val, sigma, min, max) {
val += sigma * this.normal(t) ;
return util.bound(val, min, max);
}
digits(t, n, base) {
// generate a string of digits of length n in the given base.
// defaults are length 4 and base 10
n = n || 4;
base = base || 10;
var result = '';
this.push_sequential();
while (result.length < n) {
// uniform() is finite-precision, so iterate to get big numbers.
result += this.uniform(t).toString(base).substr(2);
}
this.pop_sequential();
return result.substr(-n);
}
mac(t) {
// generate a random MAC address
var addr = [];
this.push_sequential();
for (var i=0; i < 6 ; i++) {
addr.push(this.digits(t, 2, 16));
}
this.pop_sequential();
return addr.join(':');
}
random_occurrences(t, period, rate) {
// return a random integer count of events over the given period,
// indexed by t, such that average occurrences per unit time ==
// rate. note: this does not do aggregation over specific
// intervals. random_occurrences(t,2*p) will not necessarily equal
// random_occurrences(t,p) + random_occurrences(t+p,p), but their
// expecations are equal.
period = (period.seconds) ? period.seconds() : period;
var lambda = rate*period ;
if (lambda < 100) {
// use Knuth's Poisson generator
var exp = Math.exp(-lambda) ;
this.push_sequential();
for (var k=0, p=this.uniform(t) ; p > exp ; k++) {
p *= this.uniform(t);
}
this.pop_sequential();
return k;
} else {
// avoid underflow by taking the normal approximation to
// Poisson for large lambda
return Math.floor(this.normal(t) * Math.sqrt(lambda) + lambda) ;
}
}
choose(t, choices) {
// choose an item randomly from the choices such that the same
// choice holds for this.dt seconds around t.
var p = this.uniform(t);
return choices[Math.floor(p * choices.length)];
}
choose_weighted(t, choices) {
// Choose a key from choices, an object whose keys are the items
// we want to choose from and whose values are the weights of its
// keys (0..1, summing to 1.0). If you pass a list of weights
// instead of a weighted object, this returns the index of the
// choice (array indices are keys!)
var p = this.uniform(t);
var cum = 0;
var choice ;
for (choice in choices) {
cum += choices[choice];
if (p <= cum) {
return choice;
}
}
return choice; // roundoff
}
cached_markov(t, choices) {
// Keep a cache of recent markov values to avoid having to search
// for them each time. We make the sane assumption that nobody
// would use one stoke for multiple state machines, and thus do
// not bother encoding the choices object in the cache key.
var key = this.seed + '-' + this.dt + '-' + t;
var result = MarkovCache.get(key);
if (result === null) {
result = this.markov(t, choices);
MarkovCache.put(key, result);
}
return result;
}
markov(t, choices) {
// Simulate a limited class of discrete markov process in
// which transition probabilities do not depend on state. For
// this kind of process, instead of storing an evolving
// memoryless random state (which we cannot do in our
// framework), walk backwards from t to discover the most
// recent state transition event and report that value as the
// current state. The process timestep is this.dt
//
// Transition probabilities are in choices as state:p
// attributes, and there is no explicit entry for "no
// transition".
t = (t.seconds) ? t.seconds() : t ;
var choice;
this.push_sequential();
for (var i = 0 ; i < 10000 ; i++) {
var p = this.uniform(t);
for (choice in choices) {
if (p <= choices[choice]) {
this.pop_sequential();
return choice;
} else {
p -= choices[choice];
}
}
t -= this.dt ;
}
// fail-safe: return last choice if we're spinning our wheels
this.pop_sequential();
return choice;
}
markov_switcherf(items, avgdur, cached, location) {
// return a function(moment) that switches randomly among items
// over time such that on average a given choice holds for avgdur,
// with events resolved to granularity dt. dt should be some
// multiple of your current simulation granularity (computation time
// scales as avgdur/dt).
var self = this;
avgdur = (avgdur.seconds) ? avgdur.seconds() : avgdur;
var p = this.dt / (avgdur + this.dt - 1) ; // adjust: current state is in items
var p_choice = {};
var isNumber = _.every(items, _.isNumber);
var isString = _.every(items, _.isString);
if (!isNumber && !isString) {
throw new errors.compileError('INVALID-MARKOV-ITEMS', {
location: location
});
}
items.forEach(function(choice) { p_choice[choice] = p / items.length; }) ;
if (cached) {
return function(moment) {
var choice = self.cached_markov(moment, p_choice);
return isNumber ? 1 * choice : choice;
};
} else {
return function(moment) {
var choice = self.markov(moment, p_choice);
return isNumber ? 1 * choice : choice;
};
}
}
round_robin_switcherf(items, period) {
// return a function(moment) analogous to markov_switcherf,
// but that switches sequentially among items, switching once
// each period. Not random, but convenient.
period = (period && period.seconds) ? period.seconds() : (period || 1);
return function(moment) {
var idx = Math.floor(moment.unix()/period) % items.length ;
return items[idx];
};
}
}class StokeSequence extends Stoke {
// StokeSequence: stoke.func(t) called repeatedly with the same t
// returns a random sequence. This sequence is repeatable by
// calling reset() or whenever t is returned to after evaluations
// at other values of t.
constructor(seed, dt) {
super(seed, dt);
// seed: integer. Different seeds produce different random sequences.
// dt: float: time-granularity of simulated stochastic process.
// invocations separated in time by less than dt will return the same value.
this.sequential = 1;
this.last_t = null;
}
}
// pre-load global arrays with uniform random samples, and
// pre-generate normal random samples from these. Thereafter, random
// draws will be from these fixed arrays.
var N_SAMPLES = 10009;
var _uniform_samples = [];
var _rng = seedrandom(13);
var i;
for (i=0 ; i < N_SAMPLES ; i++) { _uniform_samples.push(_rng()); }
var _normal_samples = [];
var _box_stoke = new Stoke(13, 1);
for (i=0 ; i < (N_SAMPLES+1)/2 ; i++) {
var pair = _box_stoke.boxmuller(i);
_normal_samples.push(pair[0]);
_normal_samples.push(pair[1]);
}
// discard so length === N_SAMPLES
_normal_samples.pop() ;
module.exports = {
Stoke: Stoke,
StokeSequence: StokeSequence
};
|
jforge/vaadin
|
uitest/src/main/java/com/vaadin/tests/components/datefield/DateFieldDayResolutionOffset.java
|
package com.vaadin.tests.components.datefield;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.ui.datefield.DateTimeResolution;
import com.vaadin.tests.components.AbstractReindeerTestUI;
import com.vaadin.ui.DateTimeField;
import com.vaadin.ui.Label;
public class DateFieldDayResolutionOffset extends AbstractReindeerTestUI {
private final String initialDateString = "09/01/2014 00:00:00";
@Override
protected void setup(VaadinRequest request) {
final Label dateValue = new Label(initialDateString);
dateValue.setId("dateValue");
final DateTimeFormatter dateformat = getDateFormat();
final DateTimeField dateField = getDateField(dateformat);
addComponent(dateValue);
addComponent(dateField);
dateField.addValueChangeListener(event -> dateValue
.setValue(dateformat.format(dateField.getValue())));
}
private DateTimeField getDateField(DateTimeFormatter dateformat) {
final DateTimeField dateField = new DateTimeField();
LocalDateTime initialDate = dateformat.parse(initialDateString,
LocalDateTime::from);
dateField.setResolution(DateTimeResolution.DAY);
dateField.setValue(initialDate);
return dateField;
}
private DateTimeFormatter getDateFormat() {
final DateTimeFormatter dateformat = DateTimeFormatter
.ofPattern("MM/dd/yyyy HH:mm:ss");
return dateformat;
}
@Override
protected String getTestDescription() {
return "The time should stay at 00:00:00 when selecting dates with Resolution.DAY selected.";
}
@Override
protected Integer getTicketNumber() {
return 14653;
}
}
|
sailfly/nuxeo
|
addons/nuxeo-platform-suggestbox/nuxeo-platform-suggestbox-core/src/main/java/org/nuxeo/ecm/platform/suggestbox/utils/DateMatcher.java
|
<reponame>sailfly/nuxeo
/*
* (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* <NAME>
*/
package org.nuxeo.ecm.platform.suggestbox.utils;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.chrono.GregorianChronology;
public class DateMatcher {
private static final Pattern YEAR_ONLY_MATCHER = Pattern.compile("^\\d{4}$");
private static final Pattern MONTH_DIGIT_ONLY_MATCHER = Pattern.compile("^\\d{2}$");
private static final Pattern YEAR_MONTHS_MATCHER = Pattern.compile("^\\d{4}[_ -:]\\d{2}$");
private static final Pattern MONTHS_YEAR_MATCHER = Pattern.compile("^\\d{2}[_ -:]\\d{4}$");
private static final Pattern MONTHS_DAY_YEAR_MATCHER = Pattern.compile("^\\d{2}[_ -:]\\d{2,}[_ -:]\\d{4}$");
private static final Pattern YEAR_MONTHS_DAY_MATCHER = Pattern.compile("^\\d{4}[_ -:]\\d{2,}[_ -:]\\d{2}$");
private boolean withYears = false;
private boolean withMonth = false;
private boolean withDay = false;
private final Calendar dateSuggestion;
private DateMatcher(boolean withYears, boolean withMonth, boolean withDay, Calendar dateSuggestion) {
this.withYears = withYears;
this.withMonth = withMonth;
this.withDay = withDay;
this.dateSuggestion = dateSuggestion;
}
public boolean isWithYears() {
return withYears;
}
public void setWithYears(boolean withYears) {
this.withYears = withYears;
}
public boolean isWithMonth() {
return withMonth;
}
public void setWithMonth(boolean withMonth) {
this.withMonth = withMonth;
}
public boolean isWitDay() {
return withDay;
}
public void setWitDay(boolean witDay) {
withDay = witDay;
}
public Calendar getDateSuggestion() {
return dateSuggestion;
}
public boolean hasMatch() {
return getDateSuggestion() != null;
}
public static Matcher parsingDate(Pattern pattern, String input) {
return pattern.matcher(input.trim());
}
public static DateMatcher fromInput(String input) {
try {
return doFromInput(input);
} catch (NumberFormatException e) {
return new DateMatcher(false, false, false, null);
}
}
public static DateMatcher doFromInput(String input) {
Matcher matcher = parsingDate(YEAR_ONLY_MATCHER, input);
if (matcher.find()) {
return new DateMatcher(true, false, false, dateToInstance(Integer.parseInt(matcher.group()), 1, 1));
}
matcher = parsingDate(MONTH_DIGIT_ONLY_MATCHER, input);
if (matcher.find()) {
int month = Integer.parseInt(matcher.group());
if (month > 12 || month < 1) {
return new DateMatcher(false, true, false, null);
}
return new DateMatcher(false, true, false, dateToInstance(Calendar.getInstance().get(Calendar.YEAR), month,
1));
}
matcher = parsingDate(YEAR_MONTHS_MATCHER, input);
if (matcher.find()) {
int month = Integer.parseInt(matcher.group().substring(5));
if (month > 12 || month < 1) {
return new DateMatcher(true, true, false, null);
}
int year = Integer.parseInt(matcher.group().substring(0, 4));
return new DateMatcher(true, true, false, dateToInstance(year, month, 1));
}
matcher = parsingDate(MONTHS_YEAR_MATCHER, input);
if (matcher.find()) {
int month = Integer.parseInt(matcher.group().substring(0, 2));
if (month > 12 || month < 1) {
return new DateMatcher(true, true, false, null);
}
int year = Integer.parseInt(matcher.group().substring(3));
return new DateMatcher(true, true, false, dateToInstance(year, month, 1));
}
matcher = parsingDate(MONTHS_DAY_YEAR_MATCHER, input);
if (matcher.find()) {
int first = Integer.parseInt(matcher.group().substring(0, 2));
int second = Integer.parseInt(matcher.group().substring(3, 5));
int year = Integer.parseInt(matcher.group().substring(6));
int control = first + second;
if (control < 2 || control > 12 + 31 || first < 1 || second < 1) {
return new DateMatcher(true, true, true, null);
} else if (control < 12 + 12 + 1) {
return new DateMatcher(true, true, true, dateToInstance(year, first, second));
}
int month = first;
int day = second;
if (first > second) {
month = second;
day = first;
}
Calendar dateToInstance = dateToInstance(year, month, day);
return new DateMatcher(true, true, true, dateToInstance);
}
matcher = parsingDate(YEAR_MONTHS_DAY_MATCHER, input);
if (matcher.find()) {
int year = Integer.parseInt(matcher.group().substring(0, 4));
int first = Integer.parseInt(matcher.group().substring(5, 7));
int second = Integer.parseInt(matcher.group().substring(8));
int control = first + second;
if (control < 2 || control > 12 + 31 || first < 1 || second < 1) {
return new DateMatcher(true, true, true, null);
} else if (control < 12 + 12 + 1) {
return new DateMatcher(true, true, true, dateToInstance(year, first, second));
}
int month = first;
int day = second;
if (first > second) {
month = second;
day = first;
}
Calendar dateToInstance = dateToInstance(year, month, day);
return new DateMatcher(true, true, true, dateToInstance);
}
return new DateMatcher(false, false, false, null);
}
protected static Calendar dateToInstance(int year, int month, int day) {
try {
Chronology chrono = GregorianChronology.getInstance();
DateTime dt = new DateTime(year, month, day, 12, 0, 0, 0, chrono);
return dt.toGregorianCalendar();
} catch (IllegalArgumentException e) {
return null;
}
}
}
|
Debasishray19/SoundStream
|
src/jass/generators/Sine.java
|
package jass.generators;
import jass.engine.*;
/**
Output sine wave. (Highly inefficient implementation.)
@author <NAME> (<EMAIL>)
*/
public class Sine extends Out {
/** Sampling rate in Hertz of Out. */
public float srate;
/** Amplitude or volume of sine */
protected float volume = 1;
/** Current phase */
protected float phase = 0;
/** Freq. in Hertz */
protected float freq = 440;
private float oldFreq = freq;
public static final float TWOPI = (float)(2*Math.PI);
public Sine(float srate,int bufferSize) {
super(bufferSize);
this.srate = srate;
}
/** Set amplitude
@param val Volume.
*/
public void setVolume(float val) {
volume = val;
}
/** Set frequency
@param f frequency.
*/
public void setFrequency(float f) {
freq = f;
}
protected void computeBuffer() {
int bufsz = getBufferSize();
float fact = (freq-oldFreq)/(bufsz-1);
float f;
for(int i=0;i<bufsz;i++) {
f = oldFreq + fact*i;
phase += (float)(TWOPI*f/srate);
buf[i] = (float) (volume * Math.sin((double)phase));
}
while(phase > TWOPI) {
phase -= TWOPI;
}
oldFreq = freq;
}
}
|
Kaixiang/bosh
|
bosh-director/bosh-director.gemspec
|
<reponame>Kaixiang/bosh
# coding: utf-8
require File.expand_path('../lib/bosh/director/version', __FILE__)
version = Bosh::Director::VERSION
Gem::Specification.new do |spec|
spec.name = 'bosh-director'
spec.version = version
spec.platform = Gem::Platform::RUBY
spec.summary = 'BOSH Director'
spec.description = "BOSH Director"
spec.author = 'VMware'
spec.homepage = 'https://github.com/cloudfoundry/bosh'
spec.license = 'Apache 2.0'
spec.email = '<EMAIL>'
spec.required_ruby_version = Gem::Requirement.new('>= 1.9.3')
spec.files = Dir['db/**/*', 'lib/**/*'].select{ |f| File.file? f }
spec.require_path = 'lib'
spec.bindir = 'bin'
spec.executables << 'bosh-director'
spec.executables << 'bosh-director-console'
spec.executables << 'bosh-director-drain-workers'
spec.executables << 'bosh-director-migrate'
spec.executables << 'bosh-director-scheduler'
spec.executables << 'bosh-director-worker'
# NOTE: We must specify all transitive BOSH gem dependencies found in the
# external CPIs, in order to ensure appropriate versions are installed.
# Also do the same in bosh_cli_plugin_micro.gemspec
# Review this once CPIs are completely externalized and "micro" goes away.
# ----------------------------------------------------------------------------
spec.add_dependency 'bosh_common', "~>#{version}"
spec.add_dependency 'bosh_cpi', "~>#{version}"
spec.add_dependency 'bosh-registry', "~>#{version}"
# ----------------------------------------------------------------------------
spec.add_dependency 'blobstore_client', "~>#{version}"
spec.add_dependency 'bosh-core', "~>#{version}"
spec.add_dependency 'bosh-director-core', "~>#{version}"
spec.add_dependency 'bosh-template', "~>#{version}"
spec.add_dependency 'bosh_openstack_cpi', "=2.1.0"
spec.add_dependency 'bosh_aws_cpi', "=2.1.0"
spec.add_dependency 'bosh_vsphere_cpi', "=2.1.0"
spec.add_dependency 'bosh_vcloud_cpi', '=0.11.0'
spec.add_dependency 'bcrypt-ruby', '~>3.0.1'
spec.add_dependency 'eventmachine', '~>1.0.0'
spec.add_dependency 'fog', '~>1.34.0'
spec.add_dependency 'fog-aws', '~>0.7.6'
spec.add_dependency 'httpclient', '=2.4.0'
spec.add_dependency 'logging', '~>1.8.2'
spec.add_dependency 'nats', '=0.5.0.beta.12'
spec.add_dependency 'netaddr', '~>1.5.0'
spec.add_dependency 'rack-test', '~>0.6.2' # needed for console
spec.add_dependency 'rake', '~> 10.0'
spec.add_dependency 'redis', '~>3.0.2'
spec.add_dependency 'resque', '~>1.25.0'
spec.add_dependency 'resque-backtrace', '~>0.0.1'
spec.add_dependency 'rufus-scheduler', '~>2.0.18'
spec.add_dependency 'sequel', '~>3.43.0'
spec.add_dependency 'sinatra', '~>1.4.2'
spec.add_dependency 'sys-filesystem', '~>1.1.0'
spec.add_dependency 'thin', '~>1.5.0'
spec.add_dependency 'yajl-ruby', '~>1.2.0'
spec.add_dependency 'membrane', '~>1.1.0'
spec.add_dependency 'semi_semantic', '~>1.1.0'
spec.add_dependency 'cf-uaa-lib', '~>3.2.1'
spec.add_development_dependency 'timecop'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'rspec-its'
spec.add_development_dependency 'minitar'
spec.add_development_dependency 'machinist'
spec.add_development_dependency 'sqlite3'
spec.add_development_dependency 'fakefs'
spec.add_development_dependency 'pg'
end
|
idavis/Innovatian.Idea.PowerShell
|
test/lang/lexer/keywords/PsLexerTestsKeywordReturn.java
|
package com.innovatian.idea.powershell.test.lang.lexer.keywords;
import com.innovatian.idea.powershell.lang.lexer.PsTokenTypes;
import com.innovatian.idea.powershell.test.lang.lexer.PsLexerTestContext;
import junit.framework.Assert;
public class PsLexerTestsKeywordReturn extends PsLexerTestContext {
public void testKeyword_RETURN() {
String toParse = "RETURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETURn() {
String toParse = "RETURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETUrN() {
String toParse = "RETUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETUrn() {
String toParse = "RETUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETuRN() {
String toParse = "RETuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETuRn() {
String toParse = "RETuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETurN() {
String toParse = "RETurN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETurN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RETurn() {
String toParse = "RETurn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RETurn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtURN() {
String toParse = "REtURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtURn() {
String toParse = "REtURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtUrN() {
String toParse = "REtUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtUrn() {
String toParse = "REtUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtuRN() {
String toParse = "REtuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REtuRn() {
String toParse = "REtuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REtuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REturN() {
String toParse = "REturN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REturN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_REturn() {
String toParse = "REturn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("REturn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTURN() {
String toParse = "ReTURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTURn() {
String toParse = "ReTURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTUrN() {
String toParse = "ReTUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTUrn() {
String toParse = "ReTUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTuRN() {
String toParse = "ReTuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTuRn() {
String toParse = "ReTuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTurN() {
String toParse = "ReTurN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTurN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReTurn() {
String toParse = "ReTurn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReTurn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetURN() {
String toParse = "RetURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetURn() {
String toParse = "RetURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetUrN() {
String toParse = "RetUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetUrn() {
String toParse = "RetUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetuRN() {
String toParse = "RetuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_RetuRn() {
String toParse = "RetuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("RetuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_ReturN() {
String toParse = "ReturN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("ReturN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_Return() {
String toParse = "Return";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("Return", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETURN() {
String toParse = "rETURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETURn() {
String toParse = "rETURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETUrN() {
String toParse = "rETUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETUrn() {
String toParse = "rETUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETuRN() {
String toParse = "rETuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETuRn() {
String toParse = "rETuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETurN() {
String toParse = "rETurN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETurN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rETurn() {
String toParse = "rETurn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rETurn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtURN() {
String toParse = "rEtURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtURn() {
String toParse = "rEtURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtUrN() {
String toParse = "rEtUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtUrn() {
String toParse = "rEtUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtuRN() {
String toParse = "rEtuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEtuRn() {
String toParse = "rEtuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEtuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEturN() {
String toParse = "rEturN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEturN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_rEturn() {
String toParse = "rEturn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("rEturn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTURN() {
String toParse = "reTURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTURn() {
String toParse = "reTURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTUrN() {
String toParse = "reTUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTUrn() {
String toParse = "reTUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTuRN() {
String toParse = "reTuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTuRn() {
String toParse = "reTuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTurN() {
String toParse = "reTurN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTurN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_reTurn() {
String toParse = "reTurn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("reTurn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retURN() {
String toParse = "retURN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retURN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retURn() {
String toParse = "retURn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retURn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retUrN() {
String toParse = "retUrN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retUrN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retUrn() {
String toParse = "retUrn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retUrn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retuRN() {
String toParse = "retuRN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retuRN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_retuRn() {
String toParse = "retuRn";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("retuRn", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_returN() {
String toParse = "returN";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("returN", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
public void testKeyword_return() {
String toParse = "return";
lexer.start(toParse);
Assert.assertEquals(PsTokenTypes.RETURN, lexer.getTokenType());
Assert.assertEquals("return", lexer.getTokenText());
lexer.advance();
Assert.assertNull(lexer.getTokenType());
}
}
|
zhangyage/Python-oldboy
|
day04/oop/class_study10.py
|
<reponame>zhangyage/Python-oldboy<gh_stars>1-10
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from _pyio import __metaclass__
'''
接口定义和规范设计
抽象类加抽象方法就叫接口
'''
from abc import ABCMeta, abstractmethod #下面的定义接口是的固定设计
class Alert:
__metaclass__ = ABCMeta
@abstractmethod #指定接口的方法,在继承接口是必须定义这个方法,要不报错
def Send(self):
pass
class Weixin(Alert): #继承接口类
def __init__(self):
print '__init__'
def Send(self): #必须定义接口中定义的方法名称,保证程序不报错和开发的规范
print 'send.weixin'
f=Weixin()
f.Send()
|
bobmcwhirter/drools
|
drools-core/src/main/java/org/drools/SessionConfiguration.java
|
<filename>drools-core/src/main/java/org/drools/SessionConfiguration.java
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Properties;
import org.drools.util.ChainedProperties;
/**
* SessionConfiguration
*
* A class to store Session related configuration. It must be used at session instantiation time
* or not used at all.
* This class will automatically load default values from system properties, so if you want to set
* a default configuration value for all your new sessions, you can simply set the property as
* a System property.
*
* After the Session is created, it makes the configuration immutable and there is no way to make it
* mutable again. This is to avoid inconsistent behavior inside session.
*
* NOTE: This API is under review and may change in the future.
*
*
* drools.keepReference = <true|false>
* drools.clockType = <pseudo|realtime|heartbeat|implicit>
*/
public class SessionConfiguration
implements
Externalizable {
private static final long serialVersionUID = 500L;
private ChainedProperties chainedProperties;
private volatile boolean immutable;
private boolean keepReference;
private ClockType clockType;
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( chainedProperties );
out.writeBoolean( immutable );
out.writeBoolean( keepReference );
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
chainedProperties = (ChainedProperties) in.readObject();
immutable = in.readBoolean();
keepReference = in.readBoolean();
}
/**
* Creates a new session configuration using the provided properties
* as configuration options.
*
* @param properties
*/
public SessionConfiguration(Properties properties) {
init( properties );
}
/**
* Creates a new session configuration with default configuration options.
*/
public SessionConfiguration() {
init( null );
}
private void init(Properties properties) {
this.immutable = false;
this.chainedProperties = new ChainedProperties( "rulebase.conf" );
if ( properties != null ) {
this.chainedProperties.addProperties( properties );
}
setKeepReference( Boolean.valueOf( this.chainedProperties.getProperty( "drools.keepReference",
"true" ) ).booleanValue() );
setClockType( ClockType.resolveClockType( this.chainedProperties.getProperty( "drools.clockType",
"realtime" ) ) );
}
/**
* Makes the configuration object immutable. Once it becomes immutable,
* there is no way to make it mutable again.
* This is done to keep consistency.
*/
public void makeImmutable() {
this.immutable = true;
}
/**
* Returns true if this configuration object is immutable or false otherwise.
* @return
*/
public boolean isImmutable() {
return this.immutable;
}
private void checkCanChange() {
if ( this.immutable ) {
throw new UnsupportedOperationException( "Can't set a property after configuration becomes immutable" );
}
}
public void setKeepReference(boolean keepReference) {
checkCanChange(); // throws an exception if a change isn't possible;
this.keepReference = keepReference;
}
public boolean isKeepReference() {
return this.keepReference;
}
public ClockType getClockType() {
return clockType;
}
public void setClockType(ClockType clockType) {
checkCanChange(); // throws an exception if a change isn't possible;
this.clockType = clockType;
}
}
|
SLukasDE/esl
|
src/main/esl/io/output/Function.h
|
/*
MIT License
Copyright (c) 2019-2021 <NAME>
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.
*/
#ifndef ESL_IO_OUTPUT_FUNCTION_H_
#define ESL_IO_OUTPUT_FUNCTION_H_
#include <esl/io/Output.h>
#include <esl/io/Reader.h>
#include <string>
#include <functional>
namespace esl {
namespace io {
namespace output {
class Function : public Reader {
public:
static esl::io::Output create(std::function<std::size_t(void*, std::size_t)> getDataFunction);
Function(std::function<std::size_t(void*, std::size_t)> getDataFunction);
std::size_t read(void* data, std::size_t size) override;
std::size_t getSizeReadable() const override;
bool hasSize() const override;
std::size_t getSize() const override;
private:
static constexpr std::size_t prefetchSize = 1024;
std::size_t prefetchData() const;
mutable std::function<std::size_t(void*, std::size_t)> getDataFunction;
mutable std::size_t fetchedDirectSize = 0;
mutable std::string data;
std::size_t dataPos = 0;
};
} /* namespace output */
} /* namespace io */
} /* namespace esl */
#endif /* ESL_IO_OUTPUT_FUNCTION_H_ */
|
MassICTBV/casinocoind
|
src/beast/extras/beast/test/yield_to.hpp
|
<gh_stars>1-10
//
// Copyright (c) 2013-2017 <NAME> (<EMAIL> at <EMAIL> dot <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BEAST_TEST_YIELD_TO_HPP
#define BEAST_TEST_YIELD_TO_HPP
#include <boost/asio/io_service.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/optional.hpp>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
namespace beast {
namespace test {
/** Mix-in to support tests using asio coroutines.
Derive from this class and use yield_to to launch test
functions inside coroutines. This is handy for testing
asynchronous asio code.
*/
class enable_yield_to
{
protected:
boost::asio::io_service ios_;
private:
boost::optional<boost::asio::io_service::work> work_;
std::thread thread_;
std::mutex m_;
std::condition_variable cv_;
bool running_ = false;
public:
/// The type of yield context passed to functions.
using yield_context =
boost::asio::yield_context;
enable_yield_to()
: work_(ios_)
, thread_([&]
{
ios_.run();
}
)
{
}
~enable_yield_to()
{
work_ = boost::none;
thread_.join();
}
/// Return the `io_service` associated with the object
boost::asio::io_service&
get_io_service()
{
return ios_;
}
/** Run a function in a coroutine.
This call will block until the coroutine terminates.
Function will be called with this signature:
@code
void f(args..., yield_context);
@endcode
@param f The Callable object to invoke.
@param args Optional arguments forwarded to the callable object.
*/
#if GENERATING_DOCS
template<class F, class... Args>
void
yield_to(F&& f, Args&&... args);
#else
template<class F>
void
yield_to(F&& f);
template<class Function, class Arg, class... Args>
void
yield_to(Function&& f, Arg&& arg, Args&&... args)
{
yield_to(std::bind(f,
std::forward<Arg>(arg),
std::forward<Args>(args)...,
std::placeholders::_1));
}
#endif
};
template<class Function>
void
enable_yield_to::yield_to(Function&& f)
{
{
std::lock_guard<std::mutex> lock(m_);
running_ = true;
}
boost::asio::spawn(ios_,
[&](boost::asio::yield_context do_yield)
{
f(do_yield);
std::lock_guard<std::mutex> lock(m_);
running_ = false;
cv_.notify_all();
}
, boost::coroutines::attributes(2 * 1024 * 1024));
std::unique_lock<std::mutex> lock(m_);
cv_.wait(lock, [&]{ return ! running_; });
}
} // test
} // beast
#endif
|
dup2X/gomicrosvr
|
pkg/config/errors.go
|
<filename>pkg/config/errors.go
// Package config ...
package config
import (
"fmt"
)
func wrapMissKeyErr(key string) error {
return fmt.Errorf("cannot find key: %s", key)
}
|
zhairuihao/blog-1
|
src/main/java/io/github/ramerf/blog/system/controller/common/manage/DataDictController.java
|
package io.github.ramerf.blog.system.controller.common.manage;
import io.github.ramerf.wind.core.entity.response.Rs;
import io.swagger.annotations.*;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import io.github.ramerf.blog.system.entity.Constant.AccessPath;
import io.github.ramerf.blog.system.entity.domain.common.DataDict;
import io.github.ramerf.blog.system.entity.pojo.common.DataDictPoJo;
import io.github.ramerf.blog.system.entity.request.common.DataDictRequest;
import io.github.ramerf.blog.system.entity.response.common.DataDictResponse;
import io.github.ramerf.blog.system.service.common.*;
import io.github.ramerf.blog.system.util.TextUtil;
import io.github.ramerf.blog.system.validator.common.DataDictValidator;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
@Slf4j
@Controller
@RequestMapping(AccessPath.MANAGE + "/dataDict")
@PreAuthorize("hasAnyAuthority('global:read','manage:read','dataDict:read')")
@Api(tags = "管理端: 数据字典接口")
@SuppressWarnings("UnusedDeclaration")
public class DataDictController {
@Resource private DataDictTypeService typeService;
@Resource private DataDictService service;
@Resource private CommonService commonService;
@Resource private DataDictValidator validator;
@InitBinder(value = {"dataDict"})
void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
@GetMapping("/index")
@ApiOperation("数据字典页面")
public String index(@ApiIgnore HttpSession session, @ApiIgnore Map<String, Object> map) {
commonService.writeMenuAndSiteInfo(session, map);
map.put("types", typeService.list(null));
return "manage/data_dict/index";
}
@GetMapping("/page")
@ResponseBody
@ApiOperation("根据数据字典类型获取数据字典列表")
public ResponseEntity<Rs<PageImpl<DataDictResponse>>> list(
@RequestParam(value = "typeId", required = false) String typeIdStr,
@RequestParam(value = "page", required = false) String pageStr,
@RequestParam(value = "size", required = false) String sizeStr,
@ApiParam("查询条件") @RequestParam(value = "criteria", required = false) String criteria) {
final long typeId = TextUtil.validLong(typeIdStr, -1);
final int[] pageAndSize = TextUtil.validFixPageAndSize(pageStr, sizeStr);
return commonService.page(
service.page(typeId, criteria, pageAndSize[0], pageAndSize[1]), DataDictResponse::of);
}
@GetMapping
@ApiOperation("添加数据字典页面")
public String create(@ApiIgnore HttpSession session, @ApiIgnore Map<String, Object> map) {
commonService.writeMenuAndSiteInfo(session, map);
map.put("types", typeService.list(null));
return "manage/data_dict/edit";
}
@PostMapping
@ResponseBody
@PreAuthorize("hasAnyAuthority('global:create','dataDict:create')")
@ApiOperation("添加数据字典")
public ResponseEntity<Rs<Object>> create(
@Valid DataDictRequest dataDictRequest, @ApiIgnore BindingResult bindingResult) {
log.info(" DataDictController.create : [{}]", dataDictRequest);
return commonService.create(service, DataDict.class, dataDictRequest, bindingResult);
}
@GetMapping("/{id}")
@ApiOperation("更新数据字典页面")
public String update(
@PathVariable(value = "id") String idStr,
@RequestParam(value = "typeId", required = false) String typeIdStr,
@ApiIgnore HttpSession session,
@ApiIgnore Map<String, Object> map) {
return commonService.update(
service,
DataDictPoJo.class,
idStr,
"manage/data_dict/edit",
map,
"dataDict",
id -> {
commonService.writeMenuAndSiteInfo(session, map);
map.put("types", typeService.list(null));
map.put("dataDict", service.getById(id));
},
false);
}
@PutMapping("/{id}")
@ResponseBody
@PreAuthorize("hasAnyAuthority('global:write','dataDict:write')")
@ApiOperation("更新数据字典")
public ResponseEntity<Rs<Object>> update(
@PathVariable(value = "id") String idStr,
@Valid DataDictRequest dataDictRequest,
@ApiIgnore BindingResult bindingResult) {
log.info(" DataDictController.update : [{}]", dataDictRequest);
return commonService.update(service, DataDict.class, dataDictRequest, idStr, bindingResult);
}
@DeleteMapping("/{id}")
@ResponseBody
@PreAuthorize("hasAnyAuthority('global:delete','dataDict:delete')")
@ApiOperation("删除数据字典")
public ResponseEntity<Rs<Object>> delete(@PathVariable("id") String idStr) {
log.info(" DataDictController.delete : [{}]", idStr);
return commonService.delete(service, idStr);
}
@DeleteMapping("/deleteBatch")
@ResponseBody
@PreAuthorize("hasAnyAuthority('global:delete','dataDict:delete')")
@ApiOperation("删除数据字典批量")
public ResponseEntity<Rs<Object>> deleteBatch(@RequestParam("ids") List<Long> ids) {
log.info(" DataDictController.deleteBatch : [{}]", ids);
return commonService.deleteBatch(service, ids);
}
}
|
jai-singhal/djangopy
|
vendor/bundle/ruby/2.3.0/gems/rmagick-2.16.0/doc/ex/threshold.rb
|
<reponame>jai-singhal/djangopy<filename>vendor/bundle/ruby/2.3.0/gems/rmagick-2.16.0/doc/ex/threshold.rb
#!/usr/bin/env ruby -w
require 'rmagick'
# Demonstrate the Image#threshold method
img = Magick::Image.read('images/Flower_Hat.jpg').first
# Use a threshold of 55% of QuantumRange.
img = img.threshold(Magick::QuantumRange*0.55)
#img.display
img.write('threshold.jpg')
exit
|
data-hunters/metadata-digger
|
src/main/scala/ai/datahunters/md/reader/SolrHashReader.scala
|
package ai.datahunters.md.reader
import java.util
import ai.datahunters.md.config.writer.SolrWriterConfig
import ai.datahunters.md.processor.ColumnNamesConverterFactory
import ai.datahunters.md.util.SolrClientBuilder
import org.apache.solr.client.solrj.impl.CloudSolrClient
import org.apache.solr.common.params.MapSolrParams
import org.apache.solr.common.{SolrDocument, SolrDocumentList}
import org.apache.spark.sql.types.{DataTypes, StructField, StructType}
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import scala.collection.JavaConversions._
/**
* Read id and hashes to DataFrame mainly for processing reduction.
*
* ##Important! Feature is experimental due to loading all IDs from Solr collection into driver.
* Out of memory can appear in case of large collections.
*
* @param sparkSession
* @param config
*/
case class SolrHashReader(sparkSession: SparkSession,
config: SolrWriterConfig,
namingConvention: String) extends PipelineSource {
import ai.datahunters.md.processor.HashExtractor._
import ai.datahunters.md.reader.SolrHashReader._
import ai.datahunters.md.util.HashUtils._
val nameConverter = ColumnNamesConverterFactory.create(namingConvention)
private val normalizedHashSeq: Seq[String] = HashSeq
.map(s => HashColPrefix + HashNameNorm(s))
.map(s => nameConverter.namingConvention(s))
private val StructFieldsArray = StructType(
normalizedHashSeq
.map(s => StructField(s, DataTypes.StringType, nullable = true))
.toArray
)
private val documentToStrings: SolrDocument => Seq[String] =
(document: SolrDocument) => normalizedHashSeq.map(s => getDocumentFieldValueOrEmptyString(document, s))
override def load(): DataFrame = {
val clientBuilder = SolrClientBuilder().setZKServers(config.zkServers)
.setZKSolrChroot(config.zkSolrZNode)
.setDefaultCollection(config.collection)
val clientBuilderWithSec = config.krbConfig
.map(clientBuilder.setJaas)
.getOrElse(clientBuilder)
val client = clientBuilderWithSec.build()
val documents = getSolrDocumentList(client, QueryStartRow)
val idHashValueSeq = documents.map((d: SolrDocument) =>
Row.fromSeq(documentToStrings(d)))
val dataRdd = sparkSession.sparkContext.parallelize(idHashValueSeq)
client.close()
sparkSession.createDataFrame(dataRdd, StructFieldsArray)
}
private def getDocumentFieldValueOrEmptyString(document: SolrDocument, fieldName: String) = {
val fieldValue = Option(document.getFirstValue(fieldName).asInstanceOf[String])
fieldValue.orNull
}
def getSolrDocumentList(client: CloudSolrClient, queryStartRow: Int): SolrDocumentList = {
val queryParams = new MapSolrParams(builtQueryParamMap(queryStartRow))
val response = client.query(queryParams)
val documentList = response.getResults
if (documentList.nonEmpty) {
documentList.addAll(getSolrDocumentList(client, queryStartRow + RowsValue))
}
documentList
}
def builtQueryParamMap(queryStartRow: Int) = {
val queryParamMap = new util.HashMap[String, String]()
queryParamMap.put(QueryKey, QueryAllValue)
queryParamMap.put(FieldKey, normalizedHashSeq.mkString(Comma))
queryParamMap.put(StartKey, queryStartRow.toString)
queryParamMap.put(RowsKey, RowsValue.toString)
queryParamMap
}
}
object SolrHashReader {
import ai.datahunters.md.util.HashUtils._
val QueryAllValue = "*:*"
val Comma = ","
val QueryKey = "q"
val FieldKey = "fl"
val RowsKey = "rows"
val RowsValue = 10
val StartKey = "start"
val QueryStartRow = 0
val HashSeq: Seq[String] = Seq(Crc32, Md5, Sha1, Sha224, Sha256, Sha384, Sha512)
}
|
woshihuo12/Entitas-CSharp
|
docs/search/all_d.js
|
<gh_stars>1000+
var searchData=
[
['safeaerc',['SafeAERC',['../class_entitas_1_1_safe_a_e_r_c.html',1,'Entitas']]],
['singleentity',['SingleEntity',['../class_entitas_1_1_collection_extension.html#a57b0cefb881fa38432706a4fc91a609e',1,'Entitas::CollectionExtension']]],
['singleentity_3c_20tentity_20_3e',['SingleEntity< TEntity >',['../class_entitas_1_1_collection_extension.html#a8a1d04bbc143d69a962b99d99bde3b01',1,'Entitas::CollectionExtension']]],
['singleentityexception',['SingleEntityException',['../class_entitas_1_1_single_entity_exception.html',1,'Entitas']]],
['systems',['Systems',['../class_entitas_1_1_systems.html',1,'Entitas.Systems'],['../class_entitas_1_1_systems.html#acb0154f3edb36939f2e81945c4fb0de5',1,'Entitas.Systems.Systems()']]]
];
|
skylarkfw/skylark-angular2
|
original/angular.js-1.7.5/benchmarks/orderby-bp/app.js
|
'use strict';
var app = angular.module('orderByBenchmark', []);
app.controller('DataController', function DataController($rootScope, $scope) {
this.ngRepeatCount = 5000;
this.rows = [];
var self = this;
$scope.benchmarkType = 'baseline';
$scope.rawProperty = function(key) {
return function(item) {
return item[key];
};
};
// Returns a random integer between min (included) and max (excluded)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
benchmarkSteps.push({
name: 'setup',
description: 'Set rows to empty array and apply, then push new rows to be applied in next step',
fn: function() {
var oldRows = self.rows;
$rootScope.$apply(function() {
self.rows = [];
});
self.rows = oldRows;
if (self.rows.length !== self.ngRepeatCount) {
self.rows = [];
for (var i = 0; i < self.ngRepeatCount; i++) {
self.rows.push({
'name': getRandomInt(i, (i + 40)),
'index': i
});
}
}
}
});
benchmarkSteps.push({
name: '$apply',
fn: function() {
$rootScope.$apply();
}
});
});
|
myLxlGit/course-system
|
src/main/java/com/rainng/coursesystem/controller/HomeController.java
|
<filename>src/main/java/com/rainng/coursesystem/controller/HomeController.java
package com.rainng.coursesystem.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController extends BaseController {
@RequestMapping("/")
public String hello() {
return "Hello Rainng Course Management System";
}
@RequestMapping("/test")
public Object test() {
return "Hello";
}
}
|
rbwinslow/hq
|
test/hquery/test_strings.py
|
from test.common_test_util import expected_result
from test.hquery.hquery_test_util import query_html_doc
def test_escapes_work_in_string_literals():
assert query_html_doc('', '"foo bar"') == expected_result("""
foo
bar""")
assert query_html_doc('', "'foo bar'") == expected_result("""
foo
bar""")
assert query_html_doc('', '`foo bar`') == expected_result("""
foo
bar""")
|
shiveshr/pravega-1
|
segmentstore/server/host/src/test/java/io/pravega/segmentstore/server/host/handler/ConnectionTrackerTests.java
|
/**
* Copyright Pravega 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 io.pravega.segmentstore.server.host.handler;
import io.pravega.shared.protocol.netty.RequestProcessor;
import io.pravega.shared.protocol.netty.WireCommand;
import io.pravega.test.common.AssertExtensions;
import lombok.Getter;
import lombok.val;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for the {@link ConnectionTracker} class.
*/
public class ConnectionTrackerTests {
@Test
public void testConstructor() {
AssertExtensions.assertThrows(
"Constructor accepted SingleConnectionMaxLimit under LOW_WATERMARK threshold.",
() -> new ConnectionTracker(ConnectionTracker.LOW_WATERMARK + 1, ConnectionTracker.LOW_WATERMARK - 1),
ex -> ex instanceof IllegalArgumentException);
AssertExtensions.assertThrows(
"Constructor accepted AllConnectionsMaxLimit under LOW_WATERMARK threshold.",
() -> new ConnectionTracker(ConnectionTracker.LOW_WATERMARK - 1, ConnectionTracker.LOW_WATERMARK - 2),
ex -> ex instanceof IllegalArgumentException);
AssertExtensions.assertThrows(
"Constructor accepted SingleConnectionMaxLimit > AllConnectionsMaxLimit.",
() -> new ConnectionTracker(ConnectionTracker.LOW_WATERMARK + 2, ConnectionTracker.LOW_WATERMARK + 3),
ex -> ex instanceof IllegalArgumentException);
}
/**
* Verifies that {@link ConnectionTracker#getTotalOutstanding()} is calculated properly.
*/
@Test
public void testTotalOutStanding() {
val c = new MockConnection();
val t = new ConnectionTracker();
t.updateOutstandingBytes(c, 10, 10);
Assert.assertEquals("Unexpected value from getTotalOutstanding.", 10, t.getTotalOutstanding());
t.updateOutstandingBytes(c, 1, 2);
Assert.assertEquals("Unexpected value from getTotalOutstanding.", 11, t.getTotalOutstanding());
t.updateOutstandingBytes(c, -100, 0);
Assert.assertEquals("Unexpected value from getTotalOutstanding(low-bound).", 0, t.getTotalOutstanding());
}
/**
* Verifies various scenarios for {@link ConnectionTracker#updateOutstandingBytes}.
*/
@Test
public void testAdjustOutstandingBytes() {
val allLimit = ConnectionTracker.LOW_WATERMARK * 4;
val singleLimit = ConnectionTracker.LOW_WATERMARK * 2;
val t = new ConnectionTracker(allLimit, singleLimit);
val c = new MockConnection();
// A connection increased, but it's under both the per-connection limit and total limit.
t.updateOutstandingBytes(c, singleLimit - 2, singleLimit - 2);
Assert.assertFalse("Not expecting a connection pause when under the limit.", c.isPaused());
// Single connection cannot exceed its limit.
t.updateOutstandingBytes(c, singleLimit - 1, singleLimit + 1);
Assert.assertTrue("Expected a connection pause when connection over limit.", c.isPaused());
// Increase a connection by 2. This still keeps the total under allLimit, but the per-connection quota would
// have been exceeded. The only condition allowing this to stay alive is that it's below the LOW_WATERMARK.
t.updateOutstandingBytes(c, 2, 2);
Assert.assertFalse("Not expected a connection pause when connection under LOW_WATERMARK.", c.isPaused());
// Increase a connection by 2. This should put the total limit above the absolute threshold, so it should be rejected.
t.updateOutstandingBytes(c, 2, 2);
Assert.assertTrue("Expected a connection pause when total is above limit.", c.isPaused());
// Decrease a connection by a good amount. This should still be off because the cumulative total is too high.
t.updateOutstandingBytes(c, -ConnectionTracker.LOW_WATERMARK, ConnectionTracker.LOW_WATERMARK + 1);
Assert.assertTrue("Expected a connection pause connection is over limit.", c.isPaused());
// Repeat the last step. This should be OK now, because we've reduced the total to a low-enough value
t.updateOutstandingBytes(c, -ConnectionTracker.LOW_WATERMARK, ConnectionTracker.LOW_WATERMARK + 1);
Assert.assertFalse("Not expected a connection pause when total is reduced below limit.", c.isPaused());
}
/**
* Verifies {@link TrackedConnection}.
*/
@Test
public void testTrackedConnection() {
val allLimit = ConnectionTracker.LOW_WATERMARK * 4;
val singleLimit = ConnectionTracker.LOW_WATERMARK * 2;
val baseTracker = new ConnectionTracker(allLimit, singleLimit);
val c1 = new MockConnection();
val t1 = new TrackedConnection(c1, baseTracker);
val c2 = new MockConnection();
val t2 = new TrackedConnection(c2, baseTracker);
// A connection increased, but it's under both the per-connection limit and total limit.
t1.adjustOutstandingBytes(singleLimit - 2);
Assert.assertFalse("Not expecting a connection pause when under the limit.", c1.isPaused());
// Single connection cannot exceed its limit.
t1.adjustOutstandingBytes(3);
Assert.assertTrue("Expected a connection pause when connection over limit.", c1.isPaused());
// Increase second connection by the max it can be increased. This should pause the connection.
t2.adjustOutstandingBytes(singleLimit / 2 - 1);
Assert.assertFalse("Not expected a connection pause when total is below limit.", c2.isPaused());
t2.adjustOutstandingBytes(1);
Assert.assertTrue("Expected a connection pause when total is above limit.", c2.isPaused());
Assert.assertEquals(singleLimit + 1 + singleLimit / 2, baseTracker.getTotalOutstanding());
// Decrease the last increase for connection 1. Since the are multiple connections, the overall per-connection
// max threshold decreased, so we cannot yet resume it.
t1.adjustOutstandingBytes(-3);
Assert.assertTrue("Expected a connection pause when connection was over limit (near total capacity).", c1.isPaused());
t1.adjustOutstandingBytes(-singleLimit / 2);
Assert.assertFalse("Expected a connection resume when connection dropped below limit .", c1.isPaused());
t2.adjustOutstandingBytes(-1);
Assert.assertFalse("Expected a connection resume when connection dropped below limit .", c2.isPaused());
}
private static class MockConnection implements ServerConnection {
@Getter
private boolean paused = false;
@Override
public void pauseReading() {
this.paused = true;
}
@Override
public void resumeReading() {
this.paused = false;
}
@Override
public void send(WireCommand cmd) {
throw new UnsupportedOperationException();
}
@Override
public void setRequestProcessor(RequestProcessor cp) {
throw new UnsupportedOperationException();
}
@Override
public void close() {
throw new UnsupportedOperationException();
}
@Override
public boolean isClosed() {
throw new UnsupportedOperationException();
}
}
}
|
pettyferlove/rich
|
rich-module/rich-base-info-service/src/main/java/com/github/rich/base/service/impl/SensitiveInfoCaptchaValidateServiceImpl.java
|
<filename>rich-module/rich-base-info-service/src/main/java/com/github/rich/base/service/impl/SensitiveInfoCaptchaValidateServiceImpl.java
package com.github.rich.base.service.impl;
import com.github.rich.common.core.constants.SecurityConstant;
import com.github.rich.message.domain.dto.message.CaptchaMessage;
import com.github.rich.message.stream.source.SensitiveInfoCaptchaSmsSource;
import com.github.rich.security.service.AbstractCaptchaValidateService;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* 短信验证码
*
* @author Petty
*/
@Service("sensitiveInfoCaptchaValidateService")
@EnableBinding(SensitiveInfoCaptchaSmsSource.class)
public class SensitiveInfoCaptchaValidateServiceImpl extends AbstractCaptchaValidateService {
private final RedisTemplate redisTemplate;
private final SensitiveInfoCaptchaSmsSource source;
public SensitiveInfoCaptchaValidateServiceImpl(RedisTemplate redisTemplate, SensitiveInfoCaptchaSmsSource source) {
super(redisTemplate);
this.redisTemplate = redisTemplate;
this.source = source;
}
@Override
public Boolean create(String code, String captcha, long timeout) {
boolean result = false;
StringBuilder stringBuffer = new StringBuilder(SecurityConstant.SENSITIVE_INFO_CAPTCHA_CODE_KEY);
stringBuffer.append(":");
stringBuffer.append(code);
try {
if (redisTemplate.opsForValue().setIfAbsent(stringBuffer.toString(), captcha, timeout, TimeUnit.SECONDS)) {
CaptchaMessage captchaMessage = new CaptchaMessage();
captchaMessage.setReceiver(code);
captchaMessage.setCaptchaCode(captcha);
source.output().send(new GenericMessage<>(captchaMessage));
}
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
//清空
stringBuffer.setLength(0);
}
return result;
}
@Override
public Boolean validate(String code, String captcha) {
return super.validate(SecurityConstant.SENSITIVE_INFO_CAPTCHA_CODE_KEY, code, captcha);
}
}
|
ZoonLogonEchon/SimpleSceneRenderer
|
Renderer/Components/Meshes/sphere.cpp
|
<gh_stars>0
#ifdef TEST
#include "sphere.hpp"
#include <iostream>
#include <vector>
#include <random>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
Sphere::Sphere(const std::string name)
:name(name)
{
unsigned i = 0;
std::pair<std::vector<float>, unsigned> a = { {0.0, 0.5, 1.0}, i++ };
std::pair<std::vector<float>, unsigned> b = { {0.0, -0.5, 1.0}, i++ };
std::pair<std::vector<float>, unsigned> c = { {0.5, 0.0, 1.0}, i++ };
std::pair<std::vector<float>, unsigned> d = { {-0.5, 0.0, 1.0}, i++ };
std::pair<std::vector<float>, unsigned> e = { {0.0, 0.0, 1.5}, i++ };
std::pair<std::vector<float>, unsigned> f = { {0.0, 0.0, 0.5}, i++ };
//Triangle tade("",{ a.first, d.first, e.first });
//Triangle tace("", { a.first, c.first, e.first });
//Triangle tacf("", { a.first, c.first, f.first });
//Triangle tadf("", { a.first, d.first, f.first });
//Triangle tbde("", { b.first, d.first, e.first });
//Triangle tbce("", { b.first, c.first, e.first });
//Triangle tbcf("", { b.first, c.first, f.first });
//Triangle tbdf("", { b.first, d.first, f.first });
//triangles.push_back(tade);
//triangles.push_back(tace);
//triangles.push_back(tacf);
//triangles.push_back(tadf);
//triangles.push_back(tbde);
//triangles.push_back(tbce);
//triangles.push_back(tbcf);
//triangles.push_back(tbdf);
}
Sphere::~Sphere()
{
}
unsigned int Sphere::getPrimitivesCount()
{
return triangles.size();
}
void Sphere::bufferData(OGLProgram& prog, const std::string attrName)
{
//triangles[index].bufferData();
for(auto &triangle : triangles)
{
triangle.bufferData(prog, attrName);
}
}
void Sphere::draw(OGLProgram& prog)
{
for (auto& triangle : triangles)
{
//triangle.draw(prog);
}
}
#endif
|
fmilano/CppMicroServices
|
framework/test/bundles/libC1/TestBundleC1.cpp
|
<gh_stars>100-1000
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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 "cppmicroservices/BundleActivator.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/LDAPProp.h"
#include "cppmicroservices/ServiceRegistration.h"
#include "cppmicroservices/ServiceTracker.h"
#include "cppmicroservices/util/String.h"
#include <condition_variable>
#include <future>
#include <queue>
#include <thread>
namespace cppmicroservices {
class TestBundleC1Activator
: public BundleActivator
, public ServiceTrackerCustomizer<void>
{
public:
TestBundleC1Activator()
: context()
, stop(false)
, count(0)
{}
~TestBundleC1Activator() {}
void Start(BundleContext context)
{
this->context = context;
cppmicroservices::LDAPFilter filter(
cppmicroservices::LDAPProp(Constants::OBJECTCLASS) ==
"org.cppmicroservices.c1.*" &&
cppmicroservices::LDAPProp("i") == 5);
tracker.reset(new ServiceTracker<void>(context, filter, this));
tracker->Open();
std::promise<void> p;
std::shared_future<void> f = p.get_future().share();
// Start ten threads, each registering ten services
for (int c = 0; c < 10; ++c) {
threads.emplace_back(
&TestBundleC1Activator::RegisterServices, this, f, c);
}
// Start a thread that unregisters the services
unregThread = std::thread(&TestBundleC1Activator::UnRegister, this);
p.set_value();
}
void Stop(BundleContext)
{
for (auto& th : threads) {
th.join();
}
stop = true;
unregThread.join();
tracker->Close();
if (count != 0)
throw std::logic_error("Not unregistered all services");
}
void RegisterServices(std::shared_future<void> f, int c)
{
f.wait();
for (int i = 0; i < 10; ++i) {
// Register a service ten times with different properties
InterfaceMap im;
im[std::string("org.cppmicroservices.c1.") + util::ToString(c)] =
std::make_shared<int>(1);
ServiceProperties props;
props["i"] = i;
auto reg = context.RegisterService(
std::make_shared<const InterfaceMap>(im), props);
regs.Lock(), regs.v.emplace_back(std::move(reg));
count++;
if (i % 5 == 0)
regs.NotifyAll();
}
}
void UnRegister()
{
while (!(stop.load() && (regs.Lock(), regs.v.empty()))) {
std::vector<ServiceRegistrationU> currRegs;
regs.Lock(), std::swap(currRegs, regs.v);
if (currRegs.empty()) {
auto l = regs.Lock();
regs.WaitFor(l, std::chrono::milliseconds(100), [this] {
return !regs.v.empty();
});
std::swap(currRegs, regs.v);
}
for (auto& reg : currRegs) {
if (reg.GetReference().GetProperty("i") == 5) {
// change a property, unregister later
ServiceProperties newProps;
newProps["i"] = 15;
reg.SetProperties(newProps);
regs.Lock(), regs.v.push_back(reg);
} else {
reg.Unregister();
count--;
}
}
}
}
// -------------------- Service Tracker Customizer -------------------------
InterfaceMapConstPtr AddingService(const ServiceReferenceU& reference)
{
if (reference.GetProperty("i") == 5) {
auto l = additionalReg.Lock();
if (!additionalReg.v) {
InterfaceMap im;
im[std::string("org.cppmicroservices.c1.additional")] =
std::make_shared<int>(2);
additionalReg.v =
context.RegisterService(std::make_shared<const InterfaceMap>(im));
}
return InterfaceMapConstPtr();
}
return context.GetService(reference);
}
void ModifiedService(const ServiceReferenceU& reference,
const InterfaceMapConstPtr& /*service*/)
{
if (reference.GetProperty("i") != 5)
throw std::logic_error("modified end match: wrong property");
context.GetService(reference);
}
void RemovedService(const ServiceReferenceU& /*reference*/,
const InterfaceMapConstPtr& /*service*/)
{
auto l = additionalReg.Lock();
if (additionalReg.v)
additionalReg.v.Unregister();
}
private:
BundleContext context;
std::unique_ptr<ServiceTracker<void>> tracker;
std::vector<std::thread> threads;
std::thread unregThread;
struct
: detail::MultiThreaded<detail::MutexLockingStrategy<>,
detail::WaitCondition>
{
std::vector<ServiceRegistrationU> v;
} regs;
struct : detail::MultiThreaded<>
{
ServiceRegistrationU v;
} additionalReg;
std::atomic<bool> stop;
std::atomic<int> count;
};
} // namespace cppmicroservices
CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(
cppmicroservices::TestBundleC1Activator)
|
AdjieGunt/unpamkita-react
|
src/containers/CategoryContainer/index.js
|
import CategoryContainer from './CategoryContainer'
export default CategoryContainer
|
arithmetic1728/google-api-java-client-services
|
clients/google-api-services-dataflow/v1b3/1.31.0/com/google/api/services/dataflow/model/QueryInfo.java
|
<reponame>arithmetic1728/google-api-java-client-services
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dataflow.model;
/**
* Information about a validated query.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dataflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class QueryInfo extends com.google.api.client.json.GenericJson {
/**
* Includes an entry for each satisfied QueryProperty.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> queryProperty;
/**
* Includes an entry for each satisfied QueryProperty.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getQueryProperty() {
return queryProperty;
}
/**
* Includes an entry for each satisfied QueryProperty.
* @param queryProperty queryProperty or {@code null} for none
*/
public QueryInfo setQueryProperty(java.util.List<java.lang.String> queryProperty) {
this.queryProperty = queryProperty;
return this;
}
@Override
public QueryInfo set(String fieldName, Object value) {
return (QueryInfo) super.set(fieldName, value);
}
@Override
public QueryInfo clone() {
return (QueryInfo) super.clone();
}
}
|
serfend/Project.Web.Front.Vue.DepartmentGLMap
|
src/api/bbs/post.js
|
import request from '@/utils/request'
/**
* 新增/评论帖子
*
* @export
* @param {*} model 帖子
* @returns
*/
export function newContent({ title, content, replySubject, replyTo }) {
return request.post('/post/post', { title, content, replySubject, replyTo })
}
/**
* 删除帖子
*
* @export
* @param {*} id
* @returns
*/
export function removeContent(id) {
return request.delete('/post/post', {
params: {
id
}
})
}
import form from '@/utils/form'
/**
* 筛选帖子
*
* @export
* @param {*} model 帖子
* @returns
*/
export function getContent({ page, create, createBy, replySubject, replyTo }) {
return request.post('/post/post', {
page,
create: form.toQueryStartEnd(create),
createBy: form.toQueryValue(createBy),
replyTo: form.toQueryValue(replyTo),
replySubject: form.toQueryValue(replySubject)
})
}
/**
* 点赞
*
* @export
* @param {*} id 帖子id
* @param {*} like 是否赞
* @returns
*/
export function likeContent({ id, like }) {
return request.post('/post/like', { id, like })
}
|
tfisher1226/ARIES
|
aries/common/common-util/src/main/java/org/aries/util/encrypt/EncryptPassword.java
|
<gh_stars>1-10
package org.aries.util.encrypt;
//TODO - unused for now - placeholder
public class EncryptPassword {
public static void main(String ar[]) throws Exception {
String clearTextPassword = ar[0];
//String clearTextPassword=ar[0]+":ManagementRealm:"+ar[1]; //---> This is how JBoss Encrypts password
String hashedPassword = createPasswordHash("MD5", "hex", null, null, clearTextPassword);
System.out.println("clearTextPassword: "+clearTextPassword);
System.out.println("hashedPassword: "+hashedPassword);
}
public static String createPasswordHash(String string, String string2, Object object, Object object2, String clearTextPassword) {
//TODO - leave open for now
return null;
}
}
|
sadupally/Dev
|
unisa-util/unisa-sharedclasses/src/java/za/ac/unisa/lms/domain/processDrivenSms/SmsRecipientResult.java
|
<reponame>sadupally/Dev
package za.ac.unisa.lms.domain.processDrivenSms;
public class SmsRecipientResult {
private int studentNr;
private String message;
private String cellNr;
private String errMsg;
public int getStudentNr() {
return studentNr;
}
public void setStudentNr(int studentNr) {
this.studentNr = studentNr;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCellNr() {
return cellNr;
}
public void setCellNr(String cellNr) {
this.cellNr = cellNr;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
}
|
Sen-442b/Ghost
|
core/server/data/migrations/versions/4.15/01-add-temp-members-analytic-events-table.js
|
<reponame>Sen-442b/Ghost
const utils = require('../../utils');
module.exports = utils.addTable('temp_member_analytic_events', {
id: {type: 'string', maxlength: 24, nullable: false, primary: true},
event_name: {type: 'string', maxlength: 50, nullable: false},
created_at: {type: 'dateTime', nullable: false},
member_id: {type: 'string', maxlength: 24, nullable: false},
member_status: {type: 'string', maxlength: 50, nullable: false},
entry_id: {type: 'string', maxlength: 24, nullable: true},
source_url: {type: 'string', maxlength: 2000, nullable: true},
metadata: {type: 'string', maxlength: 191, nullable: true}
});
|
srcarter3/awips2
|
cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/stationreporting/StationReportingAction.java
|
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.hydro.stationreporting;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import com.raytheon.viz.ui.dialogs.ICloseCallback;
/**
* Action for unimplemented features. To be used temporarily until final
* behavior is implemented.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 06/27/2006 lvenable Initial Creation.
* 04/16/2013 1790 rferrel Changes for non-blocking stationReportingDlg.
* 05/04/2016 5483 dgilling Updates for updated
* StationReportingStatusDlg.
*
* </pre>
*
* @author lvenable
*
*/
public class StationReportingAction extends AbstractHandler {
private StationReportingStatusDlg stationReportingDlg;
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
if (stationReportingDlg == null || stationReportingDlg.isDisposed()) {
Shell shell = HandlerUtil.getActiveShellChecked(arg0);
stationReportingDlg = new StationReportingStatusDlg(shell);
stationReportingDlg.addCloseCallback(new ICloseCallback() {
@Override
public void dialogClosed(Object returnValue) {
stationReportingDlg = null;
}
});
stationReportingDlg.open();
} else {
stationReportingDlg.bringToTop();
}
return null;
}
}
|
jinroq/msgraph
|
lib/msgraph/odata/types/primitive_types/guid_type.rb
|
class Msgraph
module Odata
module Types
module PrimitiveTypes
class GuidType < Msgraph::Odata::Types::BaseType
def valid_value?(value)
String === value
end
def coerce(value)
case value
when Symbol
value.to_s
when Numeric
value.to_s
when String
value
else
raise TypeError, "Cannot convert #{value.inspect} into a Guid."
end
end
def name
"Edm.Guid"
end
end
end
end
end
end
|
jpvelsamy/mingo
|
src/com/mingo/client/Resrv.java
|
<reponame>jpvelsamy/mingo<gh_stars>0
package com.mingo.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Cookies;
import com.mingo.client.booking.BookingViewService;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Resrv implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
Cookies.setCookie("userId", "1");
final TabSet topTabSet = new TabSet();
topTabSet.setTabBarPosition(Side.TOP);
topTabSet.setWidth("100%");
topTabSet.setHeight("100%");
Tab bookingPage = new Tab("Book tickets");
VStack bookingStack= new BookingViewService().getBookingPage();
bookingPage.setPane(bookingStack);
Tab myBookings = new Tab("My bookings");
VStack mybookingsStack = createMyBookingPage();
myBookings.setPane(mybookingsStack);
Tab webCheckin = new Tab("Web Checkin");
VStack webCheckingStack = createWebCheckinPage();
myBookings.setPane(webCheckingStack);
topTabSet.addTab(bookingPage);
topTabSet.addTab(myBookings);
topTabSet.addTab(webCheckin);
VLayout vLayout = new VLayout();
vLayout.setMembersMargin(15);
vLayout.addMember(topTabSet);
vLayout.setWidth("100%");
vLayout.setHeight("100%");
vLayout.draw();
}
private VStack createWebCheckinPage() {
VStack vStack = new VStack();
vStack.setLeft(175);
vStack.setTop(50);
vStack.setWidth("70%");
vStack.setMembersMargin(10);
return vStack;
}
protected void completePayment(String expiryDateValue,
String cardHolderValue, String cardNumberValue, String cvvNum) {
// TODO Auto-generated method stub
}
private VStack createMyBookingPage() {
VStack vStack = new VStack();
vStack.setLeft(175);
vStack.setTop(50);
vStack.setWidth("70%");
vStack.setMembersMargin(10);
return vStack;
}
}
|
wetcod/vvisp
|
packages/vvisp-utils/src/blockchainApis/index.js
|
const getContractFactory = require('./getContractFactory');
const getTxCount = require('./getTxCount');
const privateKeyToAddress = require('./privateKeyToAddress');
const sendTx = require('./sendTx');
module.exports = {
getContractFactory,
getTxCount,
privateKeyToAddress,
sendTx
};
|
DVSR1966/par4all
|
packages/PIPS/validation/Gpu/simple_loop.c
|
enum { N = 10000};
double a[N], b[N], c[N];
int main() {
int i;
for(i = 0; i < N; i++)
a[i] = b[i] + c[i];
return 0;
}
|
jurgendl/jhaws
|
jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/components/tree/Node.java
|
<filename>jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/components/tree/Node.java
package org.jhaws.common.web.wicket.components.tree;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
public interface Node<T> extends Iterable<Node<T>>, Serializable {
List<Node<T>> children();
T get();
/* default */Node<T> getChild(
int i);/*
* { return this.children().get(i); }
*/
/* default */int getChildCount(); /*
* { return this.children().size(); }
*/
@Override
/* default */Iterator<Node<T>> iterator();/*
* { return
* this.children().iterator(); }
*/
}
|
AnneLivia/URI-Online
|
Online Judges/URI/1533/main.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, num;
vector<pair<int,int>>v;
while(cin >> n && n) {
v.clear();
for(int i = 0; i < n; i++) {
cin >> num;
v.push_back(make_pair(num,i+1));
}
sort(v.rbegin(),v.rend());
cout << v[1].second << endl;
}
return 0;
}
|
ghorbanzade/beacon
|
umb-cs681-2016s/src/main/java/hw27/BankServerMain.java
|
<gh_stars>1-10
//
// CS681: Object Oriented Software Development
// Copyright 2016 <NAME> <<EMAIL>>
// More info: https://github.com/ghorbanzade/beacon
//
package edu.umb.cs681.hw27;
/**
* Demonstrates how a bank server can be created to hold bank account
* information and handle multiple client requests.
*
* @author <NAME>
* @see BankServer
*/
public final class BankServerMain {
/**
* This program creates a bank server which holds bank account informations
* and starts to listen to incoming requests on a socket.
*
* @param args command line arguments
*/
public static void main(String[] args) {
ConfigReader cr = new ConfigReader("/bank.properties");
int port = Integer.parseInt(cr.get("server.port"));
int timeout = Integer.parseInt(cr.get("server.timeout"));
BankServer server = new BankServer(port, timeout);
server.init();
}
/**
* This class should not be instantiated.
*/
private BankServerMain() {
}
}
|
jainsakshi2395/linux
|
drivers/net/phy/mxl-gpy.c
|
// SPDX-License-Identifier: GPL-2.0+
/* Copyright (C) 2021 Maxlinear Corporation
* Copyright (C) 2020 Intel Corporation
*
* Drivers for Maxlinear Ethernet GPY
*
*/
#include <linux/module.h>
#include <linux/bitfield.h>
#include <linux/phy.h>
#include <linux/netdevice.h>
/* PHY ID */
#define PHY_ID_GPYx15B_MASK 0xFFFFFFFC
#define PHY_ID_GPY21xB_MASK 0xFFFFFFF9
#define PHY_ID_GPY2xx 0x67C9DC00
#define PHY_ID_GPY115B 0x67C9DF00
#define PHY_ID_GPY115C 0x67C9DF10
#define PHY_ID_GPY211B 0x67C9DE08
#define PHY_ID_GPY211C 0x67C9DE10
#define PHY_ID_GPY212B 0x67C9DE09
#define PHY_ID_GPY212C 0x67C9DE20
#define PHY_ID_GPY215B 0x67C9DF04
#define PHY_ID_GPY215C 0x67C9DF20
#define PHY_ID_GPY241B 0x67C9DE40
#define PHY_ID_GPY241BM 0x67C9DE80
#define PHY_ID_GPY245B 0x67C9DEC0
#define PHY_MIISTAT 0x18 /* MII state */
#define PHY_IMASK 0x19 /* interrupt mask */
#define PHY_ISTAT 0x1A /* interrupt status */
#define PHY_FWV 0x1E /* firmware version */
#define PHY_MIISTAT_SPD_MASK GENMASK(2, 0)
#define PHY_MIISTAT_DPX BIT(3)
#define PHY_MIISTAT_LS BIT(10)
#define PHY_MIISTAT_SPD_10 0
#define PHY_MIISTAT_SPD_100 1
#define PHY_MIISTAT_SPD_1000 2
#define PHY_MIISTAT_SPD_2500 4
#define PHY_IMASK_WOL BIT(15) /* Wake-on-LAN */
#define PHY_IMASK_ANC BIT(10) /* Auto-Neg complete */
#define PHY_IMASK_ADSC BIT(5) /* Link auto-downspeed detect */
#define PHY_IMASK_DXMC BIT(2) /* Duplex mode change */
#define PHY_IMASK_LSPC BIT(1) /* Link speed change */
#define PHY_IMASK_LSTC BIT(0) /* Link state change */
#define PHY_IMASK_MASK (PHY_IMASK_LSTC | \
PHY_IMASK_LSPC | \
PHY_IMASK_DXMC | \
PHY_IMASK_ADSC | \
PHY_IMASK_ANC)
#define PHY_FWV_REL_MASK BIT(15)
#define PHY_FWV_TYPE_MASK GENMASK(11, 8)
#define PHY_FWV_MINOR_MASK GENMASK(7, 0)
/* SGMII */
#define VSPEC1_SGMII_CTRL 0x08
#define VSPEC1_SGMII_CTRL_ANEN BIT(12) /* Aneg enable */
#define VSPEC1_SGMII_CTRL_ANRS BIT(9) /* Restart Aneg */
#define VSPEC1_SGMII_ANEN_ANRS (VSPEC1_SGMII_CTRL_ANEN | \
VSPEC1_SGMII_CTRL_ANRS)
/* WoL */
#define VPSPEC2_WOL_CTL 0x0E06
#define VPSPEC2_WOL_AD01 0x0E08
#define VPSPEC2_WOL_AD23 0x0E09
#define VPSPEC2_WOL_AD45 0x0E0A
#define WOL_EN BIT(0)
static const struct {
int type;
int minor;
} ver_need_sgmii_reaneg[] = {
{7, 0x6D},
{8, 0x6D},
{9, 0x73},
};
static int gpy_config_init(struct phy_device *phydev)
{
int ret;
/* Mask all interrupts */
ret = phy_write(phydev, PHY_IMASK, 0);
if (ret)
return ret;
/* Clear all pending interrupts */
ret = phy_read(phydev, PHY_ISTAT);
return ret < 0 ? ret : 0;
}
static int gpy_probe(struct phy_device *phydev)
{
int ret;
if (!phydev->is_c45) {
ret = phy_get_c45_ids(phydev);
if (ret < 0)
return ret;
}
/* Show GPY PHY FW version in dmesg */
ret = phy_read(phydev, PHY_FWV);
if (ret < 0)
return ret;
phydev_info(phydev, "Firmware Version: 0x%04X (%s)\n", ret,
(ret & PHY_FWV_REL_MASK) ? "release" : "test");
return 0;
}
static bool gpy_sgmii_need_reaneg(struct phy_device *phydev)
{
int fw_ver, fw_type, fw_minor;
size_t i;
fw_ver = phy_read(phydev, PHY_FWV);
if (fw_ver < 0)
return true;
fw_type = FIELD_GET(PHY_FWV_TYPE_MASK, fw_ver);
fw_minor = FIELD_GET(PHY_FWV_MINOR_MASK, fw_ver);
for (i = 0; i < ARRAY_SIZE(ver_need_sgmii_reaneg); i++) {
if (fw_type != ver_need_sgmii_reaneg[i].type)
continue;
if (fw_minor < ver_need_sgmii_reaneg[i].minor)
return true;
break;
}
return false;
}
static bool gpy_2500basex_chk(struct phy_device *phydev)
{
int ret;
ret = phy_read(phydev, PHY_MIISTAT);
if (ret < 0) {
phydev_err(phydev, "Error: MDIO register access failed: %d\n",
ret);
return false;
}
if (!(ret & PHY_MIISTAT_LS) ||
FIELD_GET(PHY_MIISTAT_SPD_MASK, ret) != PHY_MIISTAT_SPD_2500)
return false;
phydev->speed = SPEED_2500;
phydev->interface = PHY_INTERFACE_MODE_2500BASEX;
phy_modify_mmd(phydev, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL,
VSPEC1_SGMII_CTRL_ANEN, 0);
return true;
}
static bool gpy_sgmii_aneg_en(struct phy_device *phydev)
{
int ret;
ret = phy_read_mmd(phydev, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL);
if (ret < 0) {
phydev_err(phydev, "Error: MMD register access failed: %d\n",
ret);
return true;
}
return (ret & VSPEC1_SGMII_CTRL_ANEN) ? true : false;
}
static int gpy_config_aneg(struct phy_device *phydev)
{
bool changed = false;
u32 adv;
int ret;
if (phydev->autoneg == AUTONEG_DISABLE) {
/* Configure half duplex with genphy_setup_forced,
* because genphy_c45_pma_setup_forced does not support.
*/
return phydev->duplex != DUPLEX_FULL
? genphy_setup_forced(phydev)
: genphy_c45_pma_setup_forced(phydev);
}
ret = genphy_c45_an_config_aneg(phydev);
if (ret < 0)
return ret;
if (ret > 0)
changed = true;
adv = linkmode_adv_to_mii_ctrl1000_t(phydev->advertising);
ret = phy_modify_changed(phydev, MII_CTRL1000,
ADVERTISE_1000FULL | ADVERTISE_1000HALF,
adv);
if (ret < 0)
return ret;
if (ret > 0)
changed = true;
ret = genphy_c45_check_and_restart_aneg(phydev, changed);
if (ret < 0)
return ret;
if (phydev->interface == PHY_INTERFACE_MODE_USXGMII ||
phydev->interface == PHY_INTERFACE_MODE_INTERNAL)
return 0;
/* No need to trigger re-ANEG if link speed is 2.5G or SGMII ANEG is
* disabled.
*/
if (!gpy_sgmii_need_reaneg(phydev) || gpy_2500basex_chk(phydev) ||
!gpy_sgmii_aneg_en(phydev))
return 0;
/* There is a design constraint in GPY2xx device where SGMII AN is
* only triggered when there is change of speed. If, PHY link
* partner`s speed is still same even after PHY TPI is down and up
* again, SGMII AN is not triggered and hence no new in-band message
* from GPY to MAC side SGMII.
* This could cause an issue during power up, when PHY is up prior to
* MAC. At this condition, once MAC side SGMII is up, MAC side SGMII
* wouldn`t receive new in-band message from GPY with correct link
* status, speed and duplex info.
*
* 1) If PHY is already up and TPI link status is still down (such as
* hard reboot), TPI link status is polled for 4 seconds before
* retriggerring SGMII AN.
* 2) If PHY is already up and TPI link status is also up (such as soft
* reboot), polling of TPI link status is not needed and SGMII AN is
* immediately retriggered.
* 3) Other conditions such as PHY is down, speed change etc, skip
* retriggering SGMII AN. Note: in case of speed change, GPY FW will
* initiate SGMII AN.
*/
if (phydev->state != PHY_UP)
return 0;
ret = phy_read_poll_timeout(phydev, MII_BMSR, ret, ret & BMSR_LSTATUS,
20000, 4000000, false);
if (ret == -ETIMEDOUT)
return 0;
else if (ret < 0)
return ret;
/* Trigger SGMII AN. */
return phy_modify_mmd(phydev, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL,
VSPEC1_SGMII_CTRL_ANRS, VSPEC1_SGMII_CTRL_ANRS);
}
static void gpy_update_interface(struct phy_device *phydev)
{
int ret;
/* Interface mode is fixed for USXGMII and integrated PHY */
if (phydev->interface == PHY_INTERFACE_MODE_USXGMII ||
phydev->interface == PHY_INTERFACE_MODE_INTERNAL)
return;
/* Automatically switch SERDES interface between SGMII and 2500-BaseX
* according to speed. Disable ANEG in 2500-BaseX mode.
*/
switch (phydev->speed) {
case SPEED_2500:
phydev->interface = PHY_INTERFACE_MODE_2500BASEX;
ret = phy_modify_mmd(phydev, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL,
VSPEC1_SGMII_CTRL_ANEN, 0);
if (ret < 0)
phydev_err(phydev,
"Error: Disable of SGMII ANEG failed: %d\n",
ret);
break;
case SPEED_1000:
case SPEED_100:
case SPEED_10:
phydev->interface = PHY_INTERFACE_MODE_SGMII;
if (gpy_sgmii_aneg_en(phydev))
break;
/* Enable and restart SGMII ANEG for 10/100/1000Mbps link speed
* if ANEG is disabled (in 2500-BaseX mode).
*/
ret = phy_modify_mmd(phydev, MDIO_MMD_VEND1, VSPEC1_SGMII_CTRL,
VSPEC1_SGMII_ANEN_ANRS,
VSPEC1_SGMII_ANEN_ANRS);
if (ret < 0)
phydev_err(phydev,
"Error: Enable of SGMII ANEG failed: %d\n",
ret);
break;
}
}
static int gpy_read_status(struct phy_device *phydev)
{
int ret;
ret = genphy_update_link(phydev);
if (ret)
return ret;
phydev->speed = SPEED_UNKNOWN;
phydev->duplex = DUPLEX_UNKNOWN;
phydev->pause = 0;
phydev->asym_pause = 0;
if (phydev->autoneg == AUTONEG_ENABLE && phydev->autoneg_complete) {
ret = genphy_c45_read_lpa(phydev);
if (ret < 0)
return ret;
/* Read the link partner's 1G advertisement */
ret = phy_read(phydev, MII_STAT1000);
if (ret < 0)
return ret;
mii_stat1000_mod_linkmode_lpa_t(phydev->lp_advertising, ret);
} else if (phydev->autoneg == AUTONEG_DISABLE) {
linkmode_zero(phydev->lp_advertising);
}
ret = phy_read(phydev, PHY_MIISTAT);
if (ret < 0)
return ret;
phydev->link = (ret & PHY_MIISTAT_LS) ? 1 : 0;
phydev->duplex = (ret & PHY_MIISTAT_DPX) ? DUPLEX_FULL : DUPLEX_HALF;
switch (FIELD_GET(PHY_MIISTAT_SPD_MASK, ret)) {
case PHY_MIISTAT_SPD_10:
phydev->speed = SPEED_10;
break;
case PHY_MIISTAT_SPD_100:
phydev->speed = SPEED_100;
break;
case PHY_MIISTAT_SPD_1000:
phydev->speed = SPEED_1000;
break;
case PHY_MIISTAT_SPD_2500:
phydev->speed = SPEED_2500;
break;
}
if (phydev->link)
gpy_update_interface(phydev);
return 0;
}
static int gpy_config_intr(struct phy_device *phydev)
{
u16 mask = 0;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED)
mask = PHY_IMASK_MASK;
return phy_write(phydev, PHY_IMASK, mask);
}
static irqreturn_t gpy_handle_interrupt(struct phy_device *phydev)
{
int reg;
reg = phy_read(phydev, PHY_ISTAT);
if (reg < 0) {
phy_error(phydev);
return IRQ_NONE;
}
if (!(reg & PHY_IMASK_MASK))
return IRQ_NONE;
phy_trigger_machine(phydev);
return IRQ_HANDLED;
}
static int gpy_set_wol(struct phy_device *phydev,
struct ethtool_wolinfo *wol)
{
struct net_device *attach_dev = phydev->attached_dev;
int ret;
if (wol->wolopts & WAKE_MAGIC) {
/* MAC address - Byte0:Byte1:Byte2:Byte3:Byte4:Byte5
* VPSPEC2_WOL_AD45 = Byte0:Byte1
* VPSPEC2_WOL_AD23 = Byte2:Byte3
* VPSPEC2_WOL_AD01 = Byte4:Byte5
*/
ret = phy_set_bits_mmd(phydev, MDIO_MMD_VEND2,
VPSPEC2_WOL_AD45,
((attach_dev->dev_addr[0] << 8) |
attach_dev->dev_addr[1]));
if (ret < 0)
return ret;
ret = phy_set_bits_mmd(phydev, MDIO_MMD_VEND2,
VPSPEC2_WOL_AD23,
((attach_dev->dev_addr[2] << 8) |
attach_dev->dev_addr[3]));
if (ret < 0)
return ret;
ret = phy_set_bits_mmd(phydev, MDIO_MMD_VEND2,
VPSPEC2_WOL_AD01,
((attach_dev->dev_addr[4] << 8) |
attach_dev->dev_addr[5]));
if (ret < 0)
return ret;
/* Enable the WOL interrupt */
ret = phy_write(phydev, PHY_IMASK, PHY_IMASK_WOL);
if (ret < 0)
return ret;
/* Enable magic packet matching */
ret = phy_set_bits_mmd(phydev, MDIO_MMD_VEND2,
VPSPEC2_WOL_CTL,
WOL_EN);
if (ret < 0)
return ret;
/* Clear the interrupt status register.
* Only WoL is enabled so clear all.
*/
ret = phy_read(phydev, PHY_ISTAT);
if (ret < 0)
return ret;
} else {
/* Disable magic packet matching */
ret = phy_clear_bits_mmd(phydev, MDIO_MMD_VEND2,
VPSPEC2_WOL_CTL,
WOL_EN);
if (ret < 0)
return ret;
}
if (wol->wolopts & WAKE_PHY) {
/* Enable the link state change interrupt */
ret = phy_set_bits(phydev, PHY_IMASK, PHY_IMASK_LSTC);
if (ret < 0)
return ret;
/* Clear the interrupt status register */
ret = phy_read(phydev, PHY_ISTAT);
if (ret < 0)
return ret;
if (ret & (PHY_IMASK_MASK & ~PHY_IMASK_LSTC))
phy_trigger_machine(phydev);
return 0;
}
/* Disable the link state change interrupt */
return phy_clear_bits(phydev, PHY_IMASK, PHY_IMASK_LSTC);
}
static void gpy_get_wol(struct phy_device *phydev,
struct ethtool_wolinfo *wol)
{
int ret;
wol->supported = WAKE_MAGIC | WAKE_PHY;
wol->wolopts = 0;
ret = phy_read_mmd(phydev, MDIO_MMD_VEND2, VPSPEC2_WOL_CTL);
if (ret & WOL_EN)
wol->wolopts |= WAKE_MAGIC;
ret = phy_read(phydev, PHY_IMASK);
if (ret & PHY_IMASK_LSTC)
wol->wolopts |= WAKE_PHY;
}
static int gpy_loopback(struct phy_device *phydev, bool enable)
{
int ret;
ret = phy_modify(phydev, MII_BMCR, BMCR_LOOPBACK,
enable ? BMCR_LOOPBACK : 0);
if (!ret) {
/* It takes some time for PHY device to switch
* into/out-of loopback mode.
*/
msleep(100);
}
return ret;
}
static int gpy115_loopback(struct phy_device *phydev, bool enable)
{
int ret;
int fw_minor;
if (enable)
return gpy_loopback(phydev, enable);
ret = phy_read(phydev, PHY_FWV);
if (ret < 0)
return ret;
fw_minor = FIELD_GET(PHY_FWV_MINOR_MASK, ret);
if (fw_minor > 0x0076)
return gpy_loopback(phydev, 0);
return genphy_soft_reset(phydev);
}
static struct phy_driver gpy_drivers[] = {
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY2xx),
.name = "Maxlinear Ethernet GPY2xx",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
.phy_id = PHY_ID_GPY115B,
.phy_id_mask = PHY_ID_GPYx15B_MASK,
.name = "Maxlinear Ethernet GPY115B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy115_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY115C),
.name = "Maxlinear Ethernet GPY115C",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy115_loopback,
},
{
.phy_id = PHY_ID_GPY211B,
.phy_id_mask = PHY_ID_GPY21xB_MASK,
.name = "Maxlinear Ethernet GPY211B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY211C),
.name = "Maxlinear Ethernet GPY211C",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
.phy_id = PHY_ID_GPY212B,
.phy_id_mask = PHY_ID_GPY21xB_MASK,
.name = "Maxlinear Ethernet GPY212B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY212C),
.name = "Maxlinear Ethernet GPY212C",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
.phy_id = PHY_ID_GPY215B,
.phy_id_mask = PHY_ID_GPYx15B_MASK,
.name = "Maxlinear Ethernet GPY215B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY215C),
.name = "Maxlinear Ethernet GPY215C",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY241B),
.name = "Maxlinear Ethernet GPY241B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY241BM),
.name = "Maxlinear Ethernet GPY241BM",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
{
PHY_ID_MATCH_MODEL(PHY_ID_GPY245B),
.name = "Maxlinear Ethernet GPY245B",
.get_features = genphy_c45_pma_read_abilities,
.config_init = gpy_config_init,
.probe = gpy_probe,
.suspend = genphy_suspend,
.resume = genphy_resume,
.config_aneg = gpy_config_aneg,
.aneg_done = genphy_c45_aneg_done,
.read_status = gpy_read_status,
.config_intr = gpy_config_intr,
.handle_interrupt = gpy_handle_interrupt,
.set_wol = gpy_set_wol,
.get_wol = gpy_get_wol,
.set_loopback = gpy_loopback,
},
};
module_phy_driver(gpy_drivers);
static struct mdio_device_id __maybe_unused gpy_tbl[] = {
{PHY_ID_MATCH_MODEL(PHY_ID_GPY2xx)},
{PHY_ID_GPY115B, PHY_ID_GPYx15B_MASK},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY115C)},
{PHY_ID_GPY211B, PHY_ID_GPY21xB_MASK},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY211C)},
{PHY_ID_GPY212B, PHY_ID_GPY21xB_MASK},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY212C)},
{PHY_ID_GPY215B, PHY_ID_GPYx15B_MASK},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY215C)},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY241B)},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY241BM)},
{PHY_ID_MATCH_MODEL(PHY_ID_GPY245B)},
{ }
};
MODULE_DEVICE_TABLE(mdio, gpy_tbl);
MODULE_DESCRIPTION("Maxlinear Ethernet GPY Driver");
MODULE_AUTHOR("<NAME>");
MODULE_LICENSE("GPL");
|
codenote/chromium-test
|
ash/system/tray_update.cc
|
// 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 "ash/system/tray_update.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/tray/fixed_sized_image_view.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_views.h"
#include "base/time.h"
#include "base/timer.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/aura/window.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace {
// How many seconds should we wait before showing the nag reminder?
const int kUpdateNaggingTimeSeconds = 24 * 60 * 60;
// How long should the nag reminder be displayed?
const int kShowUpdateNaggerForSeconds = 15;
int DecideResource(ash::UpdateObserver::UpdateSeverity severity, bool dark) {
switch (severity) {
case ash::UpdateObserver::UPDATE_NORMAL:
return dark ? IDR_AURA_UBER_TRAY_UPDATE_DARK:
IDR_AURA_UBER_TRAY_UPDATE;
case ash::UpdateObserver::UPDATE_LOW_GREEN:
return dark ? IDR_AURA_UBER_TRAY_UPDATE_DARK_GREEN :
IDR_AURA_UBER_TRAY_UPDATE_GREEN;
case ash::UpdateObserver::UPDATE_HIGH_ORANGE:
return dark ? IDR_AURA_UBER_TRAY_UPDATE_DARK_ORANGE :
IDR_AURA_UBER_TRAY_UPDATE_ORANGE;
case ash::UpdateObserver::UPDATE_SEVERE_RED:
return dark ? IDR_AURA_UBER_TRAY_UPDATE_DARK_RED :
IDR_AURA_UBER_TRAY_UPDATE_RED;
}
NOTREACHED() << "Unknown update severity level.";
return 0;
}
class UpdateView : public ash::internal::ActionableView {
public:
explicit UpdateView(ash::UpdateObserver::UpdateSeverity severity) {
SetLayoutManager(new
views::BoxLayout(views::BoxLayout::kHorizontal,
ash::kTrayPopupPaddingHorizontal, 0,
ash::kTrayPopupPaddingBetweenItems));
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
views::ImageView* image =
new ash::internal::FixedSizedImageView(0, ash::kTrayPopupItemHeight);
image->SetImage(bundle.GetImageNamed(DecideResource(severity, true)).
ToImageSkia());
AddChildView(image);
AddChildView(new views::Label(
bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_UPDATE)));
SetAccessibleName(bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_UPDATE));
}
virtual ~UpdateView() {}
private:
// Overridden from ActionableView.
virtual bool PerformAction(const ui::Event& event) OVERRIDE {
ash::Shell::GetInstance()->system_tray_delegate()->RequestRestart();
return true;
}
DISALLOW_COPY_AND_ASSIGN(UpdateView);
};
}
namespace ash {
namespace internal {
namespace tray {
class UpdateNagger : public ui::LayerAnimationObserver {
public:
explicit UpdateNagger(SystemTrayItem* owner)
: owner_(owner) {
RestartTimer();
owner_->system_tray()->GetWidget()->GetNativeView()->layer()->
GetAnimator()->AddObserver(this);
}
virtual ~UpdateNagger() {
internal::StatusAreaWidget* status_area =
Shell::GetPrimaryRootWindowController()->shelf()->status_area_widget();
if (status_area) {
status_area->system_tray()->GetWidget()->GetNativeView()->layer()->
GetAnimator()->RemoveObserver(this);
}
}
void RestartTimer() {
timer_.Stop();
timer_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(kUpdateNaggingTimeSeconds),
this,
&UpdateNagger::Nag);
}
private:
void Nag() {
owner_->PopupDetailedView(kShowUpdateNaggerForSeconds, false);
}
// Overridden from ui::LayerAnimationObserver.
virtual void OnLayerAnimationEnded(
ui::LayerAnimationSequence* sequence) OVERRIDE {
// TODO(oshima): Find out if the updator will be shown on non
// primary display.
if (Shell::GetPrimaryRootWindowController()->shelf()->IsVisible())
timer_.Stop();
else if (!timer_.IsRunning())
RestartTimer();
}
virtual void OnLayerAnimationAborted(
ui::LayerAnimationSequence* sequence) OVERRIDE {}
virtual void OnLayerAnimationScheduled(
ui::LayerAnimationSequence* sequence) OVERRIDE {}
SystemTrayItem* owner_;
base::OneShotTimer<UpdateNagger> timer_;
DISALLOW_COPY_AND_ASSIGN(UpdateNagger);
};
} // namespace tray
TrayUpdate::TrayUpdate(SystemTray* system_tray)
: TrayImageItem(system_tray, IDR_AURA_UBER_TRAY_UPDATE),
severity_(UpdateObserver::UPDATE_NORMAL) {
Shell::GetInstance()->system_tray_notifier()->AddUpdateObserver(this);
}
TrayUpdate::~TrayUpdate() {
Shell::GetInstance()->system_tray_notifier()->RemoveUpdateObserver(this);
}
bool TrayUpdate::GetInitialVisibility() {
return Shell::GetInstance()->system_tray_delegate()->SystemShouldUpgrade();
}
views::View* TrayUpdate::CreateDefaultView(user::LoginStatus status) {
if (!Shell::GetInstance()->system_tray_delegate()->SystemShouldUpgrade())
return NULL;
return new UpdateView(severity_);
}
views::View* TrayUpdate::CreateDetailedView(user::LoginStatus status) {
return CreateDefaultView(status);
}
void TrayUpdate::DestroyDetailedView() {
if (nagger_.get()) {
// The nagger was being displayed. Now that the detailed view is being
// closed, that means either the user clicks on it to restart, or the user
// didn't click on it to restart. In either case, start the timer to show
// the nag reminder again after the specified time.
nagger_->RestartTimer();
}
}
void TrayUpdate::OnUpdateRecommended(UpdateObserver::UpdateSeverity severity) {
severity_ = severity;
SetImageFromResourceId(DecideResource(severity_, false));
tray_view()->SetVisible(true);
if (!Shell::GetPrimaryRootWindowController()->shelf()->IsVisible() &&
!nagger_.get()) {
// The shelf is not visible, and there is no nagger scheduled.
nagger_.reset(new tray::UpdateNagger(this));
}
}
} // namespace internal
} // namespace ash
|
HassanRahim26/LEETCODE
|
ARRAYS/MEDIUM/Find First and Last Position of Element in Sorted Array/Code.cpp
|
<filename>ARRAYS/MEDIUM/Find First and Last Position of Element in Sorted Array/Code.cpp
/*
PROBLEM LINK:- https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
*/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int a = BinarySearch(nums, target);
int b = BinarySearch(nums, target+1)-1;
if (a < nums.size() && nums[a] == target)
return {a, b};
else
return {-1, -1};
}
int BinarySearch(vector<int>& nums, int target)
{
int low = 0, high = nums.size()-1;
while (low <= high)
{
int mid = low + (high - low)/2;
if (nums[mid] < target)
low = mid+1;
else
high = mid-1;
}
return low;
}
};
|
SSEHUB/EASyProducer
|
Example_SPLs/Tutorial/EASyDemoTree/src/io/ssehub/easy/demo/tree/Engine.java
|
package io.ssehub.easy.demo.tree;
public class Engine {
public static final int HORSEPOWER = 0;
}
|
lakinwecker/GeometricTools
|
GTE/Mathematics/LDLTDecomposition.h
|
<gh_stars>0
// <NAME>, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Matrix.h>
#include <Mathematics/GMatrix.h>
// Factor a positive symmetric matrix A = L * D * L^T, where L is a lower
// triangular matrix with diagonal entries all 1 (L is lower unit triangular)
// and where D is a diagonal matrix with diagonal entries all positive.
namespace gte
{
template <typename T, int32_t...> class LDLTDecomposition;
template <typename T, int32_t...> class BlockLDLTDecomposition;
// Implementation for sizes known at compile time.
template <typename T, int32_t N>
class LDLTDecomposition<T, N>
{
public:
LDLTDecomposition()
{
static_assert(
N > 0,
"Invalid size.");
}
// The matrix A must be positive definite. The implementation uses
// only the lower-triangular portion of A. On output, L is lower
// unit triangular and D is diagonal.
bool Factor(Matrix<N, N, T> const& A, Matrix<N, N, T>& L, Matrix<N, N, T>& D)
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
L.MakeZero();
D.MakeZero();
for (int32_t j = 0; j < N; ++j)
{
T Djj = A(j, j);
for (int32_t k = 0; k < j; ++k)
{
T Ljk = L(j, k);
T Dkk = D(k, k);
Djj -= Ljk * Ljk * Dkk;
}
D(j, j) = Djj;
if (Djj == zero)
{
return false;
}
L(j, j) = one;
for (int32_t i = j + 1; i < N; ++i)
{
T Lij = A(i, j);
for (int32_t k = 0; k < j; ++k)
{
T Lik = L(i, k);
T Ljk = L(j, k);
T Dkk = D(k, k);
Lij -= Lik * Ljk * Dkk;
}
Lij /= Djj;
L(i, j) = Lij;
}
}
return true;
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring before the call.
void Solve(Matrix<N, N, T> const& L, Matrix<N, N, T> const& D,
Vector<N, T> const& B, Vector<N, T>& X)
{
// Solve L * Z = L * (D * L^T * X) = B for Z.
for (int32_t r = 0; r < N; ++r)
{
X[r] = B[r];
for (int32_t c = 0; c < r; ++c)
{
X[r] -= L(r, c) * X[c];
}
}
// Solve D * Y = D * (L^T * X) = Z for Y.
for (int32_t r = 0; r < N; ++r)
{
X[r] /= D(r, r);
}
// Solve L^T * Y = Z for X.
for (int32_t r = N - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < N; ++c)
{
X[r] -= L(c, r) * X[c];
}
}
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring during the call.
void Solve(Matrix<N, N, T> const& A, Vector<N, T> const& B, Vector<N, T>& X)
{
Matrix<N, N, T> L, D;
Factor(A, L, D);
Solve(L, D, B, X);
}
};
// Implementation for sizes known only at run time.
template <typename T>
class LDLTDecomposition<T>
{
public:
int32_t const N;
LDLTDecomposition(int32_t inN)
:
N(inN)
{
LogAssert(
N > 0,
"Invalid size.");
}
// The matrix A must be positive definite. The implementation uses
// only the lower-triangular portion of A. On output, L is lower
// unit triangular and D is diagonal.
bool Factor(GMatrix<T> const& A, GMatrix<T>& L, GMatrix<T>& D)
{
LogAssert(
A.GetNumRows() == N && A.GetNumCols() == N,
"Invalid size.");
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
L.SetSize(N, N);
L.MakeZero();
D.SetSize(N, N);
D.MakeZero();
for (int32_t j = 0; j < N; ++j)
{
T Djj = A(j, j);
for (int32_t k = 0; k < j; ++k)
{
T Ljk = L(j, k);
T Dkk = D(k, k);
Djj -= Ljk * Ljk * Dkk;
}
D(j, j) = Djj;
if (Djj == zero)
{
return false;
}
L(j, j) = one;
for (int32_t i = j + 1; i < N; ++i)
{
T Lij = A(i, j);
for (int32_t k = 0; k < j; ++k)
{
T Lik = L(i, k);
T Ljk = L(j, k);
T Dkk = D(k, k);
Lij -= Lik * Ljk * Dkk;
}
Lij /= Djj;
L(i, j) = Lij;
}
}
return true;
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring before the call.
void Solve(GMatrix<T> const& L, GMatrix<T> const& D,
GVector<T> const& B, GVector<T>& X)
{
LogAssert(
L.GetNumRows() == N && L.GetNumCols() == N &&
D.GetNumRows() == N && D.GetNumCols() && B.GetSize() == N,
"Invalid size.");
X.SetSize(N);
// Solve L * Z = L * (D * L^T * X) = B for Z.
for (int32_t r = 0; r < N; ++r)
{
X[r] = B[r];
for (int32_t c = 0; c < r; ++c)
{
X[r] -= L(r, c) * X[c];
}
}
// Solve D * Y = D * (L^T * X) = Z for Y.
for (int32_t r = 0; r < N; ++r)
{
X[r] /= D(r, r);
}
// Solve L^T * Y = Z for X.
for (int32_t r = N - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < N; ++c)
{
X[r] -= L(c, r) * X[c];
}
}
}
// Solve A*X = B for positive definite A = L * D * L^T.
void Solve(GMatrix<T> const& A, GVector<T> const& B, GVector<T>& X)
{
LogAssert(
A.GetNumRows() == N && A.GetNumCols() == N && B.GetSize() == N,
"Invalid size.");
GMatrix<T> L, D;
Factor(A, L, D);
Solve(L, D, B, X);
}
};
// Implementation for sizes known at compile time.
template <typename T, int32_t BlockSize, int32_t NumBlocks>
class BlockLDLTDecomposition<T, BlockSize, NumBlocks>
{
public:
// Let B represent the block size and N represent the number of
// blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an
// N-by-N matrix of blocks, each block of size B-by-B. The value
// N*B is NumDimensions.
enum
{
NumDimensions = NumBlocks * BlockSize
};
using BlockVector = std::array<Vector<BlockSize, T>, NumBlocks>;
using BlockMatrix = std::array<std::array<Matrix<BlockSize, BlockSize, T>, NumBlocks>, NumBlocks>;
BlockLDLTDecomposition()
{
static_assert(
BlockSize > 0 && NumBlocks > 0,
"Invalid size.");
}
// Treating the matrix as a 2D table of scalars with NumDimensions
// rows and NumDimensions columns, look up the correct block that
// stores the requested element and return a reference.
void Get(BlockMatrix const& M, int32_t row, int32_t col, T& value)
{
int32_t b0 = col / BlockSize;
int32_t b1 = row / BlockSize;
int32_t i0 = col - BlockSize * b0;
int32_t i1 = row - BlockSize * b1;
auto const& MBlock = M[b1][b0];
value = MBlock(i1, i0);
}
void Set(BlockMatrix& M, int32_t row, int32_t col, T const& value)
{
int32_t b0 = col / BlockSize;
int32_t b1 = row / BlockSize;
int32_t i0 = col - BlockSize * b0;
int32_t i1 = row - BlockSize * b1;
auto& MBlock = M[b1][b0];
MBlock(i1, i0) = value;
}
// Convert from a matrix to a block matrix.
void Convert(Matrix<NumDimensions, NumDimensions, T> const& M, BlockMatrix& MBlock) const
{
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize)
{
auto& current = MBlock[r][c];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
current(j, i) = M(rb + j, cb + i);
}
}
}
}
}
// Convert from a vector to a block vector.
void Convert(Vector<NumDimensions, T> const& V, BlockVector& VBlock) const
{
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
auto& current = VBlock[r];
for (int32_t j = 0; j < BlockSize; ++j)
{
current[j] = V[rb + j];
}
}
}
// Convert from a block matrix to a matrix.
void Convert(BlockMatrix const& MBlock, Matrix<NumDimensions, NumDimensions, T>& M) const
{
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize)
{
auto const& current = MBlock[r][c];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
M(rb + j, cb + i) = current(j, i);
}
}
}
}
}
// Convert from a block vector to a vector.
void Convert(BlockVector const& VBlock, Vector<NumDimensions, T>& V) const
{
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
auto const& current = VBlock[r];
for (int32_t j = 0; j < BlockSize; ++j)
{
V[rb + j] = current[j];
}
}
}
// The block matrix A must be positive definite. The implementation
// uses only the lower-triangular blocks of A. On output, the block
// matrix L is lower unit triangular (diagonal blocks are BxB identity
// matrices) and the block matrix D is diagonal (diagonal blocks are
// BxB diagonal matrices).
bool Factor(BlockMatrix const& A, BlockMatrix& L, BlockMatrix& D)
{
for (int32_t row = 0; row < NumBlocks; ++row)
{
for (int32_t col = 0; col < NumBlocks; ++col)
{
L[row][col].MakeZero();
D[row][col].MakeZero();
}
}
for (int32_t j = 0; j < NumBlocks; ++j)
{
Matrix<BlockSize, BlockSize, T> Djj = A[j][j];
for (int32_t k = 0; k < j; ++k)
{
auto const& Ljk = L[j][k];
auto const& Dkk = D[k][k];
Djj -= MultiplyABT(Ljk * Dkk, Ljk);
}
D[j][j] = Djj;
bool invertible = false;
Matrix<BlockSize, BlockSize, T> invDjj = Inverse(Djj, &invertible);
if (!invertible)
{
return false;
}
L[j][j].MakeIdentity();
for (int32_t i = j + 1; i < NumBlocks; ++i)
{
Matrix<BlockSize, BlockSize, T> Lij = A[i][j];
for (int32_t k = 0; k < j; ++k)
{
auto const& Lik = L[i][k];
auto const& Ljk = L[j][k];
auto const& Dkk = D[k][k];
Lij -= MultiplyABT(Lik * Dkk, Ljk);
}
Lij = Lij * invDjj;
L[i][j] = Lij;
}
}
return true;
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring before the call.
void Solve(BlockMatrix const& L, BlockMatrix const& D,
BlockVector const& B, BlockVector& X)
{
// Solve L * Z = L * (D * L^T * X) = B for Z.
for (int32_t r = 0; r < NumBlocks; ++r)
{
X[r] = B[r];
for (int32_t c = 0; c < r; ++c)
{
X[r] -= L[r][c] * X[c];
}
}
// Solve D * Y = D * (L^T * X) = Z for Y.
for (int32_t r = 0; r < NumBlocks; ++r)
{
X[r] = Inverse(D[r][r]) * X[r];
}
// Solve L^T * Y = Z for X.
for (int32_t r = NumBlocks - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < NumBlocks; ++c)
{
X[r] -= X[c] * L[c][r];
}
}
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring during the call.
void Solve(BlockMatrix const& A, BlockVector const& B, BlockVector& X)
{
BlockMatrix L, D;
Factor(A, L, D);
Solve(L, D, B, X);
}
};
// Implementation for sizes known only at run time.
template <typename T>
class BlockLDLTDecomposition<T>
{
public:
// Let B represent the block size and N represent the number of
// blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an
// N-by-N matrix of blocks, each block of size B-by-B and stored in
// row-major order. The value N*B is NumDimensions.
int32_t const BlockSize;
int32_t const NumBlocks;
int32_t const NumDimensions;
// The number of elements in a BlockVector object must be NumBlocks
// and each GVector element has BlockSize components.
using BlockVector = std::vector<GVector<T>>;
// The BlockMatrix is an array of NumBlocks-by-NumBlocks matrices.
// Each block matrix is stored in row-major order. The BlockMatrix
// elements themselves are stored in row-major order. The block
// matrix element M = BlockMatrix[col + NumBlocks * row] is of size
// BlockSize-by-BlockSize (in row-major order) and is in the (row,col)
// location of the full matrix of blocks.
using BlockMatrix = std::vector<GMatrix<T>>;
BlockLDLTDecomposition(int32_t blockSize, int32_t numBlocks)
:
BlockSize(blockSize),
NumBlocks(numBlocks),
NumDimensions(blockSize* numBlocks)
{
LogAssert(
blockSize > 0 && numBlocks > 0,
"Invalid size.");
}
// Treating the matrix as a 2D table of scalars with NumDimensions
// rows and NumDimensions columns, look up the correct block that
// stores the requested element and return a reference. NOTE: You
// are responsible for ensuring that M has NumBlocks-by-NumBlocks
// elements, each M[] having BlockSize-by-BlockSize elements.
void Get(BlockMatrix const& M, int32_t row, int32_t col, T& value, bool verifySize = true)
{
if (verifySize)
{
LogAssert(
M.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks),
"Invalid size.");
}
int32_t b0 = col / BlockSize;
int32_t b1 = row / BlockSize;
int32_t i0 = col - BlockSize * b0;
int32_t i1 = row - BlockSize * b1;
auto const& MBlock = M[GetIndex(b1, b0)];
if (verifySize)
{
LogAssert(
MBlock.GetNumRows() == BlockSize &&
MBlock.GetNumCols() == BlockSize,
"Invalid size.");
}
value = MBlock(i1, i0);
}
void Set(BlockMatrix& M, int32_t row, int32_t col, T const& value, bool verifySize = true)
{
if (verifySize)
{
LogAssert(
M.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks),
"Invalid size.");
}
int32_t b0 = col / BlockSize;
int32_t b1 = row / BlockSize;
int32_t i0 = col - BlockSize * b0;
int32_t i1 = row - BlockSize * b1;
auto& MBlock = M[GetIndex(b1, b0)];
if (verifySize)
{
LogAssert(
MBlock.GetNumRows() == BlockSize &&
MBlock.GetNumCols() == BlockSize,
"Invalid size.");
}
MBlock(i1, i0) = value;
}
// Convert from a matrix to a block matrix.
void Convert(GMatrix<T> const& M, BlockMatrix& MBlock, bool verifySize = true) const
{
if (verifySize)
{
LogAssert(
M.GetNumRows() == NumDimensions &&
M.GetNumCols() == NumDimensions,
"Invalid size.");
}
size_t const szNumBlocks = static_cast<size_t>(NumBlocks);
MBlock.resize(szNumBlocks * szNumBlocks);
for (int32_t r = 0, rb = 0, index = 0; r < NumBlocks; ++r, rb += BlockSize)
{
for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize, ++index)
{
auto& current = MBlock[index];
current.SetSize(BlockSize, BlockSize);
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
current(j, i) = M(rb + j, cb + i);
}
}
}
}
}
// Convert from a vector to a block vector.
void Convert(GVector<T> const& V, BlockVector& VBlock, bool verifySize = true) const
{
if (verifySize)
{
LogAssert(
V.GetSize() == NumDimensions,
"Invalid size.");
}
VBlock.resize(static_cast<size_t>(NumBlocks));
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
auto& current = VBlock[r];
current.SetSize(BlockSize);
for (int32_t j = 0; j < BlockSize; ++j)
{
current[j] = V[rb + j];
}
}
}
// Convert from a block matrix to a matrix.
void Convert(BlockMatrix const& MBlock, GMatrix<T>& M, bool verifySize = true) const
{
if (verifySize)
{
LogAssert(
MBlock.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks),
"Invalid size.");
for (auto const& current : MBlock)
{
LogAssert(
current.GetNumRows() == NumBlocks &&
current.GetNumCols() == NumBlocks,
"Invalid size.");
}
}
M.SetSize(NumDimensions, NumDimensions);
for (int32_t r = 0, rb = 0, index = 0; r < NumBlocks; ++r, rb += BlockSize)
{
for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize, ++index)
{
auto const& current = MBlock[index];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
M(rb + j, cb + i) = current(j, i);
}
}
}
}
}
// Convert from a block vector to a vector.
void Convert(BlockVector const& VBlock, GVector<T>& V, bool verifySize = true) const
{
if (verifySize)
{
LogAssert(
VBlock.size() == static_cast<size_t>(NumBlocks),
"Invalid size.");
for (auto const& current : VBlock)
{
LogAssert(
current.GetSize() == NumBlocks,
"Invalid size.");
}
}
V.SetSize(NumDimensions);
for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize)
{
auto const& current = VBlock[r];
for (int32_t j = 0; j < BlockSize; ++j)
{
V[rb + j] = current[j];
}
}
}
// The block matrix A must be positive definite. The implementation
// uses only the lower-triangular blocks of A. On output, the block
// matrix L is lower unit triangular (diagonal blocks are BxB identity
// matrices) and the block matrix D is diagonal (diagonal blocks are
// BxB diagonal matrices).
bool Factor(BlockMatrix const& A, BlockMatrix& L, BlockMatrix& D, bool verifySize = true)
{
if (verifySize)
{
size_t szNumBlocks = static_cast<size_t>(NumBlocks);
LogAssert(
A.size() == szNumBlocks * szNumBlocks,
"Invalid size.");
for (size_t i = 0; i < A.size(); ++i)
{
LogAssert(
A[i].GetNumRows() == BlockSize &&
A[i].GetNumCols() == BlockSize,
"Invalid size.");
}
}
L.resize(A.size());
D.resize(A.size());
for (size_t i = 0; i < L.size(); ++i)
{
L[i].SetSize(BlockSize, BlockSize);
L[i].MakeZero();
D[i].SetSize(BlockSize, BlockSize);
D[i].MakeZero();
}
for (int32_t j = 0; j < NumBlocks; ++j)
{
GMatrix<T> Djj = A[GetIndex(j, j)];
for (int32_t k = 0; k < j; ++k)
{
auto const& Ljk = L[GetIndex(j, k)];
auto const& Dkk = D[GetIndex(k, k)];
Djj -= MultiplyABT(Ljk * Dkk, Ljk);
}
D[GetIndex(j, j)] = Djj;
bool invertible = false;
GMatrix<T> invDjj = Inverse(Djj, &invertible);
if (!invertible)
{
return false;
}
L[GetIndex(j, j)].MakeIdentity();
for (int32_t i = j + 1; i < NumBlocks; ++i)
{
GMatrix<T> Lij = A[GetIndex(i, j)];
for (int32_t k = 0; k < j; ++k)
{
auto const& Lik = L[GetIndex(i, k)];
auto const& Ljk = L[GetIndex(j, k)];
auto const& Dkk = D[GetIndex(k, k)];
Lij -= MultiplyABT(Lik * Dkk, Ljk);
}
Lij = Lij * invDjj;
L[GetIndex(i, j)] = Lij;
}
}
return true;
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring before the call.
void Solve(BlockMatrix const& L, BlockMatrix const& D,
BlockVector const& B, BlockVector& X, bool verifySize = true)
{
if (verifySize)
{
size_t const szNumBlocks = static_cast<size_t>(NumBlocks);
size_t const LDsize = szNumBlocks * szNumBlocks;
LogAssert(
L.size() == LDsize &&
D.size() == LDsize &&
B.size() == szNumBlocks,
"Invalid size.");
for (size_t i = 0; i < L.size(); ++i)
{
LogAssert(
L[i].GetNumRows() == BlockSize &&
L[i].GetNumCols() == BlockSize &&
D[i].GetNumRows() == BlockSize &&
D[i].GetNumCols() == BlockSize,
"Invalid size.");
}
for (size_t i = 0; i < B.size(); ++i)
{
LogAssert(
B[i].GetSize() == BlockSize,
"Invalid size.");
}
}
// Solve L * Z = L * (D * L^T * X) = B for Z.
X.resize(static_cast<size_t>(NumBlocks));
for (int32_t r = 0; r < NumBlocks; ++r)
{
X[r] = B[r];
for (int32_t c = 0; c < r; ++c)
{
X[r] -= L[GetIndex(r, c)] * X[c];
}
}
// Solve D * Y = D * (L^T * X) = Z for Y.
for (int32_t r = 0; r < NumBlocks; ++r)
{
X[r] = Inverse(D[GetIndex(r, r)]) * X[r];
}
// Solve L^T * Y = Z for X.
for (int32_t r = NumBlocks - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < NumBlocks; ++c)
{
X[r] -= X[c] * L[GetIndex(c, r)];
}
}
}
// Solve A*X = B for positive definite A = L * D * L^T with
// factoring during the call.
void Solve(BlockMatrix const& A, BlockVector const& B, BlockVector& X,
bool verifySize = true)
{
if (verifySize)
{
size_t const szNumBlocks = static_cast<size_t>(NumBlocks);
LogAssert(
A.size() == szNumBlocks * szNumBlocks &&
B.size() == szNumBlocks,
"Invalid size.");
for (size_t i = 0; i < A.size(); ++i)
{
LogAssert(
A[i].GetNumRows() == BlockSize &&
A[i].GetNumCols() == BlockSize,
"Invalid size.");
}
for (size_t i = 0; i < B.size(); ++i)
{
LogAssert(
B[i].GetSize() == BlockSize,
"Invalid size.");
}
}
BlockMatrix L, D;
Factor(A, L, D, false);
Solve(L, D, B, X, false);
}
private:
// Compute the 1-dimensional index of the block matrix in a
// 2-dimensional BlockMatrix object.
inline size_t GetIndex(int32_t row, int32_t col) const
{
return static_cast<size_t>(col + row * static_cast<size_t>(NumBlocks));
}
};
}
|
aaronvincent/gambit_aaron
|
contrib/Delphes-3.1.2/display/DisplayLinkDef.h
|
/** ExRootAnalysisLinkDef
*
* Lists classes to be included in cint dicitonary
*
* $Date: 2013-04-22 22:00:46 +0200 (Mon, 22 Apr 2013) $
* $Revision: 1097 $
*
*
* \author <NAME> - UCL, Louvain-la-Neuve
*
*/
#include "display/DelphesDisplay.h"
#include "display/DelphesCaloData.h"
#ifdef __CINT__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link C++ class DelphesDisplay+;
#pragma link C++ class DelphesCaloData+;
#endif
|
WillYee/clearsilver
|
util/test/hdf_hash_test.c
|
#include "cs_config.h"
#include <unistd.h>
#include "util/neo_misc.h"
#include "util/neo_hdf.h"
#include "util/neo_rand.h"
int main(int argc, char *argv[])
{
NEOERR *err;
HDF *hdf, *h2;
err = hdf_init(&hdf);
if (err != STATUS_OK)
{
nerr_log_error(err);
return -1;
}
err = hdf_set_value(hdf, "CGI.Foo", "Bar");
if (err)
{
nerr_log_error(err);
return -1;
}
err = hdf_set_value(hdf, "CGI.Foo", "Baz");
if (err)
{
nerr_log_error(err);
return -1;
}
h2 = hdf_get_obj(hdf, "CGI");
err = hdf_set_value(h2, "Foo", "Bang");
hdf_dump(hdf, NULL);
hdf_destroy(&hdf);
return 0;
}
|
arusinha/incubator-netbeans
|
ide/extbrowser/src/org/netbeans/modules/extbrowser/UnixBrowserImpl.java
|
<filename>ide/extbrowser/src/org/netbeans/modules/extbrowser/UnixBrowserImpl.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.extbrowser;
import java.awt.EventQueue;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.awt.StatusDisplayer;
import org.openide.execution.NbProcessDescriptor;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
/**
* The UnixBrowserImpl is implementation of browser that displays content in
* external program (Netscape). It is usable on Unix platform only because it
* uses command line option specific to this environment.
* Additionally it uses some XWindow utilities to get information about
* browser windows.
*
* @author <NAME>
*/
public class UnixBrowserImpl extends ExtBrowserImpl {
/** Number of probes to get exit status of executed command.
* Status is checked after each second.
*/
protected static final int CMD_TIMEOUT = 6;
private static RequestProcessor RP = new RequestProcessor();
/** Creates modified NbProcessDescriptor that can be used to start
* browser process when <CODE>-remote openURL()</CODE> options
* cannot be used.
* @return command or <CODE>null</CODE>
* @param p Original command.
*/
protected static NbProcessDescriptor createPatchedExecutable (NbProcessDescriptor p) {
NbProcessDescriptor newP = null;
String [] args = org.openide.util.Utilities.parseParameters(p.getArguments());
if (args.length > 1) {
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Old arguments: " + p.getArguments()); // NOI18N
}
StringBuffer newArgs = new StringBuffer ();
boolean found = false;
for (int i=0; i<args.length-1; i++) {
if (newArgs.length() > 0) {
newArgs.append(" "); // NOI18N
}
if (args[i].indexOf("-remote") >= 0 // NOI18N
&& args[i+1].indexOf("openURL(") >=0) { // NOI18N
found = true;
newArgs.append("\"{URL}\""); // NOI18N
}
else {
newArgs.append("\""+args[i]+"\""); // NOI18N
}
}
if (found) {
newP = new NbProcessDescriptor (p.getProcessName(), newArgs.toString(), p.getInfo());
}
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "ProcessName: " + p.getProcessName()); // NOI18N
ExtWebBrowser.getEM().log(Level.FINE, "New arguments: " + newArgs.toString()); // NOI18N
}
}
return newP;
}
/** Creates new UnixBrowserImpl */
public UnixBrowserImpl () {
this (null);
}
/** Creates new UnixBrowserImpl
* @param extBrowserFactory Associated browser factory to get settings from.
*/
public UnixBrowserImpl (ExtWebBrowser extBrowserFactory) {
super();
this.extBrowserFactory = extBrowserFactory;
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "UnixBrowserImpl created from factory: " + extBrowserFactory); // NOI18N
}
}
/**
* Sets current URL.</P>
*
* <P>If browser is running and we know window ID we call
* <CODE>browser_command -id _winID_ -raise -remote 'openURL(_url)'</CODE>
* else we start it with
* <CODE>browser_command _url_</CODE></P>
*
* @param url URL to show in the browser.
*/
@Override
protected void loadURLInBrowserInternal(URL url) {
assert !EventQueue.isDispatchThread();
NbProcessDescriptor cmd = extBrowserFactory.getBrowserExecutable (); // NOI18N
Process p;
StatusDisplayer sd = StatusDisplayer.getDefault ();
try {
// internal protocols cannot be displayed in external viewer
url = URLUtil.createExternalURL(url, false);
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "External url: " + url); // NOI18N
}
cmd = extBrowserFactory.getBrowserExecutable (); // NOI18N
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Executable: " + cmd); // NOI18N
}
sd.setStatusText (NbBundle.getMessage (UnixBrowserImpl.class, "MSG_Running_command", cmd.getProcessName ()));
p = cmd.exec (new ExtWebBrowser.UnixBrowserFormat (url.toString ()));
RP.post (new Status (cmd, p, url), 1000);
pcs.firePropertyChange (PROP_URL, getURL(), url);
}
catch (java.io.IOException ex) {
ExtWebBrowser.getEM().log(Level.INFO, null, ex);
// occurs when executable is not found or not executable
BrowserUtils.notifyMissingBrowser(cmd.getProcessName());
}
catch (NumberFormatException ex) {
Logger.getLogger("global").log(Level.INFO, null, ex);
}
catch (java.lang.Exception ex) {
Exceptions.printStackTrace(ex);
}
}
/** Object that checks execution result
* of browser invocation request.
* <p>It can made another attempt to start the browser
* when error output contains information that communication
* through Xremote protocol failed.
*/
private class Status implements Runnable {
/** Message printed when invocation fails even though the
* application runs, but there's no browser window (only mail client, e.g.).
*/
private static final String FAILURE_MSG_BADWINDOW = "BadWindow"; // NOI18N
/** Message printed when invocation fails because the application does not run. */
private static final String FAILURE_MSG = "No running window found."; // NOI18N
/** Originally executed command. */
private NbProcessDescriptor cmd;
/** Handle to executed process. */
private Process p;
/** URL to be displayed. */
private URL url;
/** Retries counter. */
private int retries = CMD_TIMEOUT;
/** Creates Status object to check execution result
* of browser invocation request.
* @param cmd Originally executed command.
* @param p Process that is checked.
* @param url Displayed URL that can be used when another attempt
* to start the browser is made or <CODE>null</CODE>.
*/
public Status (NbProcessDescriptor cmd, Process p, URL url) {
this. cmd = cmd;
this.p = p;
this.url = url;
}
/** Checks whether process is correctly executed.
* If it returns bad exit code or prints know error message
* it is re-executed once again.
* If the execution is not finished during timeout message is displayed.
*/
public void run () {
try {
// wait for process to finish before testing exit status:
p.waitFor();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
boolean retried = false;
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Retried: " + retried); // NOI18N
}
int exitStatus = 1;
Reader r = new InputStreamReader (p.getErrorStream ());
try {
exitStatus = p.exitValue();
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Command executed. exitValue = " + exitStatus); // NOI18N
}
} catch (IllegalThreadStateException ex) {
retries--;
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Retries: " + retries); // NOI18N
ExtWebBrowser.getEM().log(Level.FINE, "Time: " + System.currentTimeMillis()); // NOI18N
}
if (retries > 0) {
RP.post(this, 1000);
return;
} else {
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Command not finished yet"); // NOI18N
}
}
}
// hack : Netscape exits with 0 on Linux even if there is no window
if (exitStatus == 0 && org.openide.util.Utilities.getOperatingSystem() == org.openide.util.Utilities.OS_LINUX) {
final int LEN = 2048;
char [] buff = new char [LEN];
int l;
StringBuffer sb = new StringBuffer ();
try {
while ((l = r.read (buff, 0, LEN)) != -1) {
sb.append (buff, 0, l);
}
if (sb.toString ().indexOf (FAILURE_MSG) >= 0) {
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Browser output: \"" + FAILURE_MSG + "\""); // NOI18N
}
exitStatus = 2;
}
} catch (java.io.IOException ioe) {
// suppose it was executed
ExtWebBrowser.getEM().log(Level.WARNING, null, ioe);
}
}
// mozilla & netscape exits with 1 on Linux if there's mail window present,
// but there's no browser window - the URL is shown correctly, though
if (exitStatus == 1 && org.openide.util.Utilities.getOperatingSystem() == org.openide.util.Utilities.OS_LINUX) {
final int LEN = 2048;
char [] buff = new char [LEN];
int l;
StringBuffer sb = new StringBuffer ();
try {
while ((l = r.read (buff, 0, LEN)) != -1) {
sb.append (buff, 0, l);
}
if (sb.toString ().indexOf (FAILURE_MSG_BADWINDOW) >= 0) {
if (ExtWebBrowser.getEM().isLoggable(Level.FINE)) {
ExtWebBrowser.getEM().log(Level.FINE, "Browser output: \"" + FAILURE_MSG_BADWINDOW + "\""); // NOI18N
}
exitStatus = 0;
}
} catch (java.io.IOException ioe) {
// suppose it was executed
ExtWebBrowser.getEM().log(Level.WARNING, null, ioe);
}
}
if (exitStatus == 2) {
try {
NbProcessDescriptor startCmd = UnixBrowserImpl.createPatchedExecutable(cmd);
if (startCmd != null) {
retried = true;
StatusDisplayer.getDefault().
setStatusText (NbBundle.getMessage (UnixBrowserImpl.class, "MSG_Running_command", startCmd.getProcessName ()));
Process pr = startCmd.exec (new ExtWebBrowser.UnixBrowserFormat (url.toString ()));
// do not care about result now
// RequestProcessor.getDefault ().post (new Status (startCmd, pr, null), 1000);
}
}
catch (java.io.IOException ioe) {
// suppose it was executed
ExtWebBrowser.getEM().log(Level.WARNING, null, ioe);
}
}
// #219040 - Running page in Chrome shows warning dialog.
// Ignore exitStatus 23 to workaround it - it is a Chrome's bug
// http://code.google.com/p/chromium/issues/detail?id=146762
if (exitStatus != 0 && !retried && exitStatus != 23) {
BrowserUtils.notifyMissingBrowser(cmd.getProcessName());
return;
}
}
}
}
|
purpen/frbird-app
|
thn/store/THNAddressManagerViewController.h
|
<filename>thn/store/THNAddressManagerViewController.h
//
// THNAddressManagerViewController.h
// store
//
// Created by XiaobinJia on 14-11-20.
// Copyright (c) 2014年 TaiHuoNiao. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum : NSUInteger {
kTHNAddressPageTypeManager,
kTHNAddressPageTypeSelect
} THNAddressPageType;
@class THNOrderViewController;
@interface THNAddressManagerViewController : UIViewController
@property (nonatomic, assign) THNAddressPageType type;
@property (nonatomic, assign) THNOrderViewController *delegate;
@end
|
drumonii/LeagueTrollBuild
|
backend/src/main/java/com/drumonii/loltrollbuild/riot/api/MapsResponse.java
|
package com.drumonii.loltrollbuild.riot.api;
import com.drumonii.loltrollbuild.model.GameMap;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Response class of a retrieval of LoL {@link GameMap}s from Riot's Data Dragon API.
* Response example:
*
* <pre>
* {
* "type": "map",
* "version": "5.24.2",
* "data": {
* "11": {
* "mapName": "SummonersRiftNew",
* "mapId": 11,
* "image": {
* "full": "map11.png",
* "sprite": "map0.png",
* "group": "map",
* "x": 144,
* "y": 0,
* "w": 48,
* "h": 48
* }
* }
* }
* }
* </pre>
*
* <b>Note</b>: Not all attributes retrieved from Riot are used.
*/
public class MapsResponse extends BaseResponse {
@JsonProperty("data")
private Map<String, GameMap> maps = new LinkedHashMap<>();
public Map<String, GameMap> getMaps() {
return maps;
}
public void setMaps(Map<String, GameMap> maps) {
this.maps = maps;
}
}
|
infinit/memo
|
src/memo/cli/Network.hh
|
<reponame>infinit/memo
#pragma once
#include <elle/das/cli.hh>
#include <elle/Duration.hh>
#include <memo/cli/Object.hh>
#include <memo/cli/Mode.hh>
#include <memo/cli/fwd.hh>
#include <memo/cli/symbols.hh>
#include <memo/symbols.hh>
namespace memo
{
using namespace std::literals;
namespace cli
{
class Network
: public Object<Network>
{
public:
using Self = Network;
Network(Memo& memo);
using Modes
= decltype(elle::meta::list(cli::create,
cli::delete_,
cli::export_,
cli::fetch,
cli::import,
#ifndef ELLE_WINDOWS
cli::inspect,
#endif
cli::link,
cli::list,
cli::unlink,
cli::list_services,
cli::list_silos,
cli::pull,
cli::push,
cli::run,
cli::stat,
cli::update));
using Strings = std::vector<std::string>;
/*---------------.
| Mode: create. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::description = boost::optional<std::string>()),
decltype(cli::silo = Strings{}),
decltype(cli::port = boost::optional<int>()),
decltype(cli::replication_factor = 1),
decltype(cli::eviction_delay = boost::optional<std::string>()),
decltype(cli::output = boost::optional<std::string>()),
decltype(cli::push_network = false),
decltype(cli::push = false),
decltype(cli::admin_r = Strings{}),
decltype(cli::admin_rw = Strings{}),
decltype(cli::peer = Strings{}),
// Consensus types.
decltype(cli::paxos = false),
decltype(cli::no_consensus = false),
// Overlay types.
decltype(cli::kelips = false),
decltype(cli::kalimero = false),
decltype(cli::kouncil = false),
// Kelips options.
decltype(cli::nodes = boost::optional<int>()),
decltype(cli::k = boost::optional<int>()),
decltype(cli::kelips_contact_timeout = elle::Duration{}),
decltype(cli::encrypt = boost::optional<std::string>()),
decltype(cli::protocol = boost::optional<std::string>()),
decltype(cli::tcp_heartbeat = elle::DurationOpt{}),
decltype(cli::disable_encrypt_at_rest = false),
decltype(cli::disable_encrypt_rpc = false),
decltype(cli::disable_signature = false)),
decltype(modes::mode_create)>
create;
void
mode_create(
std::string const& network_name,
boost::optional<std::string> const& description,
Strings const& silo,
boost::optional<int> port,
int replication_factor,
boost::optional<std::string> const& eviction_delay,
boost::optional<std::string> const& output_name,
bool push_network,
bool push,
Strings const& admin_r,
Strings const& admin_rw,
Strings const& peer,
// Consensus types.
bool paxos,
bool no_consensus,
// Overlay types.
bool kelips,
bool kalimero,
bool kouncil,
// Kelips options,
boost::optional<int> nodes,
boost::optional<int> k,
elle::Duration kelips_contact_timeout,
boost::optional<std::string> encrypt,
// Generic options
boost::optional<std::string> protocol,
elle::DurationOpt tcp_heartbeat,
bool disable_encrypt_at_rest,
bool disable_encrypt_rpc,
bool disable_signature);
/*---------------.
| Mode: delete. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::pull = false),
decltype(cli::purge = false),
decltype(cli::unlink = false)),
decltype(modes::mode_delete)>
delete_;
void
mode_delete(std::string const& network_name,
bool pull = false,
bool purge = false,
bool unlink = false);
/*---------------.
| Mode: export. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::output = boost::optional<std::string>())),
decltype(modes::mode_export)>
export_;
void
mode_export(std::string const& volume_name,
boost::optional<std::string> const& output_name = {});
/*--------------.
| Mode: fetch. |
`--------------*/
Mode<Self,
void (decltype(cli::name = boost::optional<std::string>())),
decltype(modes::mode_fetch)>
fetch;
void
mode_fetch(boost::optional<std::string> const& network_name = {});
/*---------------.
| Mode: import. |
`---------------*/
Mode<Self,
void (decltype(cli::input = boost::optional<std::string>())),
decltype(modes::mode_import)>
import;
void
mode_import(boost::optional<std::string> const& input_name = {});
/*----------------.
| Mode: inspect. |
`----------------*/
#ifndef ELLE_WINDOWS
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::output = boost::optional<std::string>()),
decltype(cli::status = false),
decltype(cli::peers = false),
decltype(cli::all = false),
decltype(cli::redundancy = false)),
decltype(modes::mode_inspect)>
inspect;
void
mode_inspect(std::string const& network_name,
boost::optional<std::string> const& output_name = {},
bool status = false,
bool peers = false,
bool all = false,
bool redundancy = false);
#endif
/*-------------.
| Mode: link. |
`-------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::silo = Strings{}),
decltype(cli::output = boost::optional<std::string>()),
decltype(cli::node_id = boost::optional<std::string>())),
decltype(modes::mode_link)>
link;
void
mode_link(std::string const& network_name,
Strings const& silos_names = {},
boost::optional<std::string> const& output_name = {},
boost::optional<std::string> const& node_id = {});
/*-------------.
| Mode: list. |
`-------------*/
Mode<Self,
void (),
decltype(modes::mode_list)>
list;
void
mode_list();
/*----------------------.
| Mode: list_services. |
`----------------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::peer = Strings()),
decltype(cli::async = false),
decltype(cli::cache = false),
decltype(cli::cache_ram_size = boost::optional<int>()),
decltype(cli::cache_ram_ttl = boost::optional<int>()),
decltype(cli::cache_ram_invalidation = boost::optional<int>()),
decltype(cli::cache_disk_size = boost::optional<uint64_t>()),
decltype(cli::fetch_endpoints = false),
decltype(cli::fetch = false),
decltype(cli::push_endpoints = false),
decltype(cli::push = false),
decltype(cli::publish = false),
decltype(cli::endpoints_file = boost::optional<std::string>()),
decltype(cli::port_file = boost::optional<std::string>()),
decltype(cli::port = boost::optional<int>()),
decltype(cli::peers_file = boost::optional<std::string>()),
decltype(cli::listen = boost::optional<std::string>()),
decltype(cli::fetch_endpoints_interval =
boost::optional<int>()),
decltype(cli::no_local_endpoints = false),
decltype(cli::no_public_endpoints = false),
decltype(cli::advertise_host = Strings())),
decltype(modes::mode_list_services)>
list_services;
void
mode_list_services(std::string const& network_name,
Strings peer = {},
bool async = false,
bool cache = false,
boost::optional<int> cache_ram_size = {},
boost::optional<int> cache_ram_ttl = {},
boost::optional<int> cache_ram_invalidation = {},
boost::optional<uint64_t> cache_disk_size = {},
bool fetch_endpoints = false,
bool fetch = false,
bool push_endpoints = false,
bool push = false,
bool publish = false,
boost::optional<std::string> const& endpoints_file = {},
boost::optional<std::string> const& port_file = {},
boost::optional<int> port = {},
boost::optional<std::string> const& peers_file = {},
boost::optional<std::string> listen = {},
boost::optional<int> fetch_endpoints_interval = {},
bool no_local_endpoints = false,
bool no_public_endpoints = false,
Strings advertise_host = {});
/*------------------.
| Mode: list_silos. |
`------------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>),
decltype(modes::mode_list_silos)>
list_silos;
void
mode_list_silos(std::string const& network_name);
/*-------------.
| Mode: pull. |
`-------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::purge = false)),
decltype(modes::mode_pull)>
pull;
void
mode_pull(std::string const& network_name,
bool purge = false);
/*-------------.
| Mode: push. |
`-------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>),
decltype(modes::mode_push)>
push;
void
mode_push(std::string const& network_name);
/*------------.
| Mode: run. |
`------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::input = boost::optional<std::string>()),
#ifndef ELLE_WINDOWS
decltype(cli::daemon = false),
decltype(cli::monitoring = true),
#endif
decltype(cli::peer = Strings{}),
decltype(cli::async = false),
decltype(cli::cache = false),
decltype(cli::cache_ram_size = boost::optional<int>()),
decltype(cli::cache_ram_ttl = boost::optional<int>()),
decltype(cli::cache_ram_invalidation = boost::optional<int>()),
decltype(cli::cache_disk_size = boost::optional<uint64_t>()),
decltype(cli::fetch_endpoints = false),
decltype(cli::fetch = false),
decltype(cli::push_endpoints = false),
decltype(cli::push = false),
decltype(cli::publish = false),
decltype(cli::endpoints_file = boost::optional<std::string>()),
decltype(cli::port_file = boost::optional<std::string>()),
decltype(cli::port = boost::optional<int>()),
decltype(cli::peers_file = boost::optional<std::string>()),
decltype(cli::listen = boost::optional<std::string>()),
decltype(cli::fetch_endpoints_interval =
boost::optional<int>()),
decltype(cli::no_local_endpoints = false),
decltype(cli::no_public_endpoints = false),
decltype(cli::advertise_host = Strings{}),
decltype(cli::grpc = boost::optional<std::string>()),
decltype(cli::grpc_port_file = boost::optional<std::string>()),
// Options that used to be hidden.
decltype(cli::paxos_rebalancing_auto_expand =
boost::optional<bool>()),
decltype(cli::paxos_rebalancing_inspect =
boost::optional<bool>()),
decltype(cli::resign_on_shutdown =
boost::optional<bool>())),
decltype(modes::mode_run)>
run;
void
mode_run(std::string const& network_name,
boost::optional<std::string> const& commands,
#ifndef ELLE_WINDOWS
bool daemon = false,
bool monitoring = true,
#endif
Strings peer = {},
bool async = false,
bool cache = false,
boost::optional<int> cache_ram_size = {},
boost::optional<int> cache_ram_ttl = {},
boost::optional<int> cache_ram_invalidation = {},
boost::optional<uint64_t> cache_disk_size = {},
bool fetch_endpoints = false,
bool fetch = false,
bool push_endpoints = false,
bool push = false,
bool publish = false,
boost::optional<std::string> const& endpoint_file = {},
boost::optional<std::string> const& port_file = {},
boost::optional<int> port = {},
boost::optional<std::string> const& peers_file = {},
boost::optional<std::string> listen = {},
boost::optional<int> fetch_endpoints_interval = {},
bool no_local_endpoints = false,
bool no_public_endpoints = false,
Strings advertise_host = {},
boost::optional<std::string> grpc = {},
boost::optional<std::string> const& grpc_port_file = {},
// Options that used to be hidden.
boost::optional<bool> paxos_rebalancing_auto_expand = {},
boost::optional<bool> paxos_rebalancing_inspect = {},
boost::optional<bool> resign_on_shutdown = {});
/*-------------.
| Mode: stat. |
`-------------*/
MODE(stat,
decltype(cli::name)::Formal<std::string const&>);
void
mode_stat(std::string const& network_name);
/*---------------.
| Mode: unlink. |
`---------------*/
MODE(unlink,
decltype(cli::name)::Formal<std::string const&>);
void
mode_unlink(std::string const& network_name);
/*---------------.
| Mode: update. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::description = boost::optional<std::string>()),
decltype(cli::port = boost::optional<int>()),
decltype(cli::output = boost::optional<std::string>()),
decltype(cli::push_network = false),
decltype(cli::push = false),
decltype(cli::admin_r = Strings{}),
decltype(cli::admin_rw = Strings{}),
decltype(cli::admin_remove = Strings{}),
decltype(cli::mountpoint = boost::optional<std::string>()),
decltype(cli::peer = Strings{}),
decltype(cli::protocol = boost::optional<std::string>())),
decltype(modes::mode_update)>
update;
void
mode_update(std::string const& network_name,
boost::optional<std::string> const& description = {},
boost::optional<int> port = {},
boost::optional<std::string> const& output_name = {},
bool push_network = false,
bool push = false,
Strings const& admin_r = Strings{},
Strings const& admin_rw = Strings{},
Strings const& admin_remove = Strings{},
boost::optional<std::string> const& mountpoint = {},
Strings const& peer = Strings{},
boost::optional<std::string> const& protocol = boost::none);
};
}
}
|
Rossterrrr/Qt
|
QtMario_Youtube-master/Mario_Updated/database.h
|
<filename>QtMario_Youtube-master/Mario_Updated/database.h
//Authors: equati0n,ka0t1k,zzDeagle545zz
#ifndef DATABASE_H
#define DATABASE_H
#include <QSql>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QDebug>
//Structures
struct Connection{
QSqlDatabase db;
bool connected;
};
//SQL Query
struct Query{
QString uName;
QString pass;
};
namespace DataB{
//*****************************************************************************
//*****************************************************************************
// SQL and Database Functions
//
//
//Registers the User if valid
bool regUsr(Query,QSqlDatabase);
//Checks to see if the username is taken
bool chkUsr(Query,QSqlDatabase);
//Checks to see if a Username and password Match in database
bool cUsrPas(Query,QSqlDatabase);
//Connects to Database
bool DBConnect(Connection);
}
#endif // DATABASE_H
|
IllayDevel/es4sql
|
src/main/java/org/illaydevel/sql4es/parse/sql/ParseResult.java
|
<filename>src/main/java/org/illaydevel/sql4es/parse/sql/ParseResult.java
package org.illaydevel.sql4es.parse.sql;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.illaydevel.sql4es.model.Heading;
import org.illaydevel.sql4es.model.OrderBy;
import org.illaydevel.sql4es.model.QuerySource;
import org.illaydevel.sql4es.model.expression.IComparison;
public class ParseResult {
private Heading heading;
private List<QuerySource> sources;
private QueryBuilder query;
private AggregationBuilder aggregation;
private IComparison having;
private List<OrderBy> sorts = new ArrayList<OrderBy>();
private int limit = -1;
private Boolean useCache = false;
private Boolean requestScore = false;
private SQLException exception;
public ParseResult(Heading heading, List<QuerySource> sources, QueryBuilder query, AggregationBuilder aggregation,
IComparison having, List<OrderBy> sorts, Integer limit, Boolean useCache, Boolean requestScore) {
super();
this.heading = heading;
this.sources = sources;
this.query = query;
this.aggregation = aggregation;
this.having = having;
if (sorts != null) this.sorts = sorts;
this.limit = limit;
this.useCache = useCache;
this.requestScore = requestScore;
}
public ParseResult(SQLException exception) {
this.exception = exception;
}
public Heading getHeading() {
return heading;
}
public List<QuerySource> getSources() {
return sources;
}
public QueryBuilder getQuery() {
return query;
}
public AggregationBuilder getAggregation() {
return aggregation;
}
public IComparison getHaving() {
return having;
}
public List<OrderBy> getSorts() {
return sorts;
}
public Integer getLimit() {
return limit;
}
public Boolean getUseCache() {
return useCache;
}
public Boolean getRequestScore() {
return requestScore;
}
public SQLException getException() {
return exception;
}
public ParseResult setHeading(Heading heading) {
this.heading = heading;
return this;
}
public ParseResult setSources(List<QuerySource> sources) {
this.sources = sources;
return this;
}
public ParseResult setQuery(QueryBuilder query) {
this.query = query;
return this;
}
public ParseResult setAggregation(AggregationBuilder aggregation) {
this.aggregation = aggregation;
return this;
}
public ParseResult setHaving(IComparison having) {
this.having = having;
return this;
}
public ParseResult setSorts(List<OrderBy> sorts) {
this.sorts = sorts;
return this;
}
public ParseResult setLimit(int limit) {
this.limit = limit;
return this;
}
public ParseResult setUseCache(Boolean useCache) {
this.useCache = useCache;
return this;
}
public ParseResult setRequestScore(Boolean requestScore) {
this.requestScore = requestScore;
return this;
}
public void setException(SQLException exception) {
this.exception = exception;
}
}
|
nhs-t10/delta-v
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/miming/FLmime.java
|
package org.firstinspires.ftc.teamcode.autonomous.miming;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.teleop.*;
import org.firstinspires.ftc.teamcode.data.*;
import org.firstinspires.ftc.teamcode.*;
import org.firstinspires.ftc.teamcode.auxillary.*;
import java.util.ArrayList;
@Autonomous(group = "Miming")
public class FLmime extends OpMode {
ArrayList<String> instructions;
MovementManager driver;
ElapsedTime timer;
ManipulationManager hands;
RobotState state;
int currentMimeIndex = 0;
boolean firstLoopRun = true;
public void init() {
instructions = (new FileSaver(FeatureManager.MIMING_FL)).readLines();
driver = new MovementManager(hardwareMap.get(DcMotor.class, "fl"),
hardwareMap.get(DcMotor.class, "fr"),
hardwareMap.get(DcMotor.class, "bl"),
hardwareMap.get(DcMotor.class, "br"));
hands = new ManipulationManager(
hardwareMap.get(Servo.class, "sev"),
hardwareMap.get(DcMotor.class, "lift"),
hardwareMap.get(Servo.class, "sideGrab"),
hardwareMap.get(Servo.class, "sideLift"),
hardwareMap.get(Servo.class, "foundationGrabber"),
hardwareMap.get(Servo.class, "dropper")
);
driver.backRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
driver.backLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
driver.frontRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
driver.frontLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
}
public void loop() {
if(firstLoopRun) timer = new ElapsedTime();
firstLoopRun = false;
currentMimeIndex = (int)Math.floor(timer.milliseconds() / FeatureManager.MIMING_MS_PER_SAMPLE);
if(currentMimeIndex < instructions.size()) {
for(int i = 0; i < 5; i++) if(instructions.get(currentMimeIndex).isEmpty()) currentMimeIndex++;
state = RobotState.fromString(instructions.get(currentMimeIndex));
driver.driveOmni(state.movement);
float[] liftPowers = new float[] {state.liftMotorPower, state.liftServoPos};
hands.setLiftState(liftPowers);
hands.setSideGrabberPosition(state.sideGrabPos);
hands.setSideLiftPosition(state.sideLiftPos);
hands.setFoundationGrabberPosition(state.foundationMoverPos);
telemetry.addData("latestThing", instructions.get(currentMimeIndex));
}
if(state != null){
telemetry.addData("LastState", state.toString());
telemetry.addData("Instructions Completed", currentMimeIndex + "/" + instructions.size());
telemetry.addData("State: ", state);
telemetry.addData("Servo Pos", hands.getServoPosition());
}
}
}
|
yu2003w/ustudy
|
exam/src/main/java/com/ustudy/exam/model/MetaMarkTask.java
|
<reponame>yu2003w/ustudy
package com.ustudy.exam.model;
import java.io.Serializable;
/**
* @author jared
*
* This class is to construct basic information for scoring task.
* The client needs more information based on the meta info.
*
*/
public class MetaMarkTask implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7849305044558352622L;
private String id = null;
private String teacid = null;
private String quesid = null;
private int threshold = 0;
private String marktype = null;
private int numOfMarkedPapers = 0;
public MetaMarkTask() {
super();
// TODO Auto-generated constructor stub
}
public MetaMarkTask(String id, String teacid, String quesid, int numOfScoredPapers, String mtype) {
super();
this.id = id;
this.teacid = teacid;
this.quesid = quesid;
this.numOfMarkedPapers = numOfScoredPapers;
this.marktype = mtype;
this.threshold = 0;
}
public MetaMarkTask(String teacid, String quesid, int threshold, String mtype) {
super();
this.teacid = teacid;
this.quesid = quesid;
this.threshold = threshold;
this.marktype = mtype;
this.numOfMarkedPapers = 0;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTeacid() {
return teacid;
}
public void setTeacid(String teacid) {
this.teacid = teacid;
}
public String getQuesid() {
return quesid;
}
public void setQuesid(String quesid) {
this.quesid = quesid;
}
public int getNumOfMarkedPapers() {
return numOfMarkedPapers;
}
public void setNumOfMarkedPapers(int numOfScoredPapers) {
this.numOfMarkedPapers = numOfScoredPapers;
}
public String getMarktype() {
return marktype;
}
public void setMarktype(String markType) {
this.marktype = markType;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
@Override
public String toString() {
return "MetaMarkTask [id=" + id + ", teacid=" + teacid + ", quesid=" + quesid + ", threshold=" + threshold
+ ", marktype=" + marktype + ", numOfMarkedPapers=" + numOfMarkedPapers + "]";
}
}
|
mchimsak/VodkaSrc
|
src/minecraft/de/Hero/clickgui/elements/menu/ElementComboBox.java
|
package de.Hero.clickgui.elements.menu;
import java.awt.Color;
import me.lc.vodka.Vodka;
import me.lc.vodka.module.impl.render.ClickGui;
import me.lc.vodka.setting.Setting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import de.Hero.clickgui.elements.Element;
import de.Hero.clickgui.elements.ModuleButton;
import de.Hero.clickgui.util.ColorUtil;
import de.Hero.clickgui.util.FontUtil;
/**
* Made by HeroCode
* it's free to use
* but you have to credit me
*
* @author HeroCode
*/
public class ElementComboBox extends Element {
/*
* Konstrukor
*/
public ElementComboBox(ModuleButton iparent, Setting iset) {
parent = iparent;
set = iset;
super.setup();
}
/*
* Rendern des Elements
*/
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
Color temp = ColorUtil.getClickGUIColor();
int color = new Color(temp.getRed(), temp.getGreen(), temp.getBlue(), 150).getRGB();
/*
* Die Box und Umrandung rendern
*/
Gui.drawRect((int)x, (int)y, (int)x + (int)width, (int)y + (int)height, 0xff1a1a1a);
FontUtil.drawTotalCenteredString(setstrg, (int)x +(int) width / 2, (int)y + 15/2, 0xffffffff);
int clr1 = color;
int clr2 = temp.getRGB();
Gui.drawRect((int)x, (int)y + 14, (int)x + (int)width, (int)y + 15, 0x77000000);
if (comboextended) {
Gui.drawRect((int)x, (int)y + 15, (int)x + (int)width, (int)y + (int)height, 0xaa121212);
double ay = y + 15;
for (String sld : set.getOptions()) {
String elementtitle = sld.substring(0, 1).toUpperCase() + sld.substring(1, sld.length());
FontUtil.drawCenteredString(elementtitle, (int)x + (int)width / 2, (int)ay + 2, 0xffffffff);
/*
* Ist das Element ausgew�hlt, wenn ja dann markiere
* das Element in der ComboBox
*/
if (sld.equalsIgnoreCase(set.getCurrentOption())) {
Gui.drawRect((int)x, (int)ay, (int)x + 1, (int)ay + FontUtil.getFontHeight() + 2, clr1);
}
/*
* Wie bei mouseClicked 'is hovered', wenn ja dann markiere
* das Element in der ComboBox
*/
if (mouseX >= x && mouseX <= x + width && mouseY >= ay && mouseY < ay + FontUtil.getFontHeight() + 2) {
Gui.drawRect((int)x + (int)width - 1, (int)ay, (int)x + (int)width, (int)ay + FontUtil.getFontHeight() + 2, clr2);
}
ay += FontUtil.getFontHeight() + 2;
}
}
}
/*
* 'true' oder 'false' bedeutet hat der Nutzer damit interagiert und
* sollen alle anderen Versuche der Interaktion abgebrochen werden?
*/
public boolean mouseClicked(int mouseX, int mouseY, int mouseButton) {
if (mouseButton == 0) {
if (isButtonHovered(mouseX, mouseY)) {
comboextended = !comboextended;
return true;
}
/*
* Also wenn die Box ausgefahren ist, dann wird f�r jede m�gliche Options
* �berpr�ft, ob die Maus auf diese zeigt, wenn ja dann global jeder weitere
* call an mouseClicked gestoppt und die Values werden aktualisiert
*/
if (!comboextended)return false;
double ay = y + 15;
for (String slcd : set.getOptions()) {
if (mouseX >= x && mouseX <= x + width && mouseY >= ay && mouseY <= ay + FontUtil.getFontHeight() + 2) {
if(ClickGui.sound.getBooleanValue())
Minecraft.getMinecraft().thePlayer.playSound("tile.piston.in", 20.0F, 20.0F);
if(clickgui != null && clickgui.setmgr != null)
set.setCurrentOption(slcd.toLowerCase());
return true;
}
ay += FontUtil.getFontHeight() + 2;
}
}
return super.mouseClicked(mouseX, mouseY, mouseButton);
}
/*
* Einfacher HoverCheck, ben�tigt damit die Combobox ge�ffnet und geschlossen werden kann
*/
public boolean isButtonHovered(int mouseX, int mouseY) {
return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + 15;
}
}
|
MaxLeiter/Cydia
|
debs/com.maxleiter.xorgproto/usr/local/include/X11/extensions/dmxproto.h
|
/*
* Copyright 2002-2004 Red Hat Inc., Durham, North Carolina.
*
* All Rights Reserved.
*
* 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 on 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 (including the
* next paragraph) 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
* NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS
* 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.
*/
/*
* Authors:
* <NAME>. (Rik) Faith <<EMAIL>>
*
*/
/** \file
* This file describes the structures necessary to implement the wire
* protocol for the DMX protocol extension. It should be included only
* in files that implement the client-side (or server-side) part of the
* protocol (i.e., client-side applications should \b not include this
* file). */
#ifndef _DMXSTR_H_
#define _DMXSTR_H_
#define DMX_EXTENSION_NAME "DMX"
#define DMX_EXTENSION_MAJOR 2
#define DMX_EXTENSION_MINOR 2
#define DMX_EXTENSION_PATCH 20040604
/* These values must be larger than LastExtensionError.
The values in dmxext.h and dmxproto.h *MUST* match. */
#define DMX_BAD_XINERAMA 1001
#define DMX_BAD_VALUE 1002
#define X_DMXQueryVersion 0
#define X_DMXGetScreenCount 1
#define X_DMXGetScreenInformationDEPRECATED 2
#define X_DMXGetWindowAttributes 3
#define X_DMXGetInputCount 4
#define X_DMXGetInputAttributes 5
#define X_DMXForceWindowCreationDEPRECATED 6
#define X_DMXReconfigureScreenDEPRECATED 7
#define X_DMXSync 8
#define X_DMXForceWindowCreation 9
#define X_DMXGetScreenAttributes 10
#define X_DMXChangeScreensAttributes 11
#define X_DMXAddScreen 12
#define X_DMXRemoveScreen 13
#define X_DMXGetDesktopAttributes 14
#define X_DMXChangeDesktopAttributes 15
#define X_DMXAddInput 16
#define X_DMXRemoveInput 17
/** Wire-level description of DMXQueryVersion protocol request. */
typedef struct {
CARD8 reqType; /* dmxcode */
CARD8 dmxReqType; /* X_DMXQueryVersion */
CARD16 length;
} xDMXQueryVersionReq;
#define sz_xDMXQueryVersionReq 4
/** Wire-level description of DMXQueryVersion protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 ununsed;
CARD16 sequenceNumber;
CARD32 length;
CARD32 majorVersion;
CARD32 minorVersion;
CARD32 patchVersion;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
} xDMXQueryVersionReply;
#define sz_xDMXQueryVersionReply 32
/** Wire-level description of DMXSync protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXSync */
CARD16 length;
} xDMXSyncReq;
#define sz_xDMXSyncReq 4
/** Wire-level description of DMXSync protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXSyncReply;
#define sz_xDMXSyncReply 32
/** Wire-level description of DMXForceWindowCreation protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXForceWindowCreation */
CARD16 length;
CARD32 window;
} xDMXForceWindowCreationReq;
#define sz_xDMXForceWindowCreationReq 8
/** Wire-level description of DMXForceWindowCreation protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXForceWindowCreationReply;
#define sz_xDMXForceWindowCreationReply 32
/** Wire-level description of DMXGetScreenCount protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetScreenCount */
CARD16 length;
} xDMXGetScreenCountReq;
#define sz_xDMXGetScreenCountReq 4
/** Wire-level description of DMXGetScreenCount protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 screenCount;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXGetScreenCountReply;
#define sz_xDMXGetScreenCountReply 32
/** Wire-level description of DMXGetScreenAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetScreenAttributes */
CARD16 length;
CARD32 physicalScreen;
} xDMXGetScreenAttributesReq;
#define sz_xDMXGetScreenAttributesReq 8
/** Wire-level description of DMXGetScreenAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 displayNameLength;
CARD32 logicalScreen;
CARD16 screenWindowWidth;
CARD16 screenWindowHeight;
INT16 screenWindowXoffset;
INT16 screenWindowYoffset;
CARD16 rootWindowWidth;
CARD16 rootWindowHeight;
INT16 rootWindowXoffset;
INT16 rootWindowYoffset;
INT16 rootWindowXorigin;
INT16 rootWindowYorigin;
} xDMXGetScreenAttributesReply;
#define sz_xDMXGetScreenAttributesReply 36
/** Wire-level description of DMXChangeScreensAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXChangeScreensAttributes */
CARD16 length;
CARD32 screenCount;
CARD32 maskCount;
} xDMXChangeScreensAttributesReq;
#define sz_xDMXChangeScreensAttributesReq 12
/** Wire-level description of DMXChangeScreensAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 errorScreen;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
} xDMXChangeScreensAttributesReply;
#define sz_xDMXChangeScreensAttributesReply 32
/** Wire-level description of DMXAddScreen protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXAddScreen */
CARD16 length;
CARD32 displayNameLength;
CARD32 physicalScreen;
CARD32 valueMask;
} xDMXAddScreenReq;
#define sz_xDMXAddScreenReq 16
/** Wire-level description of DMXAddScreen protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 physicalScreen;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
} xDMXAddScreenReply;
#define sz_xDMXAddScreenReply 32
/** Wire-level description of DMXRemoveScreen protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXRemoveScreen */
CARD16 length;
CARD32 physicalScreen;
} xDMXRemoveScreenReq;
#define sz_xDMXRemoveScreenReq 8
/** Wire-level description of DMXRemoveScreen protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXRemoveScreenReply;
#define sz_xDMXRemoveScreenReply 32
/** Wire-level description of DMXGetWindowAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetWindowAttributes */
CARD16 length;
CARD32 window;
} xDMXGetWindowAttributesReq;
#define sz_xDMXGetWindowAttributesReq 8
/** Wire-level description of DMXGetWindowAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 screenCount;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXGetWindowAttributesReply;
#define sz_xDMXGetWindowAttributesReply 32
/** Wire-level description of DMXGetDesktopAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetDesktopAttributes */
CARD16 length;
} xDMXGetDesktopAttributesReq;
#define sz_xDMXGetDesktopAttributesReq 4
/** Wire-level description of DMXGetDesktopAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
INT16 width;
INT16 height;
INT16 shiftX;
INT16 shiftY;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
} xDMXGetDesktopAttributesReply;
#define sz_xDMXGetDesktopAttributesReply 32
/** Wire-level description of DMXChangeDesktopAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXChangeDesktopAttributes */
CARD16 length;
CARD32 valueMask;
} xDMXChangeDesktopAttributesReq;
#define sz_xDMXChangeDesktopAttributesReq 8
/** Wire-level description of DMXChangeDesktopAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXChangeDesktopAttributesReply;
#define sz_xDMXChangeDesktopAttributesReply 32
/** Wire-level description of DMXGetInputCount protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetInputCount */
CARD16 length;
} xDMXGetInputCountReq;
#define sz_xDMXGetInputCountReq 4
/** Wire-level description of DMXGetInputCount protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 inputCount;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXGetInputCountReply;
#define sz_xDMXGetInputCountReply 32
/** Wire-level description of DMXGetInputAttributes protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXGetInputAttributes */
CARD16 length;
CARD32 deviceId;
} xDMXGetInputAttributesReq;
#define sz_xDMXGetInputAttributesReq 8
/** Wire-level description of DMXGetInputAttributes protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 inputType;
CARD32 physicalScreen;
CARD32 physicalId;
CARD32 nameLength;
BOOL isCore;
BOOL sendsCore;
BOOL detached;
CARD8 pad0;
CARD32 pad1;
} xDMXGetInputAttributesReply;
#define sz_xDMXGetInputAttributesReply 32
/** Wire-level description of DMXAddInput protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXAddInput */
CARD16 length;
CARD32 displayNameLength;
CARD32 valueMask;
} xDMXAddInputReq;
#define sz_xDMXAddInputReq 12
/** Wire-level description of DMXAddInput protocol reply. */
typedef struct {
BYTE type; /* X_Reply */
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 physicalId;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
} xDMXAddInputReply;
#define sz_xDMXAddInputReply 32
/** Wire-level description of DMXRemoveInput protocol request. */
typedef struct {
CARD8 reqType; /* DMXCode */
CARD8 dmxReqType; /* X_DMXRemoveInput */
CARD16 length;
CARD32 physicalId;
} xDMXRemoveInputReq;
#define sz_xDMXRemoveInputReq 8
/** Wire-level description of DMXRemoveInput protocol reply. */
typedef struct {
BYTE type;
CARD8 unused;
CARD16 sequenceNumber;
CARD32 length;
CARD32 status;
CARD32 pad0;
CARD32 pad1;
CARD32 pad2;
CARD32 pad3;
CARD32 pad4;
} xDMXRemoveInputReply;
#define sz_xDMXRemoveInputReply 32
#endif
|
psadda/pytorch_bayesian_unet
|
tests/test_mc_sampler.py
|
import numpy as np
import torch
from pytorch_bcnn.links import MCSampler
def _calc_uncertanty_from_mc_samples(samples):
mean_pred = samples.mean(dim=0, keepdims=False)
var_pred = samples.var(dim=0, keepdims=True)
return mean_pred, var_pred
def main():
mc_iteration = 10
mc_samples = np.random.rand(1, 10, 2).astype(np.float32)
mc_samples = np.repeat(mc_samples, mc_iteration, axis=0)
mc_samples = torch.Tensor(mc_samples)
_mean, _var = _calc_uncertanty_from_mc_samples(mc_samples)
print('numpy')
print(_mean)
print(_var)
print('------')
sampler = MCSampler(lambda x: x, mc_iteration, lambda x: x, None, None)
sampler.eval()
mean, var = sampler(mc_samples[0])
print('mc_sampler')
print(mean)
print(var)
print((np.abs(mean-_mean)))
print((np.abs(var-_var)))
print('------')
if __name__ == '__main__':
main()
|
lanSeFangZhou/tokenizer_tools
|
tokenizer_tools/evaluator/token/token_level.py
|
<filename>tokenizer_tools/evaluator/token/token_level.py
from tokenizer_tools.evaluator.token.base_evaluator import BaseEvaluator
class TokenEvaluator(BaseEvaluator):
def __init__(self, *args, **kwargs):
super(TokenEvaluator, self).__init__(*args, **kwargs)
def generate_word_offset_list(self, word_list):
offset_list = []
start_index = 0
for word in word_list:
end_index = start_index + len(word)
offset_list.append((start_index, end_index))
start_index = end_index
return offset_list
def process_one_batch(self, gold_data, test_data, *args, **kwargs):
gold_word_list = gold_data
test_word_list = test_data
gold_offset_list = self.generate_word_offset_list(gold_word_list)
test_offset_list = self.generate_word_offset_list(test_word_list)
common_offset = set(gold_offset_list).intersection(set(test_offset_list))
self.wc_of_correct += len(common_offset)
self.wc_of_test += len(test_offset_list)
self.wc_of_gold += len(gold_offset_list)
if __name__ == "__main__":
evaluator = TokenEvaluator()
evaluator.process_one_batch(
['我是谁', '呢呢'],
['我是', '谁', '呢呢']
)
evaluator.process_one_batch(
['我是谁', '呢呢'],
['我是', '谁', '呢呢']
)
score = evaluator.get_score()
print(score)
|
aligungr/ue-ran-sim
|
src/asn/rrc/ASN_RRC_RAN-AreaConfig.h
|
<reponame>aligungr/ue-ran-sim
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NR-RRC-Definitions"
* found in "asn/nr-rrc-15.6.0.asn1"
* `asn1c -fcompound-names -pdu=all -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D rrc`
*/
#ifndef _ASN_RRC_RAN_AreaConfig_H_
#define _ASN_RRC_RAN_AreaConfig_H_
#include <asn_application.h>
/* Including external dependencies */
#include "ASN_RRC_TrackingAreaCode.h"
#include "ASN_RRC_RAN-AreaCode.h"
#include <asn_SEQUENCE_OF.h>
#include <constr_SEQUENCE_OF.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ASN_RRC_RAN-AreaConfig */
typedef struct ASN_RRC_RAN_AreaConfig {
ASN_RRC_TrackingAreaCode_t trackingAreaCode;
struct ASN_RRC_RAN_AreaConfig__ran_AreaCodeList {
A_SEQUENCE_OF(ASN_RRC_RAN_AreaCode_t) list;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} *ran_AreaCodeList;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} ASN_RRC_RAN_AreaConfig_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_ASN_RRC_RAN_AreaConfig;
extern asn_SEQUENCE_specifics_t asn_SPC_ASN_RRC_RAN_AreaConfig_specs_1;
extern asn_TYPE_member_t asn_MBR_ASN_RRC_RAN_AreaConfig_1[2];
#ifdef __cplusplus
}
#endif
#endif /* _ASN_RRC_RAN_AreaConfig_H_ */
#include <asn_internal.h>
|
freebird-airlines/WhirlyGlobe
|
android/library/maply/src/main/cpp/WideVectorManager_jni.cpp
|
<filename>android/library/maply/src/main/cpp/WideVectorManager_jni.cpp
/*
* WideVectorManager_jni.cpp
* WhirlyGlobeLib
*
* Created by <NAME> on 3/8/17.
* Copyright 2011-2017 mousebird consulting
*
* 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 <jni.h>
#import "Maply_jni.h"
#import "com_mousebird_maply_WideVectorManager.h"
#import "WhirlyGlobe.h"
#import "WhirlyKitLog.h"
using namespace WhirlyKit;
using namespace Maply;
// Wrapper that tracks the scene as well
class WideVecManagerWrapper
{
public:
WideVecManagerWrapper(WideVectorManager *vecManager,Scene *scene)
: vecManager(vecManager), scene(scene)
{
}
WideVectorManager *vecManager;
Scene *scene;
};
typedef JavaClassInfo<WideVecManagerWrapper> WideVectorManagerWrapperClassInfo;
template<> WideVectorManagerWrapperClassInfo *WideVectorManagerWrapperClassInfo::classInfoObj = NULL;
JNIEXPORT void JNICALL Java_com_mousebird_maply_WideVectorManager_nativeInit
(JNIEnv *env, jclass cls)
{
WideVectorManagerWrapperClassInfo::getClassInfo(env,cls);
}
JNIEXPORT void JNICALL Java_com_mousebird_maply_WideVectorManager_initialise
(JNIEnv *env, jobject obj, jobject sceneObj)
{
try
{
Scene *scene = SceneClassInfo::getClassInfo()->getObject(env, sceneObj);
if (!scene)
return;
WideVectorManager *vecManager = dynamic_cast<WideVectorManager *>(scene->getManager(kWKWideVectorManager));
WideVecManagerWrapper *wrap = new WideVecManagerWrapper(vecManager,scene);
WideVectorManagerWrapperClassInfo::getClassInfo()->setHandle(env,obj,wrap);
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::initialise()");
}
}
static std::mutex disposeMutex;
JNIEXPORT void JNICALL Java_com_mousebird_maply_WideVectorManager_dispose
(JNIEnv *env, jobject obj)
{
try
{
WideVectorManagerWrapperClassInfo *classInfo = WideVectorManagerWrapperClassInfo::getClassInfo();
{
std::lock_guard<std::mutex> lock(disposeMutex);
WideVecManagerWrapper *wrap = classInfo->getObject(env,obj);
if (!wrap)
return;
classInfo->clearHandle(env,obj);
delete wrap;
}
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::dispose()");
}
}
JNIEXPORT jlong JNICALL Java_com_mousebird_maply_WideVectorManager_addVectors
(JNIEnv *env, jobject obj, jobject vecObjList, jobject vecInfoObj, jobject changeSetObj)
{
try
{
WideVectorManagerWrapperClassInfo *classInfo = WideVectorManagerWrapperClassInfo::getClassInfo();
WideVecManagerWrapper *wrap = classInfo->getObject(env,obj);
WideVectorInfo *vecInfo = WideVectorInfoClassInfo::getClassInfo()->getObject(env,vecInfoObj);
ChangeSet *changeSet = ChangeSetClassInfo::getClassInfo()->getObject(env,changeSetObj);
if (!wrap || !vecInfo || !changeSet)
return EmptyIdentity;
// Get the iterator
// Note: Look these up once
jclass listClass = env->GetObjectClass(vecObjList);
jclass iterClass = env->FindClass("java/util/Iterator");
jmethodID literMethod = env->GetMethodID(listClass,"iterator","()Ljava/util/Iterator;");
jobject liter = env->CallObjectMethod(vecObjList,literMethod);
jmethodID hasNext = env->GetMethodID(iterClass,"hasNext","()Z");
jmethodID next = env->GetMethodID(iterClass,"next","()Ljava/lang/Object;");
env->DeleteLocalRef(iterClass);
env->DeleteLocalRef(listClass);
ShapeSet shapes;
VectorObjectClassInfo *vecObjClassInfo = VectorObjectClassInfo::getClassInfo();
while (env->CallBooleanMethod(liter, hasNext))
{
jobject javaVecObj = env->CallObjectMethod(liter, next);
VectorObject *vecObj = vecObjClassInfo->getObject(env,javaVecObj);
if (vecObj != NULL)
shapes.insert(vecObj->shapes.begin(),vecObj->shapes.end());
env->DeleteLocalRef(javaVecObj);
}
env->DeleteLocalRef(liter);
// Resolve a missing program
if (vecInfo->programID == EmptyIdentity)
{
bool isGlobe = dynamic_cast<WhirlyGlobe::GlobeScene *>(wrap->scene);
vecInfo->programID = wrap->vecManager->getScene()->getProgramIDBySceneName(isGlobe ? kToolkitDefaultWideVectorGlobeProgram : kToolkitDefaultWideVectorProgram);
}
SimpleIdentity vecId = wrap->vecManager->addVectors(&shapes,*vecInfo,*changeSet);
return vecId;
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::addVectors()");
}
return EmptyIdentity;
}
JNIEXPORT void JNICALL Java_com_mousebird_maply_WideVectorManager_removeVectors
(JNIEnv *env, jobject obj, jlongArray idArrayObj, jobject changeSetObj)
{
try
{
WideVectorManagerWrapperClassInfo *classInfo = WideVectorManagerWrapperClassInfo::getClassInfo();
WideVecManagerWrapper *wrap = classInfo->getObject(env,obj);
ChangeSet *changeSet = ChangeSetClassInfo::getClassInfo()->getObject(env,changeSetObj);
if (!wrap || !changeSet)
return;
SimpleIDSet idSet;
ConvertLongArrayToSet(env,idArrayObj,idSet);
wrap->vecManager->removeVectors(idSet,*changeSet);
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::removeVectors()");
}
}
JNIEXPORT void JNICALL Java_com_mousebird_maply_WideVectorManager_enableVectors
(JNIEnv *env, jobject obj, jlongArray idArrayObj, jboolean enable, jobject changeSetObj)
{
try
{
WideVectorManagerWrapperClassInfo *classInfo = WideVectorManagerWrapperClassInfo::getClassInfo();
WideVecManagerWrapper *wrap = classInfo->getObject(env,obj);
ChangeSet *changeSet = ChangeSetClassInfo::getClassInfo()->getObject(env,changeSetObj);
if (!wrap || !changeSet)
return;
SimpleIDSet idSet;
ConvertLongArrayToSet(env,idArrayObj,idSet);
wrap->vecManager->enableVectors(idSet,enable,*changeSet);
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::enableVectors()");
}
}
JNIEXPORT jlong JNICALL Java_com_mousebird_maply_WideVectorManager_instanceVectors
(JNIEnv *env, jobject obj, jlong vecID, jobject vecInfoObj, jobject changeSetObj)
{
try
{
WideVectorManagerWrapperClassInfo *classInfo = WideVectorManagerWrapperClassInfo::getClassInfo();
WideVecManagerWrapper *wrap = classInfo->getObject(env,obj);
WideVectorInfo *vecInfo = WideVectorInfoClassInfo::getClassInfo()->getObject(env,vecInfoObj);
ChangeSet *changeSet = ChangeSetClassInfo::getClassInfo()->getObject(env,changeSetObj);
if (!wrap || !vecInfo || !changeSet)
return EmptyIdentity;
return wrap->vecManager->instanceVectors(vecID,*vecInfo,*changeSet);
}
catch (...)
{
__android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in WideVectorManager::instanceVectors()");
}
return EmptyIdentity;
}
|
MicroEJ/Demo-PartialBuffer
|
stm32f7508_freertos-bsp/projects/microej/net/src/LLNET_Common.c
|
<filename>stm32f7508_freertos-bsp/projects/microej/net/src/LLNET_Common.c
/*
* C
*
* Copyright 2016-2020 MicroEJ Corp. All rights reserved.
* This library is provided in source code for use, modification and test, subject to license terms.
* Any modification of the source code will break MicroEJ Corp. warranties on the whole library.
*/
/**
* @file
* @brief LLNET_Common implementation over BSD-like API.
* @author MicroEJ Developer Team
* @version 1.1.1
* @date 7 February 2020
*/
#include "LLNET_Common.h"
#include "async_select.h"
#include "async_select_cache.h"
#include <string.h>
#include "LLNET_CHANNEL_impl.h"
#include "LLNET_CONSTANTS.h"
#include "LLNET_ERRORS.h"
#include <sys/socket.h>
#include <stdint.h>
#if LLNET_AF & LLNET_AF_IPV6
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#endif
#ifndef USE_IOCTL_FOR_BLOCKING_OPTION
#include <fcntl.h>
#endif
/** @brief external function used to retrieve currentTime (same as MicroJvm) */
extern int64_t LLMJVM_IMPL_getCurrentTime__Z(uint8_t system);
int32_t asyncOperation(int32_t fd, SELECT_Operation operation, uint8_t retry){
int32_t timeout;
// the socket is not readable or writable.
// A blocking request is added in the dispatch event queue.
timeout = async_select_get_socket_timeout_from_cache(fd);
if (timeout == -1) {
timeout = LLNET_CHANNEL_IMPL_getOption(fd, CPNET_SO_TIMEOUT, 0);
}
//check the timeout
if(timeout < 0){
//error code
return timeout;
}
if((timeout != 0) && retry){
int64_t absolute_timeout = async_select_get_socket_absolute_timeout_from_cache(fd);
//The socket has been configured with a timeout
//AND there is no available data
//AND this is the second read (retry==true)
//THEN most likely the timeout has been reached during the first read
//BUT there is a special case where more Java threads were waiting for a notification
//on the same socket, and more Java threads were woken up by the async_select, but the
//first Java thread which ran consumed the socket event, so we can end up in this case
//without the full timeout being passed
//SO check that the timeout really passed for the socket, otherwise add a new async_select
//request with the remaining timeout
if (absolute_timeout != -1) {
int64_t current_time = LLMJVM_IMPL_getCurrentTime__Z(1);
if (current_time >= absolute_timeout) {
return J_ETIMEDOUT;
} else {
timeout = absolute_timeout - current_time;
}
} else {
return J_EUNKNOWN;
}
}
int32_t res = async_select(fd, operation, timeout, NULL);
if(res == 0){
// request added in the queue
return J_NET_NATIVE_CODE_BLOCKED_WITHOUT_RESULT;
}
// requests queue limit reached
return J_ASYNC_BLOCKING_REQUEST_QUEUE_LIMIT_REACHED;
}
/**
* @brief Fills-in the given timeval struct with the given time in milliseconds.
*
* @param[in] time_ms time in milliseconds.
* @param[in] time_timeval pointer to the timeval struct to fill-in.
*/
void time_ms_to_timeval(int64_t time_ms, struct timeval* time_timeval){
if(time_ms >= 1000){
time_timeval->tv_sec = time_ms / 1000;
time_timeval->tv_usec = (time_ms % 1000) * 1000;
}else{
time_timeval->tv_sec = 0;
time_timeval->tv_usec = time_ms * 1000;
}
}
/**
* @brief Sets the given socket in non-blocking mode or not.
*
* @param[in] fd socket file descriptor
* @param[in] non_blocking true to enable non-blocking, false to enable blocking.
*
* @return 0 on success, a negative value on error.
*/
int32_t set_socket_non_blocking(int32_t fd, bool non_blocking){
#ifdef USE_IOCTL_FOR_BLOCKING_OPTION
int32_t non_blocking_option = non_blocking==true ? 1 : 0;
int32_t res = llnet_ioctl(fd, FIONBIO, &non_blocking_option);
return res;
#else
int32_t flags = llnet_fcntl(fd, F_GETFL, 0);
if(flags == -1){
return -1;
}
if(non_blocking == true){
flags |= O_NONBLOCK;
}
else {
flags &= ~O_NONBLOCK;
}
return llnet_fcntl(fd, F_SETFL, flags);
#endif
}
/**
* @brief Checks if the given socket is in non-blocking mode or not.
*
* @param[in] fd socket file descriptor
*
* @return true if the socket is non blocking, false if the socket is blocking or an error occurs.
*/
bool is_socket_non_blocking(int32_t fd){
#ifdef USE_IOCTL_FOR_BLOCKING_OPTION
return false;
#else
int32_t flags = llnet_fcntl(fd, F_GETFL, 0);
if(flags == -1){
return false;
}
return (flags & O_NONBLOCK) != 0;
#endif
}
/**
* @brief Convert a network error code into a java error code.
*
* @param[in] err the error code returned by a BSD-like function.
*
* @return an error code defined in LLNET_ERRORS.h.
*/
int32_t map_to_java_exception(int32_t err){
switch(err){
case (EACCES):
return J_EACCES;
case (EBADF):
return J_EBADF;
case (EHOSTDOWN):
return J_EHOSTDOWN;
case (ENETDOWN):
return J_ENETDOWN;
case (ENETUNREACH):
return J_ENETUNREACH;
case (EADDRINUSE):
return J_EADDRINUSE;
case (EINVAL):
return J_EINVAL;
case (ECONNABORTED):
return J_ECONNABORTED;
case (ENOPROTOOPT):
return J_ENOPROTOOPT;
case (ENOTCONN):
return J_ENOTCONN;
case (EAFNOSUPPORT):
return J_EAFNOSUPPORT;
case (ECONNREFUSED):
return J_ECONNREFUSED;
case (EISCONN):
return J_EISCONN;
case (ECONNRESET):
return J_ECONNRESET;
case (EMSGSIZE):
return J_EMSGSIZE;
case (EPIPE):
return J_EPIPE;
case (ETIMEDOUT):
return J_ETIMEDOUT;
case (ENOBUFS):
case (ENOSPC):
case (ENOMEM):
return J_ENOMEM;
case (EHOSTUNREACH):
return J_EHOSTUNREACH;
default:
return J_EUNKNOWN;
}
}
#if LLNET_AF & LLNET_AF_IPV6
uint32_t getScopeForIp(const char *ip){
struct ifaddrs *addrs;
char ipAddress[NI_MAXHOST];
uint32_t scope = 0;
// walk over the list of all interface addresses
getifaddrs(&addrs);
for (struct ifaddrs *addr = addrs; addr; addr = addr->ifa_next) {
if (addr->ifa_addr && addr->ifa_addr->sa_family == AF_INET6) { // only interested in ipv6 ones
getnameinfo(addr->ifa_addr, sizeof(struct sockaddr_in6), ipAddress,
sizeof(ipAddress), NULL, 0, NI_NUMERICHOST);
// result actually contains the interface name, so strip it
for (int i = 0; ipAddress[i]; i++) {
if (ipAddress[i] == '%') {
ipAddress[i] = '\0';
break;
}
}
// if the ip matches, convert the interface name to a scope index
if (strcmp(ipAddress, ip) == 0) {
scope = if_nametoindex(addr->ifa_name);
break;
}
}
}
// If the scope wasn't set in the name search, set it to LLNET_IPV6_INTERFACE_NAME
if(0 == scope) {
scope = if_nametoindex(LLNET_IPV6_INTERFACE_NAME);
}
freeifaddrs(addrs);
return scope;
}
/**
* @brief Map the given IPv4 address into an IPv6 address.<p>
* <code>ipv4_addr</code> and <code>ipv6_addr</code> pointers can reference the same memory address.
*
* @param[in] ipv4_addr the IPv4 to map
* @param[out] ipv6_addr the destination IPv6
*/
void map_ipv4_into_ipv6(in_addr_t* ipv4_addr, struct in6_addr* ipv6_addr){
// Convert IPv4 into IPv6 directly in the addr array
if(*(ipv4_addr) == llnet_htonl(INADDR_ANY)){
// Use IPv6 wildcard address
*ipv6_addr = in6addr_any;
}
else {
uint8_t* ipv6_addr_u8 = (uint8_t*)ipv6_addr;
// Destination offset of the IPv4 address: end of struct in6_addr
int ipv4_dest_offset = sizeof(struct in6_addr) - sizeof(in_addr_t);
// Copy the IPv4 address at the end of struct in6_addr
memcpy(ipv6_addr_u8 + ipv4_dest_offset, ipv4_addr, sizeof(in_addr_t));
// Add 0xFF:0xFF before
ipv6_addr_u8[ipv4_dest_offset - 1] = 0xFF;
ipv6_addr_u8[ipv4_dest_offset - 2] = 0xFF;
// Set to 0 all the other bytes
memset(ipv6_addr_u8, 0, ipv4_dest_offset - 2);
}
}
#endif
|
Archive-42/a-whole-bunch-o-gatsby-templates
|
gatsby-plugin-preconnect/test-projects/base-configuration-test/cypress/integration/remove-duplicates.unit.spec.js
|
<filename>gatsby-plugin-preconnect/test-projects/base-configuration-test/cypress/integration/remove-duplicates.unit.spec.js<gh_stars>1-10
/// <reference types="Cypress" />
import { removeDuplicates } from ".../../../src/utils"
context("removeDuplicates", () => {
context("When invoked", () => {
context("And an array of one option is passed", () => {
it("Then it returns an equal array", () => {
const domainsObj = [{ domain: "http://foo.com" }]
const result = removeDuplicates(domainsObj)
const expectedResult = [{ domain: "http://foo.com" }]
expect(result).to.deep.equal(expectedResult)
})
})
context("And an array of domains with no duplicates is passed", () => {
it("Then it returns an equal array", () => {
const domainsObj = [
{ domain: "http://foo.com" },
{ domain: "http://bar.com" },
]
const result = removeDuplicates(domainsObj)
const expectedResult = [
{ domain: "http://foo.com" },
{ domain: "http://bar.com" },
]
expect(result).to.deep.equal(expectedResult)
})
})
context("And an array of domains with duplicates is passed", () => {
it("Then it returns an array without the duplicated option", () => {
const domainsObj = [
{ domain: "http://foo.com" },
{ domain: "http://bar.com" },
{ domain: "http://foo.com" },
]
const result = removeDuplicates(domainsObj)
const expectedResult = [
{ domain: "http://foo.com" },
{ domain: "http://bar.com" },
]
expect(result).to.deep.equal(expectedResult)
})
})
context(
"And an array of domains with different crossOrigin options",
() => {
it("Then it returns an array without the duplicated options", () => {
const domainsObj = [
{ domain: "http://foo.com" },
{ domain: "http://foo.com", crossOrigin: true },
{ domain: "http://foo.com", crossOrigin: false },
{ domain: "http://foo.com", crossOrigin: "anonymous" },
{ domain: "http://foo.com", crossOrigin: "use-credentials" },
{ domain: "http://bar.com" },
{ domain: "http://bar.com", crossOrigin: true },
{ domain: "http://bar.com", crossOrigin: false },
{ domain: "http://bar.com", crossOrigin: "anonymous" },
{ domain: "http://bar.com", crossOrigin: "use-credentials" },
]
const domainsObjWithDuplicates = [...domainsObj, ...domainsObj]
const result = removeDuplicates(domainsObjWithDuplicates)
const expectedResult = domainsObj
expect(result).to.deep.equal(expectedResult)
})
}
)
})
})
|
MC-JY/tika
|
tika-core/src/main/java/org/apache/tika/mime/MinShouldMatchClause.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tika.mime;
import java.util.List;
class MinShouldMatchClause implements Clause {
private final int min;
private final List<Clause> clauses;
/**
* Minimum number of clauses that need to match.
* <p>
* Throws IllegalArgumentException if min <= 0,
* if clauses is null or has size == 0, or if min > clauses.size()
*
* @param min
* @param clauses
*/
MinShouldMatchClause(int min, List<Clause> clauses) {
if (clauses == null || clauses.size() == 0) {
throw new IllegalArgumentException("clauses must be not null with size > 0");
}
if (min > clauses.size()) {
throw new IllegalArgumentException(
"min (" + min + ") cannot be > clauses.size (" + clauses.size() + ")");
} else if (min <= 0) {
throw new IllegalArgumentException("min cannot be <= 0: " + min);
}
this.min = min;
this.clauses = clauses;
}
public boolean eval(byte[] data) {
int matches = 0;
for (Clause clause : clauses) {
if (clause.eval(data)) {
if (++matches >= min) {
return true;
}
}
}
return false;
}
public int size() {
int size = 0;
for (Clause clause : clauses) {
size = Math.max(size, clause.size());
}
return size;
}
public String toString() {
return "minShouldMatch (min: " + min + ") " + clauses;
}
}
|
tranek/coh2_rgt_extractor
|
coh2_rgt_extractor/Rainman_src/CRgdFile.h
|
/*
Rainman Library
Copyright (C) 2006 Corsix <<EMAIL>>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _C_RGD_FILE_H_
#define _C_RGD_FILE_H_
#include "gnuc_defines.h"
#include <vector>
#include "IFileStore.h"
#include "IMetaTable.h"
#include "CRgdHashTable.h"
#include "CLuaFile.h"
#include "Api.h"
class RAINMAN_API CRgdFile : public IMetaNode
{
public:
static const int sk_TableInt = 101;
struct _RgdEntry;
union _RgdEntryData
{
float f;
unsigned long i;
char* s;
bool b;
wchar_t* ws;
std::vector<_RgdEntry*>* t;
};
struct _RgdEntry
{
CRgdFile* pParentFile;
unsigned long iHash;
const char* sName;
eDataTypes Type;
_RgdEntryData Data;
_RgdEntry* pExt;
};
static bool _SortOutEntries(_RgdEntry* a, _RgdEntry* b);
static bool _SortOutEntriesNum(_RgdEntry* a, _RgdEntry* b);
public:
CRgdFile(void);
virtual ~CRgdFile(void);
/*
enum eValues
{
// Errors
E_NoStream = 0, // No stream was passed into the function
E_MemoryAllocateError, // Couldn't allocate enough memory
E_ReadError, // Could not read data from stream
E_WriteError, // Could not write data to stream
E_NoData, // No DATAAEGD segment found
E_MemoryReadError, // Couldn't read from memory
E_SyntaxError, // Couldn't process binary data into a table
E_InvalidDataType = 15, // Invalid LUA data type
// Warnings (Can continue but may not work)
E_UnrecognisedHeader = 7, // The RGD file had an unrecognised header
E_InvalidCRC, // The CRC doesn't match
// No Errors
E_OK, // Everything went fine
//Other
E_UnknownError // Um, OMGWTFHAX?!?
};
*/
void New(long iVersion = 1);
void Load(IFileStore::IStream *pStream);
void Load(CLuaFile *pLuaFile, long iVersion = 1);
/*!
\todo check DT_NoData and DT_WString references
*/
void Save(IFileStore::IOutputStream *pStream);
//! Creates a lua_State from the RGD state.
/*!
Use MakeLuaFromRgdAndNil() or MakeLuaFromRgdQuickly() to make LUA
files from an RGD. Use this to make a LUA state which can then be
used to run scripts over.
*/
lua_State* CreateLuaState();
CRgdHashTable* GetHashTable();
void SetHashTable(CRgdHashTable *pTable);
// These only manipulate the (first) DATAAEGD chunk (hopefully, RGDs only _need_ that chunk)
const char* GetDescriptorString();
void SetDescriptorString(const char* sString);
long GetChunkVersion();
void SetChunkVersion(long iVersion);
// All node types
virtual eDataTypes VGetType();
virtual const char* VGetName();
// Floats, Bools, Strings , WStrings
virtual float VGetValueFloat();
virtual unsigned long VGetValueInteger();
virtual bool VGetValueBool();
virtual const char* VGetValueString();
virtual const wchar_t* VGetValueWString();
virtual IMetaTable* VGetValueMetatable();
// Set
virtual void VSetType(eDataTypes eType);
virtual void VSetName(const char* sName);
virtual void VSetNameHash(long iHash);
virtual void VSetValueFloat(float fValue);
virtual void VSetValueInteger(unsigned long iValue);
virtual void VSetValueBool(bool bValue);
virtual void VSetValueString(const char* sValue);
virtual void VSetValueWString(const wchar_t* wsValue);
virtual CMemoryStore::COutStream* VGetNodeAsRainmanRgd();
virtual void SGetNodeFromRainmanRgd(IFileStore::IStream* pInput, bool bSetName = false);
class CMetaTable;
class RAINMAN_API CMetaNode : public IMetaNode
{
protected:
friend class CRgdFile;
friend class CMetaTable;
CMetaNode(_RgdEntry* pData);
_RgdEntry* m_pData;
public:
virtual ~CMetaNode();
virtual eDataTypes VGetType();
virtual const char* VGetName();
virtual unsigned long VGetNameHash();
// Floats, Bools, Strings , WStrings
virtual float VGetValueFloat();
virtual unsigned long VGetValueInteger();
virtual bool VGetValueBool();
virtual const char* VGetValueString();
virtual const wchar_t* VGetValueWString();
virtual IMetaNode::IMetaTable* VGetValueMetatable();
// Set
virtual void VSetType(eDataTypes eType);
virtual void VSetName(const char* sName);
virtual void VSetNameHash(unsigned long iHash);
virtual void VSetValueFloat(float fValue);
virtual void VSetValueInteger(unsigned long iValue);
virtual void VSetValueBool(bool bValue);
virtual void VSetValueString(const char* sValue);
virtual void VSetValueWString(const wchar_t* wsValue);
virtual CMemoryStore::COutStream* VGetNodeAsRainmanRgd();
virtual void SGetNodeFromRainmanRgd(IFileStore::IStream* pInput, bool bSetName = false);
};
class RAINMAN_API CMetaTable : public IMetaNode::IMetaTable
{
protected:
friend class CMetaNode;
friend class CRgdFile;
CMetaTable(_RgdEntry* pData);
_RgdEntry* m_pData;
std::vector<_RgdEntry*> m_vecChildren;
public:
virtual ~CMetaTable();
virtual unsigned long VGetChildCount();
virtual IMetaNode* VGetChild(unsigned long iIndex);
virtual IMetaNode::eDataTypes VGetReferenceType();
virtual const char* VGetReferenceString();
virtual const wchar_t* VGetReferenceWString();
// Set
virtual void VSetReferenceType(IMetaNode::eDataTypes eType);
virtual void VSetReferenceString(const char* sValue);
virtual void VSetReferenceWString(const wchar_t* wsValue);
virtual IMetaNode* VAddChild(const char* sName);
virtual void VDeleteChild(unsigned long iIndex);
};
static void _CleanRgdTable(_RgdEntry *pTable); // Erases the RGD table from memory
protected:
friend class CMetaNode;
friend class CMetaTable;
friend class CRgdFileMacro;
struct _RgdHeader // aka. Chunky header?
{
char *sHeader; // 16 bytes "Relic Chunky\x0D\x0A\x1A\x00"
long iVersion; // 1 - is the same in all (is 3 in CoH)
long iUnknown3; // 1 - is the same in all
// v3 only:
long iUnknown4;
long iUnknown5;
long iUnknown6;
};
struct _RgdChunk
{
char *sChunkyType; // 8 bytes "DATAAEGD"
long iVersion; // CoH = 1. DoW = ?
long iChunkLength; // iStringLength + sizeof(iCRC) + sizeof(iDataLength) + iDataLength
long iStringLength;
char* sString; // variable length
// these two only in v3 chunky
unsigned long iUnknown1;
unsigned long iUnknown2;
unsigned long iCRC; // CRC32 of pData
long iDataLength;
char* pData;
_RgdEntry RootEntry;
};
_RgdHeader m_RgdHeader;
std::vector<_RgdChunk*> m_vRgdChunks;
_RgdChunk* m_pDataChunk;
CRgdHashTable* m_pHashTable;
bool m_bConvertTableIntToTable;
void _Clean(); // Erases the currently loaded RGD file from memory
/*!
Sets the top of the lus_State's stack to the specified table
*/
static void _RgdTableToLuaState(lua_State* L, _RgdEntry *pTable);
void _ProcessRawRgdData(IFileStore::IStream *pStream, _RgdEntry *pDestination);
void _WriteRawRgdData(IFileStore::IOutputStream *pStream, _RgdEntry *pSource, bool bTable101 = false);
friend bool _SortCMetaTableChildren(CRgdFile::_RgdEntry* p1, CRgdFile::_RgdEntry* p2);
void _LoadLua(lua_State* L, _RgdEntry* pDest, bool bSkipThisLevelRef = false);
static void _WriteRainmanRgdData(CMemoryStore::COutStream* pOutput, _RgdEntry* pSource);
static void _ReadRainmanRgdData(IFileStore::IStream* pInput, _RgdEntry* pDestination, bool bSetName);
};
#endif
|
GiGainfosystems/geoplasma-ce
|
frontend/src/actions/pages.js
|
import config from '../config';
import { dataRequest, dataRequestError, formRequestFinished, formRequest, formRequestSuccess, formRequestError } from './fetching'
import { LOAD_PAGES_SUCCESS } from './types'
/**
* Get all pages that are present on the web portal
*/
export function getPages() {
return (dispatch) => {
dispatch(dataRequest('getpages', true));
fetch(config.apiBaseUrl+'api/pages', {
mode: 'cors'
})
.then((response) => {
if (!response.ok) {
dispatch(dataRequestError('getpages', false));
}
dispatch(formRequestFinished());
return response;
})
.then((response) => response.json())
.then((data) => {
dispatch(loadPagesSuccess(data))
})
};
}
/**
* Loaded the pages successfully
*
* @param {} pages - The pages of the web portal
*/
export const loadPagesSuccess = (pages) => {
return {
type: LOAD_PAGES_SUCCESS,
pages
}
}
/**
* Save a page to the web portal
*
* @param {} id - If a page is edited, the according ID of the page
* @param {} title - Title of the page
* @param {} title_de
* @param {} title_cs
* @param {} title_pl
* @param {} title_sk
* @param {} title_sl
* @param {} navigation - Placement of the link to the page on the web portal (Top navi, Footer)
* @param {} url - URL of the new page
* @param {} token - JWT token
*/
export function savePage(id, title, title_de, title_cs, title_pl, title_sk, title_sl, navigation, url, token) {
return (dispatch) => {
dispatch(formRequest('savepage', true));
fetch(config.apiBaseUrl+'api/superuser/page/edit?token='+token, {
mode: 'cors',
method: 'POST',
body: JSON.stringify({id, title, title_de, title_cs, title_pl, title_sk, title_sl, navigation, url})
})
.then((response) => {
if (!response.ok) {
dispatch(formRequestError('savepage', false));
}
dispatch(formRequestFinished());
return response;
})
.then((response) => response.json())
.then((entries) => {
dispatch(formRequestSuccess({ form: 'savepage', status: true}));
dispatch(loadPagesSuccess(entries))
})
};
}
/**
* Remove a page from the web portal
*
* @param {} id - ID of the page that should be removed
* @param {} token - JWT token
*/
export function removePage(id, token) {
return (dispatch) => {
dispatch(formRequest('removepage', true));
fetch(config.apiBaseUrl+'api/superuser/page/delete?token='+token, {
mode: 'cors',
method: 'POST',
body: JSON.stringify({id})
})
.then((response) => {
if (!response.ok) {
dispatch(formRequestError('removepage', false));
}
dispatch(formRequestFinished());
return response;
})
.then((response) => response.json())
.then((entries) => {
dispatch(formRequestSuccess({ form: 'removepage', status: true}));
dispatch(loadPagesSuccess(entries))
})
};
}
|
dappstore123/wallet-core
|
src/NULS/TransactionBuilder.h
|
// Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#pragma once
#include "../proto/NULS.pb.h"
#include <algorithm>
namespace TW::NULS {
struct TransactionBuilder {
/// Plans a transaction by selecting UTXOs and calculating fees.
static Proto::TransactionPlan plan(const NULS::Proto::TransactionPurpose& purpose) {
if (purpose.utxos_size() == 0) {
return Proto::TransactionPlan{};
}
if (purpose.use_max_amount()) {
return calculatorMaxAmountPlan(purpose);
}
if (purpose.amount() == 0) {
return Proto::TransactionPlan{};
}
// set common field first
auto plan = Proto::TransactionPlan();
plan.set_amount(purpose.amount());
plan.set_timestamp(purpose.timestamp());
plan.set_private_key(purpose.private_key());
plan.set_from_address(purpose.from_address());
plan.set_to_address(purpose.to_address());
plan.set_remark(purpose.remark());
// Calculate all UTXO available amount
uint64_t availableAmount = 0;
for (auto& utxo : purpose.utxos()) {
availableAmount += utxo.amount();
}
plan.set_available_amount(availableAmount);
// all UTXO available amount less that transfer amount, error
if (!purpose.use_max_amount() && availableAmount < plan.amount()) {
return Proto::TransactionPlan{};
}
Proto::TransactionOutput output;
output.set_amount(purpose.amount());
output.set_to_address(purpose.to_address());
output.set_index(0);
output.set_lock_time(0);
std::vector<Proto::TransactionOutput> outputs;
outputs.push_back(output);
auto sortedUtxos = purpose.utxos();
std::sort(sortedUtxos.begin(), sortedUtxos.end(),
[](const Proto::TransactionInput& lhs, const Proto::TransactionInput& rhs) {
return lhs.amount() > rhs.amount();
});
std::vector<Proto::TransactionInput> selectUtxos;
int64_t values = 0;
int64_t fee = 0;
for (auto utxo : sortedUtxos) {
selectUtxos.push_back(utxo);
values += utxo.amount();
// We need recalculate transaction fee when we insert an new utxo record
uint32_t txSize =
calculatorTransactionSize(static_cast<uint32_t>(selectUtxos.size()), 1, static_cast<uint32_t>(purpose.remark().size()));
fee = calculatorTransactionFee(txSize);
if (values == (purpose.amount() + fee)) {
// selected uxto amount equal spent and fee.
break;
} else if (values > (purpose.amount() + fee)) {
// all amount bigger that spent and fee, need change back
txSize = calculatorTransactionSize(static_cast<uint32_t>(selectUtxos.size()), 2, static_cast<uint32_t>(purpose.remark().size()));
fee = calculatorTransactionFee(txSize);
if (values < (purpose.amount() + fee)) {
// don't have enough input amount because change back output
continue;
}
Proto::TransactionOutput changeOutput;
changeOutput.set_amount(values - purpose.amount() - fee);
changeOutput.set_to_address(purpose.from_address());
changeOutput.set_index(1);
changeOutput.set_lock_time(0);
outputs.push_back(changeOutput);
break;
} else {
if (txSize > MAX_TRANSACTION_SIZE) {
// Can't execute purpose transaction because transaction size limit
return Proto::TransactionPlan{};
}
}
}
plan.set_fee(fee);
plan.set_change(values - purpose.amount() - fee);
*plan.mutable_inputs() = {selectUtxos.begin(), selectUtxos.end()};
*plan.mutable_outputs() = {outputs.begin(), outputs.end()};
return plan;
}
static Proto::TransactionPlan
calculatorMaxAmountPlan(const NULS::Proto::TransactionPurpose& purpose) {
auto plan = Proto::TransactionPlan();
uint32_t maxInputs = calculatorMaxInput(static_cast<uint32_t>(purpose.remark().size()));
uint32_t selectCount = std::min((uint32_t)purpose.utxos_size(), maxInputs);
auto sortedUtxos = purpose.utxos();
std::sort(sortedUtxos.begin(), sortedUtxos.end(),
[](const Proto::TransactionInput& lhs, const Proto::TransactionInput& rhs) {
return lhs.amount() > rhs.amount();
});
std::vector<Proto::TransactionInput> selectUtxos;
uint64_t newAmount = 0;
for (int i = 0; i < selectCount; ++i) {
auto utxo = sortedUtxos[i];
newAmount += utxo.amount();
selectUtxos.push_back(utxo);
}
uint32_t txSize = calculatorTransactionSize(selectCount, 1, static_cast<uint32_t>(purpose.remark().size()));
uint64_t fee = calculatorTransactionFee(txSize);
if (newAmount < fee) {
return Proto::TransactionPlan{};
}
plan.set_available_amount(newAmount);
plan.set_amount(newAmount - fee);
plan.set_fee(fee);
plan.set_change(0L);
Proto::TransactionOutput output;
output.set_amount(plan.amount());
output.set_to_address(purpose.to_address());
output.set_index(0);
output.set_lock_time(0);
std::vector<Proto::TransactionOutput> outputs;
outputs.push_back(output);
*plan.mutable_inputs() = {selectUtxos.begin(), selectUtxos.end()};
*plan.mutable_outputs() = {outputs.begin(), outputs.end()};
return plan;
}
static int32_t calculatorMaxInput(uint32_t remarkSize) {
uint32_t outputSize = 1 * TRANSACTION_OUTPUT_SIZE;
uint32_t maxInputs =
(MAX_TRANSACTION_SIZE - TRANSACTION_HEAD_SIZE - remarkSize - outputSize) / 50;
if ((MAX_TRANSACTION_SIZE - TRANSACTION_HEAD_SIZE - remarkSize - outputSize) % 50 != 0) {
maxInputs -= 1;
}
return maxInputs;
}
static uint32_t calculatorTransactionSize(uint32_t inputCount, uint32_t outputCount,
uint32_t remarkSize) {
uint32_t size = 124 + TRANSACTION_INPUT_SIZE * inputCount +
TRANSACTION_OUTPUT_SIZE * outputCount + remarkSize;
return size;
}
static const uint16_t TRANSACTION_HEAD_SIZE = 124;
static const uint16_t TRANSACTION_INPUT_SIZE = 50;
static const uint16_t TRANSACTION_OUTPUT_SIZE = 38;
/// Transaction size must less that 300KB
static const uint64_t MAX_TRANSACTION_SIZE = 300 * 1024;
/// 0.001 NULS per KB
static const uint64_t MIN_PRICE_PRE_1024_BYTES = 100000;
static inline uint64_t calculatorTransactionFee(uint64_t size) {
uint64_t fee = (size / 1024) * MIN_PRICE_PRE_1024_BYTES;
if (size % 1024 > 0) {
fee += MIN_PRICE_PRE_1024_BYTES;
}
return fee;
}
};
} // namespace TW::NULS
|
shwezinoo/python-excercises
|
ex23.py
|
print "Let's practice everything"
print 'Your\'d need to know \'about escapes with \\that do \n newlines and \t tabs.'
poem="""
\t The lovely world
with logic so firmly planted
cannot doscern \n the needs of love
nor comprehend passion from intution
and requires an explanation
\n\t where there is none.
"""
print "-----------------"
print poem
print "--------------------"
five=10-2+3-6
print "This should be five:%s"%five
def secret_formula(started):
jelly_beans=started*500
jars=jelly_beans/1000
crates=jars/100
return jelly_beans,jars,crates
start_point=10000
beans,jars,crates=secret_formula(start_point)
print "With a starting point of :%d"%start_point
print "We'd have %d beans,%d jars,and%d crates."%(beans,jars,crates)
start_point=start_point/10
print "We can also do that this way"
print "We'd have %d beans,%d jars,and %d crates."%secret_formula(start_point)
|
ExtendJ/Regression-Tests
|
tests/enum/constructor_04f/Test.java
|
// Enum constructors can not be protected
// .result=COMPILE_FAIL
enum E {
;
int i;
protected E() {
i = 3;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.