max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
321 | <reponame>sitedata/imgmin
/* ex: set ts=4 et: */
/*
* IMGMIN Apache2 Module
*
* Author: <NAME> <<EMAIL>>
* http://github.com/rflynn
*/
#include "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_general.h"
#include "util_filter.h"
#include "apr_buckets.h"
#include "apr_md5.h"
#include "http_request.h"
#define APR_WANT_STRFUNC
#include "apr_want.h"
/* mkdir */
#include <sys/stat.h>
#include <sys/types.h>
#include "imgmin.h"
module AP_MODULE_DECLARE_DATA imgmin_module;
/* per-... ? */
typedef struct {
struct imgmin_options opt;
apr_size_t bufferSize;
char cache_dir[PATH_MAX];
} imgmin_filter_config;
/*
* default/min/max config settings
* see 'imgmin_filter_cmds' at the bottom of the file for the keys to override this in httpd.conf
*/
#define CACHE_DIR_DEFAULT "/var/imgmin-cache"
#define BUFFERSIZE_DEFAULT (1024 * 1024 * 4)
#define BUFFERSIZE_MIN (1024 * 256) /* anything less than this is stupid */
static void *create_imgmin_server_config(apr_pool_t *p, server_rec *s)
{
imgmin_filter_config *c = apr_pcalloc(p, sizeof *c);
(void) imgmin_options_init(&c->opt);
c->bufferSize = BUFFERSIZE_DEFAULT;
strcpy(c->cache_dir, CACHE_DIR_DEFAULT);
/* intialize ImageMagick */
MagickWandGenesis();
return c;
}
static const char *imgmin_set_error_threshold(cmd_parms *cmd,
void *dummy,
const char *arg)
{
imgmin_filter_config *c = ap_get_module_config(
cmd->server->module_config,
&imgmin_module);
imgmin_opt_set_error_threshold(&c->opt, arg);
return NULL;
}
static const char *imgmin_set_cache_dir(cmd_parms *cmd,
void *dummy,
const char *arg)
{
imgmin_filter_config *c = ap_get_module_config(
cmd->server->module_config,
&imgmin_module);
if (strlen(arg) >= sizeof c->cache_dir)
{
fprintf(stderr, "Cache Dir length > %lu! '%s'\n",
(unsigned long)sizeof c->cache_dir, arg);
} else {
strcpy(c->cache_dir, arg);
}
return NULL;
}
static const char *imgmin_set_buffer_size(cmd_parms *cmd,
void *dummy,
const char *arg)
{
imgmin_filter_config *c = ap_get_module_config(
cmd->server->module_config,
&imgmin_module);
apr_int64_t n = apr_strtoi64(arg, NULL, 10);
if (errno == ERANGE) {
fprintf(stderr, "Invalid bufferSize: %lu\n", (unsigned long)n);
} else if (n < 64 * 1024) {
fprintf(stderr, "bufferSize too small: %lu\n", (unsigned long)n);
} else {
c->bufferSize = n;
}
return NULL;
}
typedef struct imgmin_ctx_t
{
apr_bucket_brigade *bb;
unsigned char *buffer;
apr_size_t buflen;
} imgmin_ctx;
static apr_status_t imgmin_ctx_cleanup(void *data)
{
return APR_SUCCESS;
}
static void magickfree(void *data)
{
(void) MagickRelinquishMemory(data);
}
static char * cache_path(unsigned char *blob, size_t len, char path[PATH_MAX], const char *prefix)
{
unsigned char digest[APR_MD5_DIGESTSIZE];
char *result = NULL;
if (apr_md5(digest, blob, len) == APR_SUCCESS)
{
int fmt;
fmt = snprintf(path, PATH_MAX,
"%s/%02x/%02x/%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
prefix,
digest[0], digest[1], digest[2], digest[3],
digest[4], digest[5], digest[6], digest[7],
digest[8], digest[9], digest[10], digest[11],
digest[12], digest[13], digest[14], digest[15]);
if (fmt >= 0 && (size_t)fmt < PATH_MAX)
{
result = path;
}
}
return result;
}
static int mkdir_n(const char path[PATH_MAX], size_t len)
{
char tmppath[PATH_MAX];
strcpy(tmppath, path);
tmppath[len] = '\0';
fprintf(stderr, "mkdir(%s)\n", tmppath);
if (mkdir(tmppath, 0755) != 0)
{
if (errno != EEXIST)
{
perror("mkdir");
}
return 0;
}
return 1;
}
/*
* given a path of prefix/XX/YY/ZZZZZZZZZZZZZZZ
* ensure that prefix/XX/YY exists
*/
static void cache_path_ensure(const char *prefix, const char path[PATH_MAX])
{
size_t prelen = strlen(prefix);
(void) mkdir_n(path, prelen+3);
(void) mkdir_n(path, prelen+3+3);
}
static void cache_set(const char *prefix, const char *path, unsigned char *blob, size_t len)
{
FILE *fd;
cache_path_ensure(prefix, path);
fd = fopen(path, "wb");
if (!fd)
{
perror("fopen");
} else {
if (fwrite(blob, 1, len, fd) != len)
{
/* write to an error log...? */
perror("fwrite");
}
fclose(fd);
}
}
/*
* given an image in a buffer, attempt to locate and retrieve it in our cache.
* upon error or the file not being found return NULL
*/
static MagickWand * cache_get(const char *path, imgmin_ctx *ctx)
{
MagickWand *cached = NULL;
FILE *fd;
fd = fopen(path, "rb");
if (fd)
{
cached = NewMagickWand();
if (cached)
{
if (MagickTrue != MagickReadImageFile(cached, fd))
{
perror("MagickReadImageFile");
cached = DestroyMagickWand(cached);
}
} else {
perror("NewMagickWand");
}
fclose(fd);
}
return cached;
}
/*
* image file blob is in ctx->buffer[0..ctx->buflen)
* read it into imagemagick, apply imgmin to it and append the resulting blob
* into ctx->bb brigade
*/
static void do_imgmin(ap_filter_t *f, imgmin_ctx *ctx, imgmin_filter_config *c)
{
char path[PATH_MAX];
MagickWand *mw;
unsigned char *blob;
size_t bloblen;
/*
* calculate the cache path based on the original image contents
* and attempt to load cached results
*/
mw = NULL;
if (cache_path(ctx->buffer, ctx->buflen, path, c->cache_dir))
{
mw = cache_get(path, ctx);
}
if (mw)
{
blob = MagickGetImageBlob(mw, &bloblen);
} else {
/*
* not in cache. generate result and save to cache.
*/
MagickWand *tmp;
mw = NewMagickWand();
MagickReadImageBlob(mw, ctx->buffer, ctx->buflen);
tmp = search_quality(mw, "-", &c->opt);
blob = MagickGetImageBlob(tmp, &bloblen);
/* if result is larger than original fall back */
if (bloblen > ctx->buflen)
{
(void) MagickRelinquishMemory(blob);
blob = MagickGetImageBlob(mw, &bloblen);
}
/*
* if the results aren't from the cache, write to the cache for later use
*/
cache_set(c->cache_dir, path, blob, bloblen);
tmp = DestroyMagickWand(tmp);
}
/*
* by this point we've got the contents of our image response in 'blob',
* whether it's a cached image, a new response or the original image.
*/
{
apr_bucket *b = apr_bucket_heap_create((char *)blob,
bloblen, magickfree,
f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
}
mw = DestroyMagickWand(mw);
}
static apr_status_t imgmin_out_filter(ap_filter_t *f,
apr_bucket_brigade *bb)
{
apr_bucket *e;
request_rec *r = f->r;
imgmin_ctx *ctx = f->ctx;
imgmin_filter_config *c;
/* Do nothing if asked to filter nothing. */
if (APR_BRIGADE_EMPTY(bb)) {
return ap_pass_brigade(f->next, bb);
}
c = ap_get_module_config(r->server->module_config, &imgmin_module);
/* If we don't have a context, we need to ensure that it is okay to send
* the imgmind content. If we have a context, that means we've done
* this before and we liked it.
* This could be not so nice if we always fail. But, if we succeed,
* we're in better shape.
*/
if (!ctx) {
/* only work on main request/no subrequests */
if (r->main != NULL) {
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, bb);
}
/* We can't operate on Content-Ranges */
if (apr_table_get(r->headers_out, "Content-Range") != NULL) {
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, bb);
}
/* For a 304 or 204 response there is no entity included in
* the response and hence nothing to imgmin. */
if (r->status == HTTP_NOT_MODIFIED || r->status == HTTP_NO_CONTENT) {
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, bb);
}
/* We're cool with filtering this. */
ctx = f->ctx = apr_pcalloc(r->pool, sizeof *ctx);
ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
ctx->buffer = apr_palloc(r->pool, c->bufferSize);
ctx->buflen = 0;
/* initialize... */
/*
* Register a cleanup function to ensure that we cleanup
* imgmin resources.
*/
apr_pool_cleanup_register(r->pool, ctx, imgmin_ctx_cleanup,
apr_pool_cleanup_null);
}
while (!APR_BRIGADE_EMPTY(bb))
{
e = APR_BRIGADE_FIRST(bb);
if (APR_BUCKET_IS_EOS(e)) {
/* data is in ctx->buffer, imgmin it, pass results to new
* brigade ctx->bb */
do_imgmin(f, ctx, c);
/* No need for cleanup any longer */
apr_pool_cleanup_kill(r->pool, ctx, imgmin_ctx_cleanup);
/* Remove EOS from the old list, and insert into the new. */
APR_BUCKET_REMOVE(e);
APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
/* Okay, we've seen the EOS.
* Time to pass it along down the chain.
*/
return ap_pass_brigade(f->next, ctx->bb);
}
if (APR_BUCKET_IS_FLUSH(e)) {
apr_status_t rv;
/* Remove flush bucket from old brigade and insert into the new. */
APR_BUCKET_REMOVE(e);
APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
rv = ap_pass_brigade(f->next, ctx->bb);
if (rv != APR_SUCCESS) {
return rv;
}
continue;
}
if (APR_BUCKET_IS_METADATA(e)) {
/* Remove old brigade, insert into new. */
APR_BUCKET_REMOVE(e);
APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
continue;
}
/* append bucket data to ctx->buffer... */
/* TODO: I can avoid the ctx->buffer allocation and copy if I'm less lazy -- since this is intended
* for static JPEGs, and since most are reasonable sized, I'm assuming the entire file contents will
* come in one data bucket, in which case, if we do NOT receive a second data buckets before we see EOS
* we can simply not delete it and retain a pointer to it
*
* TODO: apr_bucket_read(..., APR_NONBLOCK_READ)
*/
{
const char *data = NULL;
apr_size_t len = 0;
apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
if (ctx->buflen + len > c->bufferSize)
{
len = c->bufferSize - ctx->buflen;
}
memcpy(ctx->buffer + ctx->buflen, data, len);
ctx->buflen += len;
}
apr_bucket_delete(e);
}
apr_brigade_cleanup(bb);
return APR_SUCCESS;
}
#define PROTO_FLAGS AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH
static void register_hooks(apr_pool_t *p)
{
ap_register_output_filter("IMGMIN", imgmin_out_filter, NULL, AP_FTYPE_RESOURCE);
}
static const command_rec imgmin_filter_cmds[] = {
AP_INIT_TAKE1("ImgminErrorThreshold", imgmin_set_error_threshold, NULL, RSRC_CONF, "Set error threshold (0-255.0)"),
AP_INIT_TAKE1("ImgminCacheDir", imgmin_set_cache_dir, NULL, RSRC_CONF, "Cache dir prefix. Default /var/imgmin-cache"),
AP_INIT_TAKE1("ImgminBufferSize", imgmin_set_buffer_size, NULL, RSRC_CONF, "Set maximum buffer size based on largest feasible image"),
{NULL}
};
module AP_MODULE_DECLARE_DATA imgmin_module = {
STANDARD20_MODULE_STUFF,
NULL, /* dir config creater */
NULL, /* dir merger --- default is to override */
create_imgmin_server_config, /* server config */
NULL, /* merge server config */
imgmin_filter_cmds, /* command table */
register_hooks /* register hooks */
};
| 6,522 |
825 | <filename>torchdyn/numerics/hypersolvers.py
# 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 torch
import torch.nn as nn
from torchdyn.numerics.solvers import Euler, Midpoint, RungeKutta4
class HyperEuler(Euler):
def __init__(self, hypernet, dtype=torch.float32):
super().__init__(dtype)
self.hypernet = hypernet
self.stepping_class = 'fixed'
def step(self, f, x, t, dt, k1=None):
_, x_sol, _ = super().step(f, x, t, dt, k1)
return None, x_sol + dt**2 * self.hypernet(t, x), None
class HyperMidpoint(Midpoint):
def __init__(self, hypernet, dtype=torch.float32):
super().__init__(dtype)
self.hypernet = hypernet
self.stepping_class = 'fixed'
def step(self, f, x, t, dt, k1=None):
_, x_sol, _ = super().step(f, x, t, dt, k1)
return None, x_sol + dt**3 * self.hypernet(t, x), None
class HyperRungeKutta4(RungeKutta4):
def __init__(self, hypernet, dtype=torch.float32):
super().__init__(dtype)
self.hypernet = hypernet
def step(self, f, x, t, dt, k1=None):
_, x_sol, _ = super().step(f, x, t, dt, k1)
return None, x_sol + dt**5 * self.hypernet(t, x), None
| 695 |
1,383 | <filename>src/chrono_vehicle/cosim/terrain/ChVehicleCosimTerrainNodeGranularMPI.cpp
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2020 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: <NAME>
// =============================================================================
//
// Implementation of the MPI granular TERRAIN NODE (using Chrono::Distributed).
//
// The global reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// CURRENT LIMITATIONS:
// - rigid obstacles not supported
// - settling phase not implemented
//
//
// =============================================================================
#include <algorithm>
#include <cmath>
#include <set>
#include <limits>
#include <unordered_map>
#include <omp.h>
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsGenerators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono_distributed/collision/ChBoundary.h"
#include "chrono_distributed/collision/ChCollisionModelDistributed.h"
#include "chrono_vehicle/cosim/terrain/ChVehicleCosimTerrainNodeGranularMPI.h"
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
using std::cout;
using std::cerr;
using std::endl;
using namespace rapidjson;
namespace chrono {
namespace vehicle {
// Ensure that all bodies other than obstacles or granular particles are created with a smaller identifier.
// This allows filtering particle bodies or particle+obstacle bodies.
static const int body_id_obstacles = 100000; // start identifier for obstacle bodies
static const int body_id_particles = 110000; // start identifier for particle bodies
// -----------------------------------------------------------------------------
// Construction of the terrain node:
// - create the (distributed) Chrono system and set solver parameters
// - create the OpenGL visualization window
//
// ATTENTION: A distributed system requires an MPI subcommunicator.
// This is available only after initialization of the co-simulation framework.
// -----------------------------------------------------------------------------
ChVehicleCosimTerrainNodeGranularMPI::ChVehicleCosimTerrainNodeGranularMPI(double length, double width)
: ChVehicleCosimTerrainNodeChrono(Type::GRANULAR_MPI, length, width, ChContactMethod::SMC),
m_radius_p(5e-3),
m_sampling_type(utils::SamplingType::POISSON_DISK),
m_init_depth(0.2),
m_separation_factor(1.001),
m_in_layers(false),
m_constructed(false),
m_proxies_constructed(false),
m_hthick(0.1),
m_num_particles(0),
m_system(nullptr) {
if (!cosim::IsFrameworkInitialized()) {
if (m_rank == TERRAIN_NODE_RANK)
cerr << "Error: Co-simulation framework not initialized." << endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
// Get the rank within the intracommunicator
MPI_Comm_rank(cosim::GetTerrainIntracommunicator(), &m_sub_rank);
// Default granular material properties
m_radius_g = 0.01;
m_rho_g = 2000;
// Create the distributed system
CreateSystem();
if (m_rank == TERRAIN_NODE_RANK && !m_system->OnMaster()) {
cerr << "Error: Inconsistent intracommunicator rank." << endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
}
ChVehicleCosimTerrainNodeGranularMPI::ChVehicleCosimTerrainNodeGranularMPI(const std::string& specfile)
: ChVehicleCosimTerrainNodeChrono(Type::GRANULAR_MPI, 0, 0, ChContactMethod::SMC),
m_constructed(false),
m_proxies_constructed(false),
m_hthick(0.1),
m_num_particles(0),
m_system(nullptr) {
if (!cosim::IsFrameworkInitialized()) {
if (m_rank == TERRAIN_NODE_RANK)
cerr << "Error: rank " << MBS_NODE_RANK << " is not running an MBS node." << endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
// Get the rank within the intracommunicator
MPI_Comm_rank(cosim::GetTerrainIntracommunicator(), &m_sub_rank);
// Create the distributed system
CreateSystem();
if (m_rank == TERRAIN_NODE_RANK && !m_system->OnMaster()) {
cerr << "Error: Inconsistent intracommunicator rank." << endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
// Read granular OMP terrain parameters from provided specfile
SetFromSpecfile(specfile);
m_init_height = m_init_depth;
}
ChVehicleCosimTerrainNodeGranularMPI::~ChVehicleCosimTerrainNodeGranularMPI() {
delete m_system;
}
void ChVehicleCosimTerrainNodeGranularMPI::CreateSystem() {
// Create the Chrono::Distributed system.
m_system = new ChSystemDistributed(cosim::GetTerrainIntracommunicator(), 0, 100000);
m_system->GetSettings()->solver.contact_force_model = ChSystemSMC::ContactForceModel::Hertz;
m_system->GetSettings()->solver.tangential_displ_mode = ChSystemSMC::TangentialDisplacementModel::OneStep;
m_system->GetSettings()->solver.use_material_properties = true;
m_system->Set_G_acc(ChVector<>(0, 0, m_gacc));
m_system->GetSettings()->solver.use_full_inertia_tensor = false;
m_system->GetSettings()->solver.tolerance = 0.1;
m_system->GetSettings()->solver.max_iteration_bilateral = 100;
m_system->GetSettings()->collision.narrowphase_algorithm = collision::ChNarrowphase::Algorithm::HYBRID;
m_system->GetSettings()->collision.collision_envelope = 0;
m_system->SetNumThreads(1);
#pragma omp parallel
#pragma omp master
{
// Sanity check: print number of threads in a parallel region
cout << "[Terrain node] [" << m_rank << " " << m_sub_rank
<< "] actual number of OpenMP threads: " << omp_get_num_threads() << endl;
}
}
// -----------------------------------------------------------------------------
//// TODO: error checking
void ChVehicleCosimTerrainNodeGranularMPI::SetFromSpecfile(const std::string& specfile) {
Document d;
ReadSpecfile(specfile, d);
double length = d["Patch dimensions"]["Length"].GetDouble();
double width = d["Patch dimensions"]["Width"].GetDouble();
m_hdimX = length / 2;
m_hdimY = width / 2;
m_radius_g = d["Granular material"]["Radius"].GetDouble();
m_rho_g = d["Granular material"]["Density"].GetDouble();
double coh_pressure = d["Material properties"]["Cohesion pressure"].GetDouble();
double coh_force = CH_C_PI * m_radius_g * m_radius_g * coh_pressure;
auto material = chrono_types::make_shared<ChMaterialSurfaceSMC>();
material->SetFriction(d["Material properties"]["Coefficient of friction"].GetDouble());
material->SetRestitution(d["Material properties"]["Coefficient of restitution"].GetDouble());
material->SetYoungModulus(d["Material properties"]["Young modulus"].GetDouble());
material->SetPoissonRatio(d["Material properties"]["Poisson ratio"].GetDouble());
material->SetAdhesion(static_cast<float>(coh_force));
material->SetKn(d["Material properties"]["Kn"].GetDouble());
material->SetGn(d["Material properties"]["Gn"].GetDouble());
material->SetKt(d["Material properties"]["Kt"].GetDouble());
material->SetGt(d["Material properties"]["Gt"].GetDouble());
m_material_terrain = material;
std::string sampling = d["Particle generation"]["Sampling method"].GetString();
if (sampling.compare("POISSON_DISK") == 0)
m_sampling_type = utils::SamplingType::POISSON_DISK;
else if (sampling.compare("HCP_PACK") == 0)
m_sampling_type = utils::SamplingType::HCP_PACK;
else if (sampling.compare("REGULAR_GRID") == 0)
m_sampling_type = utils::SamplingType::REGULAR_GRID;
m_init_depth = d["Particle generation"]["Initial height"].GetDouble();
m_separation_factor = d["Particle generation"]["Separation factor"].GetDouble();
m_in_layers = d["Particle generation"]["Initialize in layers"].GetBool();
std::string n_model = d["Simulation settings"]["Normal contact model"].GetString();
if (n_model.compare("Hertz") == 0)
m_system->GetSettings()->solver.contact_force_model = ChSystemSMC::ContactForceModel::Hertz;
else if (n_model.compare("Hooke") == 0)
m_system->GetSettings()->solver.contact_force_model = ChSystemSMC::ContactForceModel::Hooke;
else if (n_model.compare("Flores") == 0)
m_system->GetSettings()->solver.contact_force_model = ChSystemSMC::ContactForceModel::Flores;
else if (n_model.compare("Hertz") == 0)
m_system->GetSettings()->solver.contact_force_model = ChSystemSMC::ContactForceModel::PlainCoulomb;
std::string t_model = d["Simulation settings"]["Tangential displacement model"].GetString();
if (t_model.compare("MultiStep") == 0)
m_system->GetSettings()->solver.tangential_displ_mode = ChSystemSMC::TangentialDisplacementModel::MultiStep;
else if (t_model.compare("OneStep") == 0)
m_system->GetSettings()->solver.tangential_displ_mode = ChSystemSMC::TangentialDisplacementModel::OneStep;
else if (t_model.compare("None") == 0)
m_system->GetSettings()->solver.tangential_displ_mode = ChSystemSMC::TangentialDisplacementModel::None;
m_system->GetSettings()->solver.use_material_properties =
d["Simulation settings"]["Use material properties"].GetBool();
m_radius_p = d["Simulation settings"]["Proxy contact radius"].GetDouble();
m_fixed_proxies = d["Simulation settings"]["Fix proxies"].GetBool();
}
void ChVehicleCosimTerrainNodeGranularMPI::SetNumThreads(int num_threads) {
m_system->SetNumThreads(num_threads);
}
void ChVehicleCosimTerrainNodeGranularMPI::SetWallThickness(double thickness) {
m_hthick = thickness / 2;
}
void ChVehicleCosimTerrainNodeGranularMPI::SetGranularMaterial(double radius, double density) {
m_radius_g = radius;
m_rho_g = density;
}
void ChVehicleCosimTerrainNodeGranularMPI::UseMaterialProperties(bool flag) {
m_system->GetSettings()->solver.use_material_properties = flag;
}
void ChVehicleCosimTerrainNodeGranularMPI::SetContactForceModel(ChSystemSMC::ContactForceModel model) {
m_system->GetSettings()->solver.contact_force_model = model;
}
void ChVehicleCosimTerrainNodeGranularMPI::SetTangentialDisplacementModel(
ChSystemSMC::TangentialDisplacementModel model) {
m_system->GetSettings()->solver.tangential_displ_mode = model;
}
void ChVehicleCosimTerrainNodeGranularMPI::SetSamplingMethod(utils::SamplingType type,
double init_height,
double sep_factor,
bool in_layers) {
m_sampling_type = type;
m_init_depth = init_height;
m_separation_factor = sep_factor;
m_in_layers = in_layers;
}
void ChVehicleCosimTerrainNodeGranularMPI::SetMaterialSurface(const std::shared_ptr<ChMaterialSurfaceSMC>& mat) {
m_material_terrain = mat;
}
// -----------------------------------------------------------------------------
// Complete construction of the mechanical system.
// Invoked by ChVehicleCosimTerrainNodeChrono::OnInitialize.
// - create distributed system (MPI subcommunicator available here)
// - adjust system settings
// - create the container body
// - create the granular material
// -----------------------------------------------------------------------------
void ChVehicleCosimTerrainNodeGranularMPI::Construct() {
if (m_constructed)
return;
// Resize vector of additional tire data
m_tire_data.resize(m_num_tire_nodes);
// Issue messages and render only on the main terrain node
m_verbose = m_verbose && (m_rank == TERRAIN_NODE_RANK);
m_render = m_render && (m_rank == TERRAIN_NODE_RANK);
// Calculate container (half) height
double r = m_separation_factor * m_radius_g;
double delta = 2.0f * r;
// Domain decomposition
ChVector<> lo(-m_hdimX - delta, -m_hdimY - delta, -2 * m_radius_g);
ChVector<> hi(+m_hdimX + delta, +m_hdimY + delta, m_init_depth + 3 * m_radius_g);
m_system->GetDomain()->SetSplitAxis(0); //// TODO: let user specify this
m_system->GetDomain()->SetSimDomain(lo, hi);
m_system->SetGhostLayer(2 * m_radius_g);
// Estimates for number of bins for broad-phase.
int factor = 2;
auto& sub_lo = m_system->GetDomain()->GetSubLo();
auto& sub_hi = m_system->GetDomain()->GetSubHi();
auto sub_hdim = (sub_hi - sub_lo) / 2;
int binsX = (int)std::ceil(sub_hdim.x() / m_radius_g) / factor;
int binsY = (int)std::ceil(sub_hdim.y() / m_radius_g) / factor;
int binsZ = 1;
m_system->GetSettings()->collision.bins_per_axis = vec3(binsX, binsY, binsZ);
if (m_verbose)
cout << "[Terrain node] broad-phase bins: " << binsX << " x " << binsY << " x " << binsZ << endl;
// ---------------------
// Create container body
// ----------------------
auto container = std::shared_ptr<ChBody>(m_system->NewBody());
container->SetIdentifier(-1);
container->SetPos(ChVector<>(0, 0, 0));
container->SetMass(1);
container->SetBodyFixed(true);
container->SetCollide(true);
m_system->AddBodyAllRanks(container);
double dimX = 2 * m_hdimX;
double dimY = 2 * m_hdimY;
double dimZ = m_init_depth;
double hdimZ = dimZ / 2;
auto cb = new ChBoundary(container, std::static_pointer_cast<ChMaterialSurfaceSMC>(m_material_terrain));
cb->AddPlane(ChFrame<>(ChVector<>(0, 0, 0), QUNIT), ChVector2<>(dimX, dimY));
cb->AddPlane(ChFrame<>(ChVector<>(-m_hdimX, 0, hdimZ), Q_from_AngY(+CH_C_PI_2)), ChVector2<>(dimZ, dimY));
cb->AddPlane(ChFrame<>(ChVector<>(+m_hdimX, 0, hdimZ), Q_from_AngY(-CH_C_PI_2)), ChVector2<>(dimZ, dimY));
cb->AddPlane(ChFrame<>(ChVector<>(0, -m_hdimY, hdimZ), Q_from_AngX(-CH_C_PI_2)), ChVector2<>(dimX, dimZ));
cb->AddPlane(ChFrame<>(ChVector<>(0, +m_hdimY, hdimZ), Q_from_AngX(+CH_C_PI_2)), ChVector2<>(dimX, dimZ));
// Enable deactivation of bodies that exit a specified bounding box.
// We set this bounding box to encapsulate the container with a conservative height.
m_system->GetSettings()->collision.use_aabb_active = true;
m_system->GetSettings()->collision.aabb_min = real3(-m_hdimX - m_hthick, -m_hdimY - m_hthick, -m_hthick);
m_system->GetSettings()->collision.aabb_max = real3(+m_hdimX + m_hthick, +m_hdimY + m_hthick, 2 * hdimZ + 2);
// --------------------------
// Generate granular material
// --------------------------
// Mass and inertia moments for a granular particle
double mass_g = m_rho_g * 4 / 3 * CH_C_PI * m_radius_g * m_radius_g * m_radius_g;
ChVector<> inertia_g = (2.0 / 5.0) * mass_g * m_radius_g * m_radius_g * ChVector<>(1, 1, 1);
// Create particles using the specified volume sampling type
utils::Sampler<double>* sampler;
switch (m_sampling_type) {
default:
case utils::SamplingType::POISSON_DISK:
sampler = new utils::PDSampler<double>(delta);
break;
case utils::SamplingType::HCP_PACK:
sampler = new utils::HCPSampler<double>(delta);
break;
case utils::SamplingType::REGULAR_GRID:
sampler = new utils::GridSampler<double>(delta);
break;
}
// Create particle locations
std::vector<ChVector<>> points;
if (m_in_layers) {
ChVector<> hdims(m_hdimX - r, m_hdimY - r, 0);
double z = delta;
while (z < m_init_depth) {
auto points_new = sampler->SampleBox(ChVector<>(0, 0, z), hdims);
points.insert(points.end(), points_new.begin(), points_new.end());
if (m_verbose)
cout << " z = " << z << "\tnum particles = " << points.size() << endl;
z += delta;
}
} else {
ChVector<> hdims(m_hdimX - r, m_hdimY - r, hdimZ - r);
points = sampler->SampleBox(ChVector<>(0, 0, hdimZ), hdims);
}
// Create particle bodies with identifiers starting at m_Id_g
m_num_particles = (unsigned int)points.size();
if (m_verbose)
cout << "[Terrain node] Generated num particles = " << m_num_particles << endl;
m_init_height = -std::numeric_limits<double>::max();
int particle_id = body_id_particles;
for (unsigned int i = 0; i < m_num_particles; i++) {
auto body =
chrono_types::make_shared<ChBody>(chrono_types::make_shared<collision::ChCollisionModelDistributed>());
body->SetIdentifier(particle_id++);
body->SetMass(mass_g);
body->SetInertiaXX(inertia_g);
body->SetPos(points[i]);
body->SetRot(ChQuaternion<>(1, 0, 0, 0));
body->SetBodyFixed(false);
body->SetCollide(true);
body->GetCollisionModel()->ClearModel();
utils::AddSphereGeometry(body.get(), m_material_terrain, m_radius_g);
body->GetCollisionModel()->BuildModel();
m_system->AddBody(body);
if (points[i].z() > m_init_height)
m_init_height = points[i].z();
}
if (m_verbose)
cout << "[Terrain node] initial height = " << m_init_height << endl;
#ifdef CHRONO_OPENGL
// Render only on the main terrain node
m_render = m_render && (m_rank == TERRAIN_NODE_RANK);
// Create the visualization window
if (m_render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Terrain Node (GranularOMP)", m_system);
gl_window.SetCamera(ChVector<>(0, -3, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
gl_window.SetRenderMode(opengl::WIREFRAME);
}
#endif
// Write file with terrain node settings
if (m_rank == TERRAIN_NODE_RANK) {
std::ofstream outf;
outf.open(m_node_out_dir + "/settings.info", std::ios::out);
outf << "System settings" << endl;
outf << " Integration step size = " << m_step_size << endl;
outf << " Use material properties? "
<< (m_system->GetSettings()->solver.use_material_properties ? "YES" : "NO") << endl;
outf << "Terrain patch dimensions" << endl;
outf << " X = " << 2 * m_hdimX << " Y = " << 2 * m_hdimY << endl;
outf << "Terrain material properties" << endl;
auto mat = std::static_pointer_cast<ChMaterialSurfaceSMC>(m_material_terrain);
outf << " Coefficient of friction = " << mat->GetKfriction() << endl;
outf << " Coefficient of restitution = " << mat->GetRestitution() << endl;
outf << " Young modulus = " << mat->GetYoungModulus() << endl;
outf << " Poisson ratio = " << mat->GetPoissonRatio() << endl;
outf << " Adhesion force = " << mat->GetAdhesion() << endl;
outf << " Kn = " << mat->GetKn() << endl;
outf << " Gn = " << mat->GetGn() << endl;
outf << " Kt = " << mat->GetKt() << endl;
outf << " Gt = " << mat->GetGt() << endl;
outf << "Granular material properties" << endl;
outf << " particle radius = " << m_radius_g << endl;
outf << " particle density = " << m_rho_g << endl;
outf << " number particles = " << m_num_particles << endl;
outf << "Proxy body properties" << endl;
outf << " proxies fixed? " << (m_fixed_proxies ? "YES" : "NO") << endl;
outf << " proxy contact radius = " << m_radius_p << endl;
}
// Mark system as constructed.
m_constructed = true;
}
// -----------------------------------------------------------------------------
double ChVehicleCosimTerrainNodeGranularMPI::CalcTotalKineticEnergy() {
double KE = 0;
int i = 0;
auto bl_itr = m_system->data_manager->body_list->begin();
for (; bl_itr != m_system->data_manager->body_list->end(); bl_itr++, i++) {
if (m_system->ddm->comm_status[i] != chrono::distributed::EMPTY && (*bl_itr)->GetIdentifier() > 0) {
const auto& vel = (*bl_itr)->GetPos_dt();
const auto& omg = (*bl_itr)->GetWvel_par();
const auto& m = (*bl_itr)->GetMass();
const auto& J = (*bl_itr)->GetInertiaXX();
KE += m * vel.Length2() + omg.Dot(J * omg);
}
}
return 0.5 * KE;
}
double ChVehicleCosimTerrainNodeGranularMPI::CalcCurrentHeight() {
double height = -std::numeric_limits<double>::max();
int i = 0;
auto bl_itr = m_system->data_manager->body_list->begin();
for (; bl_itr != m_system->data_manager->body_list->end(); bl_itr++, i++) {
if (m_system->ddm->comm_status[i] != chrono::distributed::EMPTY) {
const auto& pos = (*bl_itr)->GetPos();
if ((*bl_itr)->GetIdentifier() > 0 && pos.z() > height)
height = pos.z();
}
}
return height;
}
//// TODO: Consider looking only at particles below a certain fraction of the
//// height of the highest particle. This would eliminate errors in estimating
//// the total volume stemming from a "non-smooth" top surface or stray particles.
double ChVehicleCosimTerrainNodeGranularMPI::CalculatePackingDensity(double& depth) {
// Find height of granular material
double z_max = CalcCurrentHeight();
double z_min = 0;
depth = z_max - z_min;
// Find total volume of granular material
double Vt = (2 * m_hdimX) * (2 * m_hdimY) * (z_max - z_min);
// Find volume of granular particles
double Vs = m_num_particles * (4.0 / 3) * CH_C_PI * std::pow(m_radius_g, 3);
// Packing density = Vs/Vt
return Vs / Vt;
}
// -----------------------------------------------------------------------------
// Tire mesh information is available in m_mesh_data only on the main terrain node.
// Broadcast information to intra-communicator.
void ChVehicleCosimTerrainNodeGranularMPI::ScatterInitData(unsigned int i) {
auto root = m_system->GetMasterRank();
auto comm = m_system->GetCommunicator();
double tire_info[2];
if (m_rank == TERRAIN_NODE_RANK) {
tire_info[0] = m_tire_radius[i];
tire_info[1] = m_tire_width[i];
}
MPI_Bcast(tire_info, 2, MPI_DOUBLE, root, comm);
if (m_rank != TERRAIN_NODE_RANK) {
m_tire_radius[i] = tire_info[0];
m_tire_width[i] = tire_info[1];
}
unsigned int surf_props[3];
if (m_rank == TERRAIN_NODE_RANK) {
surf_props[0] = m_mesh_data[i].nv;
surf_props[1] = m_mesh_data[i].nn;
surf_props[2] = m_mesh_data[i].nt;
}
MPI_Bcast(surf_props, 3, MPI_UNSIGNED, root, comm);
if (m_rank != TERRAIN_NODE_RANK) {
m_mesh_data[i].nv = surf_props[0];
m_mesh_data[i].nn = surf_props[1];
m_mesh_data[i].nt = surf_props[2];
m_mesh_data[i].verts.resize(m_mesh_data[i].nv);
m_mesh_data[i].norms.resize(m_mesh_data[i].nn);
m_mesh_data[i].idx_verts.resize(m_mesh_data[i].nt);
m_mesh_data[i].idx_norms.resize(m_mesh_data[i].nt);
m_mesh_state[i].vpos.resize(m_mesh_data[i].nv);
m_mesh_state[i].vvel.resize(m_mesh_data[i].nv);
}
double* vert_data = new double[3 * m_mesh_data[i].nv + 3 * m_mesh_data[i].nn];
int* tri_data = new int[3 * m_mesh_data[i].nt + 3 * m_mesh_data[i].nt];
if (m_rank == TERRAIN_NODE_RANK) {
for (unsigned int iv = 0; iv < m_mesh_data[i].nv; iv++) {
vert_data[3 * iv + 0] = m_mesh_data[i].verts[iv].x();
vert_data[3 * iv + 1] = m_mesh_data[i].verts[iv].y();
vert_data[3 * iv + 2] = m_mesh_data[i].verts[iv].z();
}
for (unsigned int in = 0; in < m_mesh_data[i].nn; in++) {
vert_data[3 * m_mesh_data[i].nv + 3 * in + 0] = m_mesh_data[i].norms[in].x();
vert_data[3 * m_mesh_data[i].nv + 3 * in + 1] = m_mesh_data[i].norms[in].y();
vert_data[3 * m_mesh_data[i].nv + 3 * in + 2] = m_mesh_data[i].norms[in].z();
}
for (unsigned int it = 0; it < m_mesh_data[i].nt; it++) {
tri_data[6 * it + 0] = m_mesh_data[i].idx_verts[it].x();
tri_data[6 * it + 1] = m_mesh_data[i].idx_verts[it].y();
tri_data[6 * it + 2] = m_mesh_data[i].idx_verts[it].z();
tri_data[6 * it + 3] = m_mesh_data[i].idx_norms[it].x();
tri_data[6 * it + 4] = m_mesh_data[i].idx_norms[it].y();
tri_data[6 * it + 5] = m_mesh_data[i].idx_norms[it].z();
}
}
MPI_Bcast(vert_data, 3 * m_mesh_data[i].nv + 3 * m_mesh_data[i].nn, MPI_DOUBLE, root, comm);
MPI_Bcast(tri_data, 3 * m_mesh_data[i].nt + 3 * m_mesh_data[i].nt, MPI_INT, root, comm);
if (m_rank != TERRAIN_NODE_RANK) {
for (unsigned int iv = 0; iv < m_mesh_data[i].nv; iv++) {
m_mesh_data[i].verts[iv].x() = vert_data[3 * iv + 0];
m_mesh_data[i].verts[iv].y() = vert_data[3 * iv + 1];
m_mesh_data[i].verts[iv].z() = vert_data[3 * iv + 2];
}
for (unsigned int in = 0; in < m_mesh_data[i].nn; in++) {
m_mesh_data[i].norms[in].x() = vert_data[3 * m_mesh_data[i].nv + 3 * in + 0];
m_mesh_data[i].norms[in].y() = vert_data[3 * m_mesh_data[i].nv + 3 * in + 1];
m_mesh_data[i].norms[in].z() = vert_data[3 * m_mesh_data[i].nv + 3 * in + 2];
}
for (unsigned int it = 0; it < m_mesh_data[i].nt; it++) {
m_mesh_data[i].idx_verts[it].x() = tri_data[6 * it + 0];
m_mesh_data[i].idx_verts[it].y() = tri_data[6 * it + 1];
m_mesh_data[i].idx_verts[it].z() = tri_data[6 * it + 2];
m_mesh_data[i].idx_norms[it].x() = tri_data[6 * it + 3];
m_mesh_data[i].idx_norms[it].y() = tri_data[6 * it + 4];
m_mesh_data[i].idx_norms[it].z() = tri_data[6 * it + 5];
}
}
delete[] vert_data;
delete[] tri_data;
MPI_Bcast(&m_load_mass[i], 1, MPI_DOUBLE, root, comm);
float mat_props[8];
if (m_rank == TERRAIN_NODE_RANK) {
mat_props[0] = m_mat_props[i].mu;
mat_props[1] = m_mat_props[i].cr;
mat_props[2] = m_mat_props[i].Y;
mat_props[3] = m_mat_props[i].nu;
mat_props[4] = m_mat_props[i].kn;
mat_props[5] = m_mat_props[i].gn;
mat_props[6] = m_mat_props[i].kt;
mat_props[7] = m_mat_props[i].gt;
}
MPI_Bcast(mat_props, 8, MPI_FLOAT, root, comm);
if (m_rank != TERRAIN_NODE_RANK) {
m_mat_props[i].mu = mat_props[0];
m_mat_props[i].cr = mat_props[1];
m_mat_props[i].Y = mat_props[2];
m_mat_props[i].nu = mat_props[3];
m_mat_props[i].kn = mat_props[4];
m_mat_props[i].gn = mat_props[5];
m_mat_props[i].kt = mat_props[6];
m_mat_props[i].gt = mat_props[7];
}
}
// Body position must be known when adding the body to a Chrono::Distributed system, so that the body is assigned to the
// appropriate rank. However, in the co-simulation framework, the wheel/spindle position is not known until the first
// synchronization. We defer proxy body creation until the first synchronization time.
void ChVehicleCosimTerrainNodeGranularMPI::CreateMeshProxies(unsigned int i) {
ScatterInitData(i);
m_tire_data[i].m_gids.resize(m_mesh_data[i].nt);
m_tire_data[i].m_start_tri = (i == 0) ? 0 : m_tire_data[i - 1].m_start_tri + m_mesh_data[i].nt;
}
void ChVehicleCosimTerrainNodeGranularMPI::CreateWheelProxy(unsigned int i) {
ScatterInitData(i);
m_tire_data[i].m_gids.resize(m_mesh_data[i].nt);
m_tire_data[i].m_start_tri = (i == 0) ? 0 : m_tire_data[i - 1].m_start_tri + m_mesh_data[i].nt;
}
// Since Chrono::Distributed cannot treat a trimesh as a single collision object,
// we always create a number of proxy bodies with triangle collision shape equal
// to the number of faces in the tire mesh. These proxies are used for both rigid
// and flexible tires.
// Assign to each body an identifier equal to the index of its corresponding mesh face.
// Add all proxy bodies to the same collision family and disable collision between any
// two members of this family.
void ChVehicleCosimTerrainNodeGranularMPI::CreateMeshProxiesInternal(unsigned int i) {
//// RADU TODO: better approximation of mass / inertia?
double mass_p = m_load_mass[i] / m_mesh_data[i].nt;
ChVector<> inertia_p = 1e-3 * mass_p * ChVector<>(0.1, 0.1, 0.1);
auto material_tire = m_mat_props[i].CreateMaterial(m_method);
for (unsigned int it = 0; it < m_mesh_data[i].nt; it++) {
unsigned int body_id = m_tire_data[i].m_start_tri + it;
auto body = std::shared_ptr<ChBody>(m_system->NewBody());
body->SetIdentifier(body_id);
body->SetMass(mass_p);
body->SetInertiaXX(inertia_p);
body->SetBodyFixed(m_fixed_proxies);
// Determine initial position.
// Use current information in m_mesh_state which encodes the current wheel position.
const auto& tri = m_mesh_data[i].idx_verts[it];
const auto& pA = m_mesh_state[i].vpos[tri[0]];
const auto& pB = m_mesh_state[i].vpos[tri[1]];
const auto& pC = m_mesh_state[i].vpos[tri[2]];
ChVector<> pos = (pA + pB + pC) / 3;
body->SetPos(pos);
// Create contact shape.
std::string name = "tri_" + std::to_string(body_id);
body->GetCollisionModel()->ClearModel();
utils::AddTriangleGeometry(body.get(), material_tire, pA - pos, pB - pos, pC - pos, name);
body->GetCollisionModel()->SetFamily(1);
body->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(1);
body->GetCollisionModel()->BuildModel();
body->SetCollide(true);
m_system->AddBody(body);
// Update map global ID -> triangle index
m_tire_data[i].m_gids[it] = body->GetGid();
m_tire_data[i].m_map[body->GetGid()] = it;
}
}
void ChVehicleCosimTerrainNodeGranularMPI::CreateWheelProxyInternal(unsigned int i) {
//// RADU TODO: better approximation of mass / inertia?
double mass_p = m_load_mass[i] / m_mesh_data[i].nt;
ChVector<> inertia_p = 1e-3 * mass_p * ChVector<>(0.1, 0.1, 0.1);
auto material_tire = m_mat_props[i].CreateMaterial(m_method);
for (unsigned int it = 0; it < m_mesh_data[i].nt; it++) {
unsigned int body_id = m_tire_data[i].m_start_tri + it;
auto body = std::shared_ptr<ChBody>(m_system->NewBody());
body->SetIdentifier(body_id);
body->SetMass(mass_p);
body->SetInertiaXX(inertia_p);
body->SetBodyFixed(m_fixed_proxies);
// Determine initial position.
// Use current information in m_spindle_state.
const auto& tri = m_mesh_data[i].idx_verts[it];
const auto& pA = m_mesh_data[i].verts[tri[0]];
const auto& pB = m_mesh_data[i].verts[tri[1]];
const auto& pC = m_mesh_data[i].verts[tri[2]];
ChVector<> pos = (pA + pB + pC) / 3;
body->SetPos(m_spindle_state[i].pos + pos);
// Create contact shape.
std::string name = "tri_" + std::to_string(body_id);
body->GetCollisionModel()->ClearModel();
utils::AddTriangleGeometry(body.get(), material_tire, pA - pos, pB - pos, pC - pos, name);
body->GetCollisionModel()->SetFamily(1);
body->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(1);
body->GetCollisionModel()->BuildModel();
body->SetCollide(true);
m_system->AddBody(body);
// Update map global ID -> triangle index
m_tire_data[i].m_gids[it] = body->GetGid();
m_tire_data[i].m_map[body->GetGid()] = it;
}
}
// -----------------------------------------------------------------------------
// Set position, orientation, and velocity of proxy bodies based on tire mesh faces.
// The proxy body is effectively reconstructed at each synchronization time:
// - position at the center of mass of the three vertices
// - orientation: identity
// - linear and angular velocity: consistent with vertex velocities
// - contact shape: redefined to match vertex locations
void ChVehicleCosimTerrainNodeGranularMPI::UpdateMeshProxies(unsigned int i, MeshState& mesh_state) {
auto& mesh_data = m_mesh_data[i]; // mesh data for the i-th tire
auto& tire_data = m_tire_data[i]; // additional data for the i-th tire
// 1. Scatter current tire mesh state from the main terrain node to intra-communicator.
double* vert_data = new double[2 * 3 * mesh_data.nv];
if (m_rank == TERRAIN_NODE_RANK) {
for (unsigned int iv = 0; iv < mesh_data.nv; iv++) {
unsigned int offset = 3 * iv;
vert_data[offset + 0] = mesh_state.vpos[iv].x();
vert_data[offset + 1] = mesh_state.vpos[iv].y();
vert_data[offset + 2] = mesh_state.vpos[iv].z();
offset += 3 * mesh_data.nv;
vert_data[offset + 0] = mesh_state.vvel[iv].x();
vert_data[offset + 1] = mesh_state.vvel[iv].y();
vert_data[offset + 2] = mesh_state.vvel[iv].z();
}
}
MPI_Bcast(vert_data, 2 * 3 * mesh_data.nv, MPI_DOUBLE, m_system->GetMasterRank(), m_system->GetCommunicator());
if (m_rank != TERRAIN_NODE_RANK) {
for (unsigned int iv = 0; iv < mesh_data.nv; iv++) {
unsigned int offset = 3 * iv;
m_mesh_state[i].vpos[iv] = ChVector<>(vert_data[offset + 0], vert_data[offset + 1], vert_data[offset + 2]);
offset += 3 * mesh_data.nv;
m_mesh_state[i].vvel[iv] = ChVector<>(vert_data[offset + 0], vert_data[offset + 1], vert_data[offset + 2]);
}
}
delete[] vert_data;
// 2. Create proxies
if (!m_proxies_constructed) {
CreateMeshProxiesInternal(i);
m_proxies_constructed = true;
}
// 3. Use information in mesh_state to update proxy states.
std::vector<ChSystemDistributed::BodyState> states(mesh_data.nt);
std::vector<ChSystemDistributed::TriData> shapes(mesh_data.nt);
std::vector<int> shape_idx(mesh_data.nt, 0);
for (unsigned int it = 0; it < mesh_data.nt; it++) {
// Associated mesh triangle
const auto& tri = mesh_data.idx_verts[it];
// Vertex locations and velocities (expressed in global frame)
const auto& pA = mesh_state.vpos[tri.x()];
const auto& pB = mesh_state.vpos[tri.y()];
const auto& pC = mesh_state.vpos[tri.z()];
const auto& vA = mesh_state.vvel[tri.x()];
const auto& vB = mesh_state.vvel[tri.y()];
const auto& vC = mesh_state.vvel[tri.z()];
// Position and orientation of proxy body (at triangle barycenter)
ChVector<> pos = (pA + pB + pC) / 3;
states[it].pos = pos;
states[it].rot = QUNIT;
// Linear velocity (absolute) and angular velocity (local)
// These are the solution of an over-determined 9x6 linear system. However, for a centroidal
// body reference frame, the linear velocity is the average of the 3 vertex velocities.
// This leaves a 9x3 linear system for the angular velocity which should be solved in a
// least-square sense: Ax = b => (A'A)x = A'b
states[it].pos_dt = (vA + vB + vC) / 3;
states[it].rot_dt = QNULL; //// TODO: angular velocity
// Triangle contact shape (expressed in local frame).
shapes[it].v1 = pA - pos;
shapes[it].v2 = pB - pos;
shapes[it].v3 = pC - pos;
}
// Update body states
m_system->SetBodyStates(tire_data.m_gids, states);
// Update collision shapes (one triangle per collision model)
m_system->SetTriangleShapes(tire_data.m_gids, shape_idx, shapes);
}
// Set state of wheel proxy body.
void ChVehicleCosimTerrainNodeGranularMPI::UpdateWheelProxy(unsigned int i, BodyState& spindle_state) {
auto& mesh_data = m_mesh_data[i]; // mesh data for the i-th tire
auto& tire_data = m_tire_data[i]; // additional data for the i-th tire
// 1. Scatter current spindle body state from the main terrain node to intra-communicator.
double state_data[13];
if (m_rank == TERRAIN_NODE_RANK) {
state_data[0] = spindle_state.pos.x();
state_data[1] = spindle_state.pos.y();
state_data[2] = spindle_state.pos.z();
state_data[3] = spindle_state.rot.e0();
state_data[4] = spindle_state.rot.e1();
state_data[5] = spindle_state.rot.e2();
state_data[6] = spindle_state.rot.e3();
state_data[7] = spindle_state.lin_vel.x();
state_data[8] = spindle_state.lin_vel.y();
state_data[9] = spindle_state.lin_vel.z();
state_data[10] = spindle_state.ang_vel.x();
state_data[11] = spindle_state.ang_vel.y();
state_data[12] = spindle_state.ang_vel.z();
}
MPI_Bcast(state_data, 13, MPI_DOUBLE, m_system->GetMasterRank(), m_system->GetCommunicator());
if (m_rank != TERRAIN_NODE_RANK) {
spindle_state.pos = ChVector<>(state_data[0], state_data[1], state_data[2]);
spindle_state.rot = ChQuaternion<>(state_data[3], state_data[4], state_data[5], state_data[6]);
spindle_state.lin_vel = ChVector<>(state_data[7], state_data[8], state_data[9]);
spindle_state.ang_vel = ChVector<>(state_data[10], state_data[11], state_data[12]);
}
// 2. Create proxies
if (!m_proxies_constructed) {
CreateWheelProxyInternal(i);
m_proxies_constructed = true;
}
// 2. Use information in spindle_state to update proxy states (apply rigid body motion).
std::vector<ChSystemDistributed::BodyState> states(mesh_data.nt);
ChMatrix33<> spindle_rot(spindle_state.rot);
for (unsigned int it = 0; it < mesh_data.nt; it++) {
// Associated mesh triangle
const auto& tri = mesh_data.idx_verts[it];
const auto& pA = mesh_data.verts[tri[0]];
const auto& pB = mesh_data.verts[tri[1]];
const auto& pC = mesh_data.verts[tri[2]];
ChVector<> pos = (pA + pB + pC) / 3;
states[it].pos = spindle_state.pos + spindle_rot * pos;
states[it].rot = spindle_state.rot;
states[it].pos_dt = spindle_state.lin_vel + Vcross(spindle_state.ang_vel, pos);
states[it].rot_dt = QNULL; //// TODO: angular velocity
}
// Update body states
m_system->SetBodyStates(tire_data.m_gids, states);
}
// Calculate barycentric coordinates (a1, a2, a3) for a given point P
// with respect to the triangle with vertices {v1, v2, v3}
ChVector<> ChVehicleCosimTerrainNodeGranularMPI::CalcBarycentricCoords(const ChVector<>& v1,
const ChVector<>& v2,
const ChVector<>& v3,
const ChVector<>& vP) {
ChVector<> v12 = v2 - v1;
ChVector<> v13 = v3 - v1;
ChVector<> v1P = vP - v1;
double d_12_12 = Vdot(v12, v12);
double d_12_13 = Vdot(v12, v13);
double d_13_13 = Vdot(v13, v13);
double d_1P_12 = Vdot(v1P, v12);
double d_1P_13 = Vdot(v1P, v13);
double denom = d_12_12 * d_13_13 - d_12_13 * d_12_13;
double a2 = (d_13_13 * d_1P_12 - d_12_13 * d_1P_13) / denom;
double a3 = (d_12_12 * d_1P_13 - d_12_13 * d_1P_12) / denom;
double a1 = 1 - a2 - a3;
return ChVector<>(a1, a2, a3);
}
// -----------------------------------------------------------------------------
// Collect contact forces on the (face) proxy bodies that are in contact.
// Load mesh vertex forces and corresponding indices.
// Note: Only the main terrain node needs to load output.
void ChVehicleCosimTerrainNodeGranularMPI::GetForcesMeshProxies(unsigned int i, MeshContact& mesh_contact) {
auto& mesh_data = m_mesh_data[i]; // mesh data for the i-th tire
auto& tire_data = m_tire_data[i]; // additional data for the i-th tire
// Gather contact forces on proxy bodies on the terrain master rank.
auto force_pairs = m_system->GetBodyContactForces(tire_data.m_gids);
if (m_rank != TERRAIN_NODE_RANK)
return;
// Maintain an unordered map of vertex indices and associated contact forces.
std::unordered_map<int, ChVector<>> my_map;
// Loop over all triangles that experienced contact and accumulate forces on adjacent vertices.
for (const auto& force_pair : force_pairs) {
auto gid = force_pair.first; // global ID of the proxy body
auto it = tire_data.m_map[gid]; // index of corresponding triangle
const auto& tri = mesh_data.idx_verts[it]; // triangle vertex indices
// Centroid has barycentric coordinates {1/3, 1/3, 1/3}, so force is distributed equally to the three vertices.
ChVector<> force = force_pair.second / 3;
// For each vertex of the triangle, if it appears in the map, increment the total contact force.
// Otherwise, insert a new entry in the map.
auto v1 = my_map.find(tri[0]);
if (v1 != my_map.end()) {
v1->second += force;
} else {
my_map[tri[0]] = force;
}
auto v2 = my_map.find(tri[1]);
if (v2 != my_map.end()) {
v2->second += force;
} else {
my_map[tri[1]] = force;
}
auto v3 = my_map.find(tri[2]);
if (v3 != my_map.end()) {
v3->second += force;
} else {
my_map[tri[2]] = force;
}
}
// Extract map keys (indices of vertices in contact) and map values (corresponding contact forces) and load output
// vectors. Note: could improve efficiency by reserving space for vectors.
mesh_contact.nv = 0;
for (const auto& kv : my_map) {
mesh_contact.vidx.push_back(kv.first);
mesh_contact.vforce.push_back(kv.second);
mesh_contact.nv++;
}
}
// Collect resultant contact force and torque on wheel proxy body.
// Note: Only the main terrain node needs to load output.
void ChVehicleCosimTerrainNodeGranularMPI::GetForceWheelProxy(unsigned int i, TerrainForce& wheel_contact) {
auto& mesh_data = m_mesh_data[i]; // mesh data for the i-th tire
auto& tire_data = m_tire_data[i]; // additional data for the i-th tire
// Gather contact forces on proxy bodies on the terrain master rank.
auto force_pairs = m_system->GetBodyContactForces(tire_data.m_gids);
if (m_rank != TERRAIN_NODE_RANK)
return;
// Current spindle body position
const auto& spindle_pos = m_spindle_state[i].pos;
// Loop over all triangles that experienced contact and accumulate forces on spindle.
wheel_contact.point = ChVector<>(0, 0, 0);
wheel_contact.force = ChVector<>(0, 0, 0);
wheel_contact.moment = ChVector<>(0, 0, 0);
for (const auto& force_pair : force_pairs) {
auto gid = force_pair.first; // global ID of the proxy body
auto it = tire_data.m_map[gid]; // index of corresponding triangle
const auto& tri = mesh_data.idx_verts[it]; // triangle vertex indices
const auto& force = force_pair.second; // force on proxy body
const auto& pA = mesh_data.verts[tri[0]];
const auto& pB = mesh_data.verts[tri[1]];
const auto& pC = mesh_data.verts[tri[2]];
ChVector<> pos = (pA + pB + pC) / 3; // local position of triangle on spindle body
wheel_contact.force += force;
wheel_contact.moment += Vcross(Vsub(pos, spindle_pos), force);
}
}
// -----------------------------------------------------------------------------
void ChVehicleCosimTerrainNodeGranularMPI::OnAdvance(double step_size) {
ChVehicleCosimTerrainNodeChrono::OnAdvance(step_size);
// Force a calculation of cumulative contact forces for all bodies in the system
// (needed at the next synchronization)
m_system->CalculateContactForces();
}
void ChVehicleCosimTerrainNodeGranularMPI::Render(double time) {
#ifdef CHRONO_OPENGL
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
if (gl_window.Active()) {
gl_window.Render();
} else {
MPI_Abort(MPI_COMM_WORLD, 1);
}
#endif
}
// -----------------------------------------------------------------------------
void ChVehicleCosimTerrainNodeGranularMPI::OnOutputData(int frame) {
// Create and write frame output file.
std::string filename = OutputFilename(m_node_out_dir + "/simulation", "simulation", "dat", frame + 1, 5);
//// TODO
}
void ChVehicleCosimTerrainNodeGranularMPI::WriteCheckpoint(const std::string& filename) const {
if (m_verbose)
cout << "[Terrain node] write checkpoint ===> CURRENTLY NOT IMPLEMENTED!" << endl;
//// TODO
}
} // end namespace vehicle
} // end namespace chrono
| 18,936 |
1,443 | <filename>users/moacirosa.json
{
"copyright": "<NAME>",
"url": "http://moacir.me",
"email": "<EMAIL>",
"format": "html",
"gravatar": true,
"theme": "double-windsor"
}
| 79 |
590 | package com.mploed.dddwithspring.scoring.appservices.repositories;
import com.mploed.dddwithspring.scoring.ApplicationNumber;
import com.mploed.dddwithspring.scoring.scoringResult.ScoringResultAggregate;
public interface ScoringResultRepository {
void save(ScoringResultAggregate scoringResultAggregate);
ScoringResultAggregate findByApplicationNumber(ApplicationNumber applicationNumber);
}
| 113 |
1,056 | /*
* 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.git.ui.diff;
import java.awt.BorderLayout;
import java.io.File;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.netbeans.modules.git.GitModuleConfig;
import org.netbeans.modules.git.ui.repository.RevisionDialogController;
import org.netbeans.modules.versioning.util.ExportDiffSupport;
import org.openide.DialogDescriptor;
import org.openide.util.HelpCtx;
/**
*
* @author ondra
*/
abstract class ExportCommit extends ExportDiffSupport {
private final ExportCommitPanel panel;
private AbstractExportDiffPanel aedp;
private DocumentListener listener;
private DialogDescriptor dd;
private final RevisionDialogController controller;
/** Creates a new instance of ExportDiff */
public ExportCommit (File repository, String preselectedRevision) {
super(new File[] { repository }, GitModuleConfig.getDefault().getPreferences());
controller = new RevisionDialogController(repository, new File[] { repository }, preselectedRevision);
panel = new ExportCommitPanel(controller.getPanel());
}
private void nameChange () {
if (aedp.getOutputFileText().trim().length() > 0) {
dd.setValid(true);
} else {
dd.setValid(false);
}
}
public String getOutputFileName () {
if (aedp == null) {
return null;
} else {
return aedp.getOutputFileText().trim();
}
}
public String getSelectionRevision() {
return controller.getRevision().getRevision();
}
@Override
protected AbstractExportDiffPanel createSimpleDialog (String currentFilePath) {
aedp = new ExportAsFilePanel();
listener = new DocumentListener() {
@Override
public void insertUpdate (DocumentEvent e) {
nameChange();
}
@Override
public void removeUpdate (DocumentEvent e) {
nameChange();
}
@Override
public void changedUpdate(DocumentEvent e) {
nameChange();
}
};
setInsidePanel(aedp);
dd = new DialogDescriptor(panel, org.openide.util.NbBundle.getMessage(ExportCommit.class, "CTL_ExportDialog")); // NOI18N
dd.setModal(true);
dd.setHelpCtx(new HelpCtx(this.getClass()));
dd.setValid(false);
aedp.addOutputFileTextDocumentListener(listener);
return aedp;
}
@Override
protected void createComplexDialog (AbstractExportDiffPanel insidePanel) {
setInsidePanel(insidePanel);
aedp = insidePanel;
dd = new DialogDescriptor(panel, org.openide.util.NbBundle.getMessage(ExportCommit.class, "CTL_ExportDialog")); // NOI18N
}
@Override
protected DialogDescriptor getDialogDescriptor () {
return dd;
}
private void setInsidePanel (AbstractExportDiffPanel aedp) {
panel.insidePanel.removeAll();
panel.insidePanel.setLayout(new BorderLayout());
panel.insidePanel.add(aedp, BorderLayout.CENTER);
}
}
| 1,450 |
3,428 | <filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-1/01933.340608a4c5e02c7f6fce00e78818da21.json
{"id":"01933","group":"easy-ham-1","checksum":{"type":"MD5","value":"340608a4c5e02c7f6fce00e78818da21"},"text":"From <EMAIL> Thu Sep 26 16:33:57 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>ass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 2E3F016F03\n\tfor <jm@localhost>; Thu, 26 Sep 2002 16:33:57 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 26 Sep 2002 16:33:57 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g8QFSBg24408 for\n <<EMAIL>>; Thu, 26 Sep 2002 16:28:11 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy@spamassass<EMAIL>int.org\nFrom: boingboing <<EMAIL>>\nSubject: Gearheads and bunnyhuggers in the OED\nDate: Thu, 26 Sep 2002 15:28:11 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://boingboing.net/#85494694\nDate: Not supplied\n\nSome of the words in the new shorter Oxford English Dictionary: \n\n Asylum seeker, economic migrant, bed-blocking, and stakeholder pension \n reflect the serious side of life; bunny-hugger (a conservationist or animal \n lover), chick flick (a film appealing to women), gearhead (a car \n enthusiast), and Grinch (a spoilsport or killjoy) are entries in a more \n light-hearted vein. Several entries are testaments to the popularity of \n science fiction, among them Tardis from the TV series Doctor Who, Jedi from \n Star Wars, and Klingon from Star Trek. \n\nLink[1] Discuss[2] (_Thanks, Mark!_)\n\n[1] http://www.askoxford.com/worldofwords/wordfrom/shorter/\n[2] http://www.quicktopic.com/boing/H/2tC5tCQqCRD3b\n\n\n"} | 732 |
645 | // Copyright 2013 Viewfinder. All rights reserved.
// Author: <NAME>.
#import "DBMigrationAndroid.h"
DBMigrationAndroid::DBMigrationAndroid(AppState* state, ProgressUpdateBlock progress_update)
: DBMigration(state, progress_update) {
}
DBMigrationAndroid::~DBMigrationAndroid() {
}
void DBMigrationAndroid::RunIOSMigration(
const char* min_ios_version, const char* max_ios_version,
const string& migration_key, migration_func migrator,
const DBHandle& updates) {
// IOS migrations are not run on Android.
}
void DBMigrationAndroid::RemoveLocalOnlyPhotos(const DBHandle& updates) {
}
void DBMigrationAndroid::ConvertAssetFingerprints(const DBHandle& updates) {
}
void DBMigrationAndroid::IndexPhotos(const DBHandle& updates) {
}
// local variables:
// mode: c++
// end:
| 249 |
14,668 | <filename>device/fido/filter.cc
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/fido/filter.h"
#include "base/feature_list.h"
#include "base/json/json_reader.h"
#include "base/metrics/field_trial_params.h"
#include "base/no_destructor.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "components/device_event_log/device_event_log.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace device {
namespace fido_filter {
namespace {
const base::Feature kFilter{"WebAuthenticationFilter",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::FeatureParam<std::string> kFilterJSON{
&kFilter,
"json",
"",
};
struct FilterStep {
absl::optional<std::string> operation;
std::vector<std::string> rp_id;
absl::optional<std::string> device;
absl::optional<std::string> id_type;
std::vector<std::string> id;
absl::optional<size_t> id_min_size;
absl::optional<size_t> id_max_size;
Action action;
};
bool IsString(const base::Value& v) {
return v.is_string();
}
bool IsNonEmptyString(const base::Value& v) {
return v.is_string() && !v.GetString().empty();
}
bool IsListOf(const base::Value* v, bool (*predicate)(const base::Value&)) {
if (!v->is_list()) {
return false;
}
auto contents = v->GetList();
return !contents.empty() &&
std::all_of(contents.begin(), contents.end(), predicate);
}
std::vector<std::string> GetStringOrListOfStrings(const base::Value* v) {
if (v->is_string()) {
return {v->GetString()};
}
std::vector<std::string> ret;
for (const auto& elem : v->GetList()) {
ret.push_back(elem.GetString());
}
return ret;
}
absl::optional<std::vector<FilterStep>> ParseJSON(base::StringPiece json) {
absl::optional<base::Value> v =
base::JSONReader::Read(json, base::JSON_ALLOW_TRAILING_COMMAS);
if (!v || !v->is_dict()) {
return absl::nullopt;
}
const base::Value* filters = v->FindKey("filters");
if (!filters || !filters->is_list()) {
return absl::nullopt;
}
std::vector<FilterStep> ret;
const auto filter_list = filters->GetList();
for (const auto& filter : filter_list) {
if (!filter.is_dict()) {
return absl::nullopt;
}
// These are the keys that are extracted from the JSON:
const base::Value* operation = nullptr;
const base::Value* rp_id = nullptr;
const base::Value* device = nullptr;
const base::Value* id_type = nullptr;
const base::Value* id = nullptr;
const base::Value* id_min_size = nullptr;
const base::Value* id_max_size = nullptr;
const base::Value* action = nullptr;
// DictItems is used so that unknown keys in the dictionary can be rejected.
for (auto pair : filter.DictItems()) {
if (pair.first == "operation") {
operation = &pair.second;
} else if (pair.first == "rp_id") {
rp_id = &pair.second;
} else if (pair.first == "device") {
device = &pair.second;
} else if (pair.first == "id_type") {
id_type = &pair.second;
} else if (pair.first == "id") {
id = &pair.second;
} else if (pair.first == "id_min_size") {
id_min_size = &pair.second;
} else if (pair.first == "id_max_size") {
id_max_size = &pair.second;
} else if (pair.first == "action") {
action = &pair.second;
} else {
// Unknown keys are an error.
return absl::nullopt;
}
}
if (!action || !IsNonEmptyString(*action) ||
(operation && !IsNonEmptyString(*operation)) ||
(rp_id && !IsNonEmptyString(*rp_id) &&
!IsListOf(rp_id, IsNonEmptyString)) ||
(device && !IsNonEmptyString(*device)) ||
(id_type && !IsNonEmptyString(*id_type)) ||
(id && !IsString(*id) && !IsListOf(id, IsString)) ||
(id_min_size && !id_min_size->is_int()) ||
(id_max_size && !id_max_size->is_int())) {
return absl::nullopt;
}
if ((id_min_size || id_max_size || id) && !id_type) {
// If matches on the contents or size of an ID are given then the type
// must also be matched.
return absl::nullopt;
}
if (!rp_id && !device) {
// Filter is too broad. For safety this is disallowed, although one can
// still explicitly use a wildcard.
return absl::nullopt;
}
FilterStep step;
const std::string& action_str = action->GetString();
if (action_str == "allow") {
step.action = Action::ALLOW;
} else if (action_str == "block") {
step.action = Action::BLOCK;
} else if (action_str == "no-attestation") {
step.action = Action::NO_ATTESTATION;
} else {
return absl::nullopt;
}
if (operation) {
step.operation = operation->GetString();
}
if (rp_id) {
step.rp_id = GetStringOrListOfStrings(rp_id);
}
if (device) {
step.device = device->GetString();
}
if (id_type) {
step.id_type = id_type->GetString();
}
if (id) {
step.id = GetStringOrListOfStrings(id);
}
if (id_min_size) {
const int min_size_int = id_min_size->GetInt();
if (min_size_int < 0) {
return absl::nullopt;
}
step.id_min_size = min_size_int;
}
if (id_max_size) {
const int max_size_int = id_max_size->GetInt();
if (max_size_int < 0) {
return absl::nullopt;
}
step.id_max_size = max_size_int;
}
ret.emplace_back(std::move(step));
}
return ret;
}
const char* OperationToString(Operation op) {
switch (op) {
case Operation::MAKE_CREDENTIAL:
return "mc";
case Operation::GET_ASSERTION:
return "ga";
}
}
const char* IDTypeToString(IDType id_type) {
switch (id_type) {
case IDType::CREDENTIAL_ID:
return "cred";
case IDType::USER_ID:
return "user";
}
}
size_t g_testing_depth = 0;
struct CurrentFilter {
absl::optional<std::vector<FilterStep>> steps;
absl::optional<std::string> json;
};
CurrentFilter* GetCurrentFilter() {
static base::NoDestructor<CurrentFilter> current_filter;
return current_filter.get();
}
bool MaybeParseFilter(base::StringPiece json) {
CurrentFilter* const current_filter = GetCurrentFilter();
if (current_filter->json && json == *current_filter->json) {
return true;
}
if (json.size() == 0) {
current_filter->steps.reset();
current_filter->json = "";
return true;
}
current_filter->steps = ParseJSON(json);
if (!current_filter->steps) {
current_filter->json.reset();
return false;
}
current_filter->json = std::string(json);
return true;
}
} // namespace
void MaybeInitialize() {
if (g_testing_depth != 0) {
return;
}
const std::string& json = kFilterJSON.Get();
if (!MaybeParseFilter(json)) {
FIDO_LOG(ERROR) << "Failed to parse filter JSON. Failing open.";
}
}
Action Evaluate(
Operation op,
base::StringPiece rp_id,
absl::optional<base::StringPiece> device,
absl::optional<std::pair<IDType, base::span<const uint8_t>>> id) {
CurrentFilter* const current_filter = GetCurrentFilter();
if (!current_filter->steps) {
return Action::ALLOW;
}
absl::optional<std::string> id_hex;
if (id) {
id_hex = base::HexEncode(id->second);
}
for (const auto& filter : *current_filter->steps) {
if ((!filter.operation ||
base::MatchPattern(OperationToString(op), *filter.operation)) &&
(filter.rp_id.empty() ||
std::any_of(filter.rp_id.begin(), filter.rp_id.end(),
[rp_id](const std::string& pattern) -> bool {
return base::MatchPattern(rp_id, pattern);
})) &&
(!filter.device ||
base::MatchPattern(device.value_or(""), *filter.device)) &&
(!filter.id_type || (id && base::MatchPattern(IDTypeToString(id->first),
*filter.id_type))) &&
(!filter.id_min_size ||
(id && *filter.id_min_size <= id->second.size())) &&
(!filter.id_max_size ||
(id && *filter.id_max_size >= id->second.size())) &&
(filter.id.empty() ||
(id_hex && std::any_of(filter.id.begin(), filter.id.end(),
[&id_hex](const std::string& pattern) -> bool {
return base::MatchPattern(*id_hex, pattern);
})))) {
return filter.action;
}
}
return Action::ALLOW;
}
ScopedFilterForTesting::ScopedFilterForTesting(base::StringPiece json)
: previous_json_(GetCurrentFilter()->json) {
g_testing_depth++;
CHECK(g_testing_depth != 0);
CHECK(MaybeParseFilter(json)) << json;
}
ScopedFilterForTesting::ScopedFilterForTesting(
base::StringPiece json,
ScopedFilterForTesting::PermitInvalidJSON)
: previous_json_(GetCurrentFilter()->json) {
g_testing_depth++;
CHECK(g_testing_depth != 0);
MaybeParseFilter(json);
}
ScopedFilterForTesting::~ScopedFilterForTesting() {
CurrentFilter* const current_filter = GetCurrentFilter();
current_filter->steps.reset();
current_filter->json.reset();
g_testing_depth--;
if (previous_json_) {
CHECK(MaybeParseFilter(*previous_json_));
}
}
bool ParseForTesting(base::StringPiece json) {
CHECK(base::JSONReader::Read(json, base::JSON_ALLOW_TRAILING_COMMAS)) << json;
return MaybeParseFilter(json);
}
} // namespace fido_filter
} // namespace device
| 3,986 |
1,224 | // ================================================================================================
// TBXML.h
// Fast processing of XML files
//
// ================================================================================================
// Created by <NAME> on 21/10/2009.
// Version 1.5
//
// Copyright 2012 71Squared All rights reserved.b
//
// 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.
// ================================================================================================
@class TBXML;
// ================================================================================================
// Error Codes
// ================================================================================================
enum TBXMLErrorCodes {
D_TBXML_SUCCESS = 0,
D_TBXML_DATA_NIL,
D_TBXML_DECODE_FAILURE,
D_TBXML_MEMORY_ALLOC_FAILURE,
D_TBXML_FILE_NOT_FOUND_IN_BUNDLE,
D_TBXML_ELEMENT_IS_NIL,
D_TBXML_ELEMENT_NAME_IS_NIL,
D_TBXML_ELEMENT_NOT_FOUND,
D_TBXML_ELEMENT_TEXT_IS_NIL,
D_TBXML_ATTRIBUTE_IS_NIL,
D_TBXML_ATTRIBUTE_NAME_IS_NIL,
D_TBXML_ATTRIBUTE_NOT_FOUND,
D_TBXML_PARAM_NAME_IS_NIL
};
// ================================================================================================
// Defines
// ================================================================================================
#define D_TBXML_DOMAIN @"com.71squared.tbxml"
#define MAX_ELEMENTS 100
#define MAX_ATTRIBUTES 100
#define TBXML_ATTRIBUTE_NAME_START 0
#define TBXML_ATTRIBUTE_NAME_END 1
#define TBXML_ATTRIBUTE_VALUE_START 2
#define TBXML_ATTRIBUTE_VALUE_END 3
#define TBXML_ATTRIBUTE_CDATA_END 4
// ================================================================================================
// Structures
// ================================================================================================
/** The TBXMLAttribute structure holds information about a single XML attribute. The structure holds the attribute name, value and next sibling attribute. This structure allows us to create a linked list of attributes belonging to a specific element.
*/
typedef struct _TBXMLAttribute {
char * name;
char * value;
struct _TBXMLAttribute * next;
} TBXMLAttribute;
/** The TBXMLElement structure holds information about a single XML element. The structure holds the element name & text along with pointers to the first attribute, parent element, first child element and first sibling element. Using this structure, we can create a linked list of TBXMLElements to map out an entire XML file.
*/
typedef struct _TBXMLElement {
char * name;
char * text;
TBXMLAttribute * firstAttribute;
struct _TBXMLElement * parentElement;
struct _TBXMLElement * firstChild;
struct _TBXMLElement * currentChild;
struct _TBXMLElement * nextSibling;
struct _TBXMLElement * previousSibling;
} TBXMLElement;
/** The TBXMLElementBuffer is a structure that holds a buffer of TBXMLElements. When the buffer of elements is used, an additional buffer is created and linked to the previous one. This allows for efficient memory allocation/deallocation elements.
*/
typedef struct _TBXMLElementBuffer {
TBXMLElement * elements;
struct _TBXMLElementBuffer * next;
struct _TBXMLElementBuffer * previous;
} TBXMLElementBuffer;
/** The TBXMLAttributeBuffer is a structure that holds a buffer of TBXMLAttributes. When the buffer of attributes is used, an additional buffer is created and linked to the previous one. This allows for efficient memeory allocation/deallocation of attributes.
*/
typedef struct _TBXMLAttributeBuffer {
TBXMLAttribute * attributes;
struct _TBXMLAttributeBuffer * next;
struct _TBXMLAttributeBuffer * previous;
} TBXMLAttributeBuffer;
// ================================================================================================
// Block Callbacks
// ================================================================================================
typedef void (^TBXMLSuccessBlock)(TBXML *tbxml);
typedef void (^TBXMLFailureBlock)(TBXML *tbxml, NSError *error);
typedef void (^TBXMLIterateBlock)(TBXMLElement *element);
typedef void (^TBXMLIterateAttributeBlock)(TBXMLAttribute *attribute, NSString *attributeName, NSString *attributeValue);
// ================================================================================================
// TBXML Public Interface
// ================================================================================================
@interface TBXML : NSObject {
@private
TBXMLElement * rootXMLElement;
TBXMLElementBuffer * currentElementBuffer;
TBXMLAttributeBuffer * currentAttributeBuffer;
long currentElement;
long currentAttribute;
char * bytes;
long bytesLength;
}
@property (nonatomic, readonly) TBXMLElement * rootXMLElement;
+ (id)newTBXMLWithXMLString:(NSString*)aXMLString error:(NSError **)error;
+ (id)newTBXMLWithXMLData:(NSData*)aData error:(NSError **)error;
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile error:(NSError **)error;
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension error:(NSError **)error;
+ (id)newTBXMLWithXMLString:(NSString*)aXMLString __attribute__((deprecated));
+ (id)newTBXMLWithXMLData:(NSData*)aData __attribute__((deprecated));
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile __attribute__((deprecated));
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension __attribute__((deprecated));
- (id)initWithXMLString:(NSString*)aXMLString error:(NSError **)error;
- (id)initWithXMLData:(NSData*)aData error:(NSError **)error;
- (id)initWithXMLFile:(NSString*)aXMLFile error:(NSError **)error;
- (id)initWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension error:(NSError **)error;
- (id)initWithXMLString:(NSString*)aXMLString __attribute__((deprecated));
- (id)initWithXMLData:(NSData*)aData __attribute__((deprecated));
- (id)initWithXMLFile:(NSString*)aXMLFile __attribute__((deprecated));
- (id)initWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension __attribute__((deprecated));
- (int) decodeData:(NSData*)data;
- (int) decodeData:(NSData*)data withError:(NSError **)error;
@end
// ================================================================================================
// TBXML Static Functions Interface
// ================================================================================================
@interface TBXML (StaticFunctions)
+ (NSString*) elementName:(TBXMLElement*)aXMLElement;
+ (NSString*) elementName:(TBXMLElement*)aXMLElement error:(NSError **)error;
+ (NSString*) textForElement:(TBXMLElement*)aXMLElement;
+ (NSString*) textForElement:(TBXMLElement*)aXMLElement error:(NSError **)error;
+ (NSString*) valueOfAttributeNamed:(NSString *)aName forElement:(TBXMLElement*)aXMLElement;
+ (NSString*) valueOfAttributeNamed:(NSString *)aName forElement:(TBXMLElement*)aXMLElement error:(NSError **)error;
+ (NSString*) attributeName:(TBXMLAttribute*)aXMLAttribute;
+ (NSString*) attributeName:(TBXMLAttribute*)aXMLAttribute error:(NSError **)error;
+ (NSString*) attributeValue:(TBXMLAttribute*)aXMLAttribute;
+ (NSString*) attributeValue:(TBXMLAttribute*)aXMLAttribute error:(NSError **)error;
+ (TBXMLElement*) nextSiblingNamed:(NSString*)aName searchFromElement:(TBXMLElement*)aXMLElement;
+ (TBXMLElement*) childElementNamed:(NSString*)aName parentElement:(TBXMLElement*)aParentXMLElement;
+ (TBXMLElement*) nextSiblingNamed:(NSString*)aName searchFromElement:(TBXMLElement*)aXMLElement error:(NSError **)error;
+ (TBXMLElement*) childElementNamed:(NSString*)aName parentElement:(TBXMLElement*)aParentXMLElement error:(NSError **)error;
/** Iterate through all elements found using query.
Inspiration taken from <NAME>'s RaptureXML https://github.com/ZaBlanc/RaptureXML
*/
+ (void)iterateElementsForQuery:(NSString *)query fromElement:(TBXMLElement *)anElement withBlock:(TBXMLIterateBlock)iterateBlock;
+ (void)iterateAttributesOfElement:(TBXMLElement *)anElement withBlock:(TBXMLIterateAttributeBlock)iterateBlock;
@end
| 2,668 |
372 | <gh_stars>100-1000
/* -*- mode: c++; -*-
*-----------------------------------------------------------------------------
* $RCSfile: SoapDef.h,v $
*
* See Copyright for the status of this software.
*
* The OpenSOAP Project
* http://opensoap.jp/
*-----------------------------------------------------------------------------
*/
#ifndef SoapDef_H
#define SoapDef_H
#include <string>
#include <OpenSOAP/Defines.h>
namespace OpenSOAP {
namespace XMLDef {
extern const std::string OPENSOAP_VAR
XMLNS;
}
namespace SoapTag {
extern const std::string OPENSOAP_VAR
ENVELOPE;
extern const std::string OPENSOAP_VAR
HEADER;
extern const std::string OPENSOAP_VAR
BODY;
}
namespace SoapNamespace {
extern const std::string OPENSOAP_VAR
SOAP_ENV;
extern const std::string OPENSOAP_VAR
SOAP_ENV_PREFIX;
}
namespace ExtSoapHeaderTag {
extern const std::string OPENSOAP_VAR
OPENSOAP_HEADER_BLOCK;
extern const std::string OPENSOAP_VAR
MESSAGE_ID;
extern const std::string OPENSOAP_VAR
ASYNC;
extern const std::string OPENSOAP_VAR
FORWARDER;
extern const std::string OPENSOAP_VAR
FORWARD_PATH;
extern const std::string OPENSOAP_VAR
HOPCOUNT;
extern const std::string OPENSOAP_VAR
RECEIVED_PATH;
extern const std::string OPENSOAP_VAR
URL;
extern const std::string OPENSOAP_VAR
TIME;
extern const std::string OPENSOAP_VAR
BACKWARD_PATH;
extern const std::string OPENSOAP_VAR
TTL;
extern const std::string OPENSOAP_VAR
RESPONSE_MSG;
extern const std::string OPENSOAP_VAR
UNDELETE;
extern const std::string OPENSOAP_VAR
IN;
}
namespace ExtSoapHeaderNamespace {
extern const std::string OPENSOAP_VAR
OPENSOAP_HEADER;
extern const std::string OPENSOAP_VAR
OPENSOAP_HEADER_PREFIX;
}
namespace ExtSoapHeaderAttributes {
extern const std::string OPENSOAP_VAR
SECOND;
extern const std::string OPENSOAP_VAR
HOPTIMES;
extern const std::string OPENSOAP_VAR
ASYNCSECOND;
extern const std::string OPENSOAP_VAR
TYPE;
extern const std::string OPENSOAP_VAR
COUNT;
}
namespace ExtSoapTag {
extern const std::string OPENSOAP_VAR
RESULT;
}
namespace ExtSoapNamespace {
extern const std::string OPENSOAP_VAR
RESULT;
extern const std::string OPENSOAP_VAR
RESULT_PREFIX;
}
namespace FaultElement {
extern const std::string OPENSOAP_VAR
FAULT_CLIENT;
extern const std::string OPENSOAP_VAR
FAULT_SERVER;
}
}
#endif //SoapDef_H
| 1,327 |
688 | <filename>Python/libraries/recognizers-date-time/recognizers_date_time/date_time/spanish/holiday_parser_config.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Dict, Callable
from datetime import datetime
from recognizers_text.utilities import RegExpUtility
from ..utilities import DateUtils, HolidayFunctions
from ..base_holiday import BaseHolidayParserConfiguration
from ...resources.spanish_date_time import SpanishDateTime
class SpanishHolidayParserConfiguration(BaseHolidayParserConfiguration):
@property
def holiday_names(self) -> Dict[str, List[str]]:
return self._holiday_names
@property
def holiday_regex_list(self) -> List[str]:
return self._holiday_regexes
@property
def holiday_func_dictionary(self) -> Dict[str, Callable[[int], datetime]]:
return self._holiday_func_dictionary
def __init__(self, config):
super().__init__()
self._holiday_regexes = [
RegExpUtility.get_safe_reg_exp(SpanishDateTime.HolidayRegex1),
RegExpUtility.get_safe_reg_exp(SpanishDateTime.HolidayRegex2),
RegExpUtility.get_safe_reg_exp(SpanishDateTime.HolidayRegex3)
]
self._holiday_names = SpanishDateTime.HolidayNames
self._variable_holidays_timex_dictionary = SpanishDateTime.VariableHolidaysTimexDictionary
self.next_prefix_regex = RegExpUtility.get_safe_reg_exp(
SpanishDateTime.NextPrefixRegex)
self.previous_prefix_regex = RegExpUtility.get_safe_reg_exp(
SpanishDateTime.PreviousPrefixRegex)
self.this_prefix_regex = RegExpUtility.get_safe_reg_exp(
SpanishDateTime.ThisPrefixRegex)
def _init_holiday_funcs(self) -> Dict[str, Callable[[int], datetime]]:
local = dict([
('padres', SpanishHolidayParserConfiguration.fathers_day),
('madres', SpanishHolidayParserConfiguration.mothers_day),
('acciondegracias', SpanishHolidayParserConfiguration.thanksgiving_day),
('trabajador', SpanishHolidayParserConfiguration.international_workers_day),
('delaraza', SpanishHolidayParserConfiguration.columbus_day),
('memoria', SpanishHolidayParserConfiguration.memorial_day),
('pascuas', SpanishHolidayParserConfiguration.easter_day),
('navidad', SpanishHolidayParserConfiguration.christmas_day),
('nochebuena', SpanishHolidayParserConfiguration.christmas_eve),
('añonuevo', SpanishHolidayParserConfiguration.new_year),
('nochevieja', SpanishHolidayParserConfiguration.new_year_eve),
('yuandan', SpanishHolidayParserConfiguration.new_year),
('maestro', SpanishHolidayParserConfiguration.teacher_day),
('todoslossantos', SpanishHolidayParserConfiguration.halloween_day),
('niño', SpanishHolidayParserConfiguration.children_day),
('mujer', SpanishHolidayParserConfiguration.female_day)
])
return {**super()._init_holiday_funcs(), **local}
@staticmethod
def new_year(year: int) -> datetime:
return datetime(year, 1, 1)
@staticmethod
def new_year_eve(year: int) -> datetime:
return datetime(year, 12, 31)
@staticmethod
def christmas_day(year: int) -> datetime:
return datetime(year, 12, 25)
@staticmethod
def christmas_eve(year: int) -> datetime:
return datetime(year, 12, 24)
@staticmethod
def female_day(year: int) -> datetime:
return datetime(year, 3, 8)
@staticmethod
def children_day(year: int) -> datetime:
return datetime(year, 6, 1)
@staticmethod
def halloween_day(year: int) -> datetime:
return datetime(year, 10, 31)
@staticmethod
def teacher_day(year: int) -> datetime:
return datetime(year, 9, 11)
@staticmethod
def easter_day(year: int) -> datetime:
return HolidayFunctions.calculate_holiday_by_easter(year)
def get_swift_year(self, text: str) -> int:
trimmed_text = text.strip().lower()
swift = -10
if self.next_prefix_regex.search(trimmed_text):
swift = 1
if self.previous_prefix_regex.search(trimmed_text):
swift = -1
if self.this_prefix_regex.search(trimmed_text):
swift = 0
return swift
def sanitize_holiday_token(self, holiday: str) -> str:
return holiday.replace(' ', '').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u')
| 1,833 |
816 | <filename>src/validator/FetchEdgesValidator.cpp
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "validator/FetchEdgesValidator.h"
#include "planner/plan/Query.h"
#include "util/ExpressionUtils.h"
#include "util/SchemaUtil.h"
namespace nebula {
namespace graph {
/*static*/ const std::unordered_set<std::string> FetchEdgesValidator::reservedProperties{
kSrc,
kType,
kRank,
kDst,
};
Status FetchEdgesValidator::validateImpl() {
props_ = std::make_unique<std::vector<EdgeProp>>();
exprs_ = std::make_unique<std::vector<Expr>>();
NG_RETURN_IF_ERROR(check());
NG_RETURN_IF_ERROR(prepareEdges());
NG_RETURN_IF_ERROR(prepareProperties());
return Status::OK();
}
Status FetchEdgesValidator::toPlan() {
// Start [-> some input] -> GetEdges [-> Project] [-> Dedup] [-> next stage] -> End
std::string edgeKeysVar = (srcRef_ == nullptr ? buildConstantInput() : buildRuntimeInput());
auto *getEdgesNode = GetEdges::make(qctx_,
nullptr,
spaceId_,
src_,
type_,
rank_,
dst_,
std::move(props_),
std::move(exprs_),
dedup_,
limit_,
std::move(orderBy_),
std::move(filter_));
getEdgesNode->setInputVar(edgeKeysVar);
getEdgesNode->setColNames(geColNames_);
// the pipe will set the input variable
PlanNode *current = getEdgesNode;
// filter when the edge key is empty which means not exists edge in fact
auto *notExistEdgeFilter = Filter::make(qctx_, current, emptyEdgeKeyFilter());
notExistEdgeFilter->setColNames(geColNames_);
current = notExistEdgeFilter;
if (withYield_) {
current = Project::make(qctx_, current, newYield_->yields());
// Project select the properties then dedup
if (dedup_) {
current = Dedup::make(qctx_, current);
// the framework will add data collect to collect the result
// if the result is required
}
} else {
auto *columns = qctx_->objPool()->add(new YieldColumns());
auto *pool = qctx_->objPool();
columns->addColumn(new YieldColumn(EdgeExpression::make(pool), "edges_"));
current = Project::make(qctx_, current, columns);
}
root_ = current;
tail_ = getEdgesNode;
return Status::OK();
}
Status FetchEdgesValidator::check() {
auto *sentence = static_cast<FetchEdgesSentence *>(sentence_);
if (sentence->edgeSize() > 1) {
return Status::SemanticError("Only allow fetch on one edge.");
}
spaceId_ = vctx_->whichSpace().id;
edgeTypeName_ = *sentence->edge();
auto edgeStatus = qctx_->schemaMng()->toEdgeType(spaceId_, edgeTypeName_);
NG_RETURN_IF_ERROR(edgeStatus);
edgeType_ = edgeStatus.value();
schema_ = qctx_->schemaMng()->getEdgeSchema(spaceId_, edgeType_);
if (schema_ == nullptr) {
LOG(ERROR) << "No schema found for " << sentence->edge();
return Status::SemanticError("No schema found for `%s'", sentence->edge()->c_str());
}
return Status::OK();
}
Status FetchEdgesValidator::prepareEdges() {
auto *sentence = static_cast<FetchEdgesSentence *>(sentence_);
// from ref, eval in execute
if (sentence->isRef()) {
srcRef_ = sentence->ref()->srcid();
auto result = checkRef(srcRef_, vidType_);
NG_RETURN_IF_ERROR(result);
inputVar_ = std::move(result).value();
rankRef_ = sentence->ref()->rank();
if (rankRef_->kind() != Expression::Kind::kConstant) {
result = checkRef(rankRef_, Value::Type::INT);
NG_RETURN_IF_ERROR(result);
if (inputVar_ != result.value()) {
return Status::SemanticError(
"Can't refer to different variable as key at same time.");
}
}
dstRef_ = sentence->ref()->dstid();
result = checkRef(dstRef_, vidType_);
NG_RETURN_IF_ERROR(result);
if (inputVar_ != result.value()) {
return Status::SemanticError("Can't refer to different variable as key at same time.");
}
return Status::OK();
}
// from constant, eval now
QueryExpressionContext dummy(nullptr);
auto keysPointer = sentence->keys();
if (keysPointer != nullptr) {
auto keys = keysPointer->keys();
// row: _src, _type, _ranking, _dst
edgeKeys_.rows.reserve(keys.size());
for (const auto &key : keys) {
DCHECK(ExpressionUtils::isConstExpr(key->srcid()));
auto src = key->srcid()->eval(dummy);
if (src.type() != vidType_) {
std::stringstream ss;
ss << "the src should be type of " << vidType_ << ", but was`" << src.type() << "'";
return Status::SemanticError(ss.str());
}
auto ranking = key->rank();
DCHECK(ExpressionUtils::isConstExpr(key->dstid()));
auto dst = key->dstid()->eval(dummy);
if (dst.type() != vidType_) {
std::stringstream ss;
ss << "the dst should be type of " << vidType_ << ", but was`" << dst.type() << "'";
return Status::SemanticError(ss.str());
}
edgeKeys_.emplace_back(nebula::Row({std::move(src), ranking, std::move(dst)}));
}
}
return Status::OK();
}
Status FetchEdgesValidator::prepareProperties() {
auto *sentence = static_cast<FetchEdgesSentence *>(sentence_);
auto *yield = sentence->yieldClause();
// empty for all properties
if (yield != nullptr) {
return preparePropertiesWithYield(yield);
} else {
return preparePropertiesWithoutYield();
}
}
Status FetchEdgesValidator::preparePropertiesWithYield(const YieldClause *yield) {
withYield_ = true;
storage::cpp2::EdgeProp prop;
prop.set_type(edgeType_);
// insert the reserved properties expression be compatible with 1.0
auto *pool = qctx_->objPool();
auto *newYieldColumns = new YieldColumns();
newYieldColumns->addColumn(new YieldColumn(EdgeSrcIdExpression::make(pool, edgeTypeName_)));
newYieldColumns->addColumn(new YieldColumn(EdgeDstIdExpression::make(pool, edgeTypeName_)));
newYieldColumns->addColumn(new YieldColumn(EdgeRankExpression::make(pool, edgeTypeName_)));
for (auto col : yield->columns()) {
newYieldColumns->addColumn(col->clone().release());
}
newYield_ = qctx_->objPool()->add(new YieldClause(newYieldColumns, yield->isDistinct()));
auto newYieldSize = newYield_->columns().size();
outputs_.reserve(newYieldSize);
std::vector<std::string> propsName;
propsName.reserve(newYield_->columns().size());
dedup_ = newYield_->isDistinct();
for (auto col : newYield_->columns()) {
col->setExpr(ExpressionUtils::rewriteLabelAttr2EdgeProp(col->expr()));
NG_RETURN_IF_ERROR(invalidLabelIdentifiers(col->expr()));
const auto *invalidExpr = findInvalidYieldExpression(col->expr());
if (invalidExpr != nullptr) {
return Status::SemanticError("Invalid newYield_ expression `%s'.",
col->expr()->toString().c_str());
}
// The properties from storage directly push down only
// The other will be computed in Project Executor
const auto storageExprs = ExpressionUtils::findAllStorage(col->expr());
for (const auto &storageExpr : storageExprs) {
const auto *expr = static_cast<const PropertyExpression *>(storageExpr);
if (expr->sym() != edgeTypeName_) {
return Status::SemanticError("Mismatched edge type name");
}
// Check is prop name in schema
if (schema_->getFieldIndex(expr->prop()) < 0 &&
reservedProperties.find(expr->prop()) == reservedProperties.end()) {
LOG(ERROR) << "Unknown column `" << expr->prop() << "' in edge `" << edgeTypeName_
<< "'.";
return Status::SemanticError("Unknown column `%s' in edge `%s'",
expr->prop().c_str(),
edgeTypeName_.c_str());
}
propsName.emplace_back(expr->prop());
geColNames_.emplace_back(expr->sym() + "." + expr->prop());
}
auto typeResult = deduceExprType(col->expr());
NG_RETURN_IF_ERROR(typeResult);
outputs_.emplace_back(col->name(), typeResult.value());
// TODO(shylock) think about the push-down expr
}
prop.set_props(std::move(propsName));
props_->emplace_back(std::move(prop));
return Status::OK();
}
Status FetchEdgesValidator::preparePropertiesWithoutYield() {
// no yield
outputs_.emplace_back("edges_", Value::Type::EDGE);
storage::cpp2::EdgeProp prop;
prop.set_type(edgeType_);
std::vector<std::string> propNames; // filter the type
propNames.reserve(4 + schema_->getNumFields());
geColNames_.reserve(4 + schema_->getNumFields());
// insert the reserved properties be compatible with 1.0
// kSrc
propNames.emplace_back(kSrc);
geColNames_.emplace_back(edgeTypeName_ + "." + kSrc);
// kDst
propNames.emplace_back(kDst);
geColNames_.emplace_back(edgeTypeName_ + "." + kDst);
// kRank
propNames.emplace_back(kRank);
geColNames_.emplace_back(edgeTypeName_ + "." + kRank);
// kType
propNames.emplace_back(kType);
geColNames_.emplace_back(edgeTypeName_ + "." + kType);
for (std::size_t i = 0; i < schema_->getNumFields(); ++i) {
propNames.emplace_back(schema_->getFieldName(i));
geColNames_.emplace_back(edgeTypeName_ + "." + schema_->getFieldName(i));
}
prop.set_props(std::move(propNames));
props_->emplace_back(std::move(prop));
return Status::OK();
}
/*static*/
const Expression *FetchEdgesValidator::findInvalidYieldExpression(const Expression *root) {
return ExpressionUtils::findAny(root,
{Expression::Kind::kInputProperty,
Expression::Kind::kVarProperty,
Expression::Kind::kSrcProperty,
Expression::Kind::kDstProperty});
}
// TODO(shylock) optimize dedup input when distinct given
std::string FetchEdgesValidator::buildConstantInput() {
auto pool = qctx_->objPool();
auto input = vctx_->anonVarGen()->getVar();
qctx_->ectx()->setResult(input, ResultBuilder().value(Value(std::move(edgeKeys_))).finish());
src_ = VariablePropertyExpression::make(pool, input, kSrc);
type_ = ConstantExpression::make(pool, edgeType_);
rank_ = VariablePropertyExpression::make(pool, input, kRank);
dst_ = VariablePropertyExpression::make(pool, input, kDst);
return input;
}
std::string FetchEdgesValidator::buildRuntimeInput() {
auto pool = qctx_->objPool();
src_ = DCHECK_NOTNULL(srcRef_);
type_ = ConstantExpression::make(pool, edgeType_);
rank_ = DCHECK_NOTNULL(rankRef_);
dst_ = DCHECK_NOTNULL(dstRef_);
return inputVar_;
}
Expression *FetchEdgesValidator::emptyEdgeKeyFilter() {
// _src != empty && _dst != empty && _rank != empty
DCHECK_GE(geColNames_.size(), 3);
auto *pool = qctx_->objPool();
auto *srcNotEmptyExpr = notEmpty(EdgeSrcIdExpression::make(pool, edgeTypeName_));
auto *dstNotEmptyExpr = notEmpty(EdgeDstIdExpression::make(pool, edgeTypeName_));
auto *rankNotEmptyExpr = notEmpty(EdgeRankExpression::make(pool, edgeTypeName_));
auto *edgeKeyNotEmptyExpr = lgAnd(srcNotEmptyExpr, lgAnd(dstNotEmptyExpr, rankNotEmptyExpr));
return edgeKeyNotEmptyExpr;
}
} // namespace graph
} // namespace nebula
| 5,437 |
396 | package com.ibm.webapi.data;
import java.util.List;
import com.ibm.webapi.business.CoreArticle;
import com.ibm.webapi.business.InvalidArticle;
public interface ArticlesDataAccess {
public CoreArticle addArticle(CoreArticle article) throws NoConnectivity, InvalidArticle;
public List<CoreArticle> getArticles(int amount) throws NoConnectivity;
} | 105 |
578 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <deque>
#include <mutex>
#include <set>
#include "cachelib/navy/block_cache/EvictionPolicy.h"
namespace facebook {
namespace cachelib {
namespace navy {
namespace detail {
struct Node {
const RegionId rid{};
// Indicate when this region was initially tracked
const std::chrono::seconds trackTime{};
std::chrono::seconds secondsSinceTracking() const {
return getSteadyClockSeconds() - trackTime;
}
};
} // namespace detail
// Simple FIFO policy
class FifoPolicy final : public EvictionPolicy {
public:
FifoPolicy();
FifoPolicy(const FifoPolicy&) = delete;
FifoPolicy& operator=(const FifoPolicy&) = delete;
~FifoPolicy() override = default;
void touch(RegionId /* rid */) override {}
// Adds a new region to the queue for tracking.
void track(const Region& region) override;
// Evicts the first added region and stops tracking.
RegionId evict() override;
// Resets FIFO policy to the initial state.
void reset() override;
// Gets memory used by FIFO policy.
size_t memorySize() const override {
std::lock_guard<std::mutex> lock{mutex_};
return sizeof(*this) + sizeof(detail::Node) * queue_.size();
}
// Exports FIFO policy stats via CounterVisitor.
void getCounters(const CounterVisitor& v) const override;
// Persists metadata associated with FIFO policy.
void persist(RecordWriter& rw) const override;
// Recovers from previously persisted metadata associated with FIFO policy.
void recover(RecordReader& rr) override;
private:
std::deque<detail::Node> queue_;
mutable std::mutex mutex_;
};
// Segmented FIFO policy
//
// It divides the fifo queue into N segments. Each segment holds
// number of items proportional to its segment ratio. For example,
// if we have 3 segments and the ratio of [2, 1, 1], the lowest
// priority segment will hold 50% of the items whereas the other
// two higher priority segments will hold 25% each.
//
// On insertion, a priority is used as an Insertion Point. E.g. a pri-2
// region will be inserted into the third highest priority segment. After
// the insertion is completed, we will trigger rebalance, where this
// region may be moved to below the insertion point, if the segment it
// was originally inserted into had exceeded the size allowed by its ratio.
//
// Our rebalancing scheme allows the lowest priority segment to grow beyond
// its ratio allows for, since there is no lower segment to move into.
//
// Also note that rebalancing is also triggered after an eviction.
//
// The rate of inserting new regions look like the following:
// Pri-2 ---
// \
// Pri-1 -------
// \
// Pri-0 ------------
// When pri-2 exceeds its ratio, it effectively downgrades the oldest region in
// pri-2 to pri-1, and that region is now pushed down at the combined rate of
// (new pri-1 regions + new pri-2 regions), so effectively it gets evicted out
// of the system faster once it is beyond the pri-2 segment ratio. Segment
// ratio is put in place to prevent the lower segments getting so small a
// portion of the flash device.
class SegmentedFifoPolicy final : public EvictionPolicy {
public:
// @segmentRatio ratio of the size of each segment. Size of this param also
// indicates the number of segments in the sfifo. This cannot
// be empty.
explicit SegmentedFifoPolicy(std::vector<unsigned int> segmentRatio);
SegmentedFifoPolicy(const SegmentedFifoPolicy&) = delete;
SegmentedFifoPolicy& operator=(const SegmentedFifoPolicy&) = delete;
~SegmentedFifoPolicy() override = default;
void touch(RegionId /* rid */) override {}
// Adds a new region to the segments for tracking.
void track(const Region& region) override;
// Evicts the region with the lowest priority and stops tracking.
RegionId evict() override;
// Resets Segmented FIFO policy to the initial state.
void reset() override;
// Gets memory used by Segmented FIFO policy.
size_t memorySize() const override;
// Exports Segmented FIFO policy stats via CounterVisitor.
void getCounters(const CounterVisitor& v) const override;
// Persists metadata associated with segmented FIFO policy.
void persist(RecordWriter& rw) const override;
// Recovers from previously persisted metadata associated with segmented FIFO
// policy.
void recover(RecordReader& rr) override;
private:
void rebalanceLocked();
size_t numElementsLocked();
// Following are used to compute the ratio of each segment's
// size. The formula is as follows:
// (total_segments * (segment's ratio / sum(ratio))
const std::vector<unsigned int> segmentRatio_;
const unsigned int totalRatioWeight_;
std::vector<std::deque<detail::Node>> segments_;
mutable std::mutex mutex_;
};
} // namespace navy
} // namespace cachelib
} // namespace facebook
| 1,563 |
506 | #pragma once
#include "UIWidget.hpp"
#include <vector>
#include <utility>
// Combo Widget, supports up to two values on the
// home screen
namespace gfx
{
class UISensorComboWidget : public UIWidget
{
using ImagePath = std::string;
using ValueType = std::string;
public:
UISensorComboWidget(ScreenDriver* screenptr, Frame frame, uint16_t tag = 0);
void draw() override;
void setTextColor(Color textColor);
void setLabel(const std::string label);
void setImageWithValue(const std::pair<ImagePath, ValueType>& valuePair);
void eraseValues();
private:
Color mTextColor;
std::string mLabel;
std::vector<std::pair<ImagePath, ValueType>> mValues;
};
} // namespace gfx
| 272 |
796 | <gh_stars>100-1000
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class net_zhuoweizhang_pokerface_PokerFace */
#ifndef _Included_net_zhuoweizhang_pokerface_PokerFace
#define _Included_net_zhuoweizhang_pokerface_PokerFace
#ifdef __cplusplus
extern "C" {
#endif
#undef net_zhuoweizhang_pokerface_PokerFace_PROT_READ
#define net_zhuoweizhang_pokerface_PokerFace_PROT_READ 1L
#undef net_zhuoweizhang_pokerface_PokerFace_PROT_WRITE
#define net_zhuoweizhang_pokerface_PokerFace_PROT_WRITE 2L
#undef net_zhuoweizhang_pokerface_PokerFace_PROT_EXEC
#define net_zhuoweizhang_pokerface_PokerFace_PROT_EXEC 4L
#undef net_zhuoweizhang_pokerface_PokerFace_PROT_NONE
#define net_zhuoweizhang_pokerface_PokerFace_PROT_NONE 0L
#undef net_zhuoweizhang_pokerface_PokerFace__SC_PAGESIZE
#define net_zhuoweizhang_pokerface_PokerFace__SC_PAGESIZE 39L
/*
* Class: net_zhuoweizhang_pokerface_PokerFace
* Method: mprotect
* Signature: (JJI)I
*/
JNIEXPORT jint JNICALL Java_net_zhuoweizhang_pokerface_PokerFace_mprotect
(JNIEnv *, jclass, jlong, jlong, jint);
/*
* Class: net_zhuoweizhang_pokerface_PokerFace
* Method: sysconf
* Signature: (I)J
*/
JNIEXPORT jlong JNICALL Java_net_zhuoweizhang_pokerface_PokerFace_sysconf
(JNIEnv *, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif
| 575 |
631 | <reponame>zwc456baby/AndroidKeyBoard<filename>Demo/androidtvwidget/src/main/java/com/open/androidtvwidget/leanback/recycle/impl/PrvInterface.java
package com.open.androidtvwidget.leanback.recycle.impl;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
/**
* 按键加载更多接口.
* Created by hailongqiu on 2016/9/5.
*/
public interface PrvInterface {
void setOnLoadMoreComplete(); // 按键加载更多-->完成.
void setPagingableListener(RecyclerViewTV.PagingableListener pagingableListener);
}
| 208 |
361 | /*
* 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.servicecomb.demo.springmvc.server;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;
import javax.ws.rs.core.Response.Status;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
// test cases for retry
@RestSchema(schemaId = "RetrySchema")
@RequestMapping(path = "/retry", produces = MediaType.APPLICATION_JSON_VALUE)
public class RetrySchema {
private AtomicLong counter = new AtomicLong(0);
@GetMapping(path = "/governance/successWhenRetry")
public boolean successWhenRetry() {
if (counter.getAndIncrement() % 3 != 0) {
throw new InvocationException(Status.INTERNAL_SERVER_ERROR, "try again later.");
}
return true;
}
@GetMapping(path = "/governance/successWhenRetryAsync")
public CompletableFuture<Boolean> successWhenRetryAsync() {
CompletableFuture<Boolean> result = new CompletableFuture<>();
if (counter.getAndIncrement() % 2 == 0) {
result.completeExceptionally(new InvocationException(Status.INTERNAL_SERVER_ERROR, "try again later."));
} else {
result.complete(true);
}
return result;
}
}
| 657 |
310 | package org.seasar.doma.jdbc.query;
import static org.seasar.doma.internal.util.AssertionUtil.assertNotNull;
import org.seasar.doma.FetchType;
import org.seasar.doma.internal.jdbc.sql.NodePreparedSqlBuilder;
import org.seasar.doma.jdbc.SqlKind;
import org.seasar.doma.jdbc.SqlNode;
public class CountQuery extends AbstractSelectQuery {
protected SqlNode sqlNode;
@Override
public boolean isResultEnsured() {
return true;
}
@Override
public boolean isResultMappingEnsured() {
return false;
}
@Override
public FetchType getFetchType() {
return FetchType.LAZY;
}
@Override
public void prepare() {
super.prepare();
assertNotNull(sqlNode);
}
@Override
protected void prepareSql() {
SqlNode transformedSqlNode = config.getDialect().transformSelectSqlNodeForGettingCount(sqlNode);
buildSql(
(evaluator, expander) -> {
NodePreparedSqlBuilder sqlBuilder =
new NodePreparedSqlBuilder(
config, SqlKind.SELECT, null, evaluator, sqlLogType, expander);
return sqlBuilder.build(transformedSqlNode, this::comment);
});
}
@Override
public void complete() {
// do nothing
}
public void setSqlNode(SqlNode sqlNode) {
this.sqlNode = sqlNode;
}
}
| 497 |
348 | {"nom":"Lagny","circ":"6ème circonscription","dpt":"Oise","inscrits":368,"abs":193,"votants":175,"blancs":26,"nuls":6,"exp":143,"res":[{"nuance":"FN","nom":"<NAME>","voix":73},{"nuance":"REM","nom":"<NAME>","voix":70}]} | 88 |
521 | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Netscape Portable Runtime (NSPR).
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "primpl.h"
#include "MacMemAllocator.h"
void _MD_InitGC() {}
void *_MD_GrowGCHeap(size_t *sizep)
{
void *heapPtr = NULL;
size_t heapSize = *sizep;
// In previous versions of this code we tried to allocate GC heaps from the application
// heap. In the 4.0 application, we try to keep our app heap allications to a minimum
// and instead go through our own memory allocation routines.
heapPtr = malloc(heapSize);
if (heapPtr == NULL) {
FreeMemoryStats stats;
memtotal(heapSize, &stats); // How much can we allcoate?
if (stats.maxBlockSize < heapSize)
heapSize = stats.maxBlockSize;
heapPtr = malloc(heapSize);
if (heapPtr == NULL) // Now we're hurting
heapSize = 0;
}
*sizep = heapSize;
return heapPtr;
}
void _MD_FreeGCSegment(void *base, int32 /* len */)
{
free(base);
}
| 818 |
1,690 | <reponame>longyuzhao/sagemaker-python-sdk
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from __future__ import absolute_import
import pytest
from sagemaker.deprecations import (
deprecated_class,
deprecated_deserialize,
deprecated_function,
deprecated_serialize,
removed_arg,
removed_function,
removed_kwargs,
renamed_kwargs,
deprecation_warning,
deprecated,
)
def test_renamed_kwargs():
kwargs, c = {"a": 1}, 2
val = renamed_kwargs("b", new_name="c", value=c, kwargs=kwargs)
assert val == 2
kwargs, c = {"a": 1, "c": 2}, 2
val = renamed_kwargs("b", new_name="c", value=c, kwargs=kwargs)
assert val == 2
with pytest.warns(DeprecationWarning):
kwargs, c = {"a": 1, "b": 3}, 2
val = renamed_kwargs("b", new_name="c", value=c, kwargs=kwargs)
assert val == 3
assert kwargs == {"a": 1, "b": 3, "c": 3}
def test_removed_arg():
arg = None
removed_arg("b", arg)
with pytest.warns(DeprecationWarning):
arg = "it's here"
removed_arg("b", arg)
def test_removed_kwargs():
kwarg = {"a": 1}
removed_kwargs("b", kwarg)
with pytest.warns(DeprecationWarning):
kwarg = {"a": 1, "b": 3}
removed_kwargs("b", kwarg)
def test_deprecation_warning_for_function():
@deprecation_warning(msg="message", date="date")
def sample_function():
return "xxxx...."
with pytest.warns(DeprecationWarning) as w:
output = sample_function()
assert output == "xxxx...."
msg = (
"sample_function will be deprecated on date.message in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_deprecation_warning_for_class():
@deprecation_warning(msg="message", date="date")
class SampleClass:
def __init__(self):
pass
with pytest.warns(DeprecationWarning) as w:
SampleClass()
msg = (
"SampleClass will be deprecated on date.message in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_deprecation_warning_for_class_method():
class SampleClass:
def __init__(self):
pass
@deprecation_warning(msg="message", date="date")
def sample_method(self):
return "xxxx...."
s = SampleClass()
with pytest.warns(DeprecationWarning) as w:
output = s.sample_method()
assert output == "xxxx...."
msg = (
"sample_method will be deprecated on date.message in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_deprecated_for_function():
@deprecated
def sample_function():
return "xxxx...."
with pytest.warns(DeprecationWarning) as w:
output = sample_function()
assert output == "xxxx...."
msg = (
"sample_function is a no-op in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_deprecated_for_class():
@deprecated
class SampleClass:
def __init__(self):
pass
with pytest.warns(DeprecationWarning) as w:
SampleClass()
msg = (
"SampleClass is a no-op in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_deprecated_for_class_method():
class SampleClass:
def __init__(self):
pass
@deprecated
def sample_method(self):
return "xxxx...."
s = SampleClass()
with pytest.warns(DeprecationWarning) as w:
output = s.sample_method()
assert output == "xxxx...."
msg = (
"sample_method is a no-op in sagemaker>=2.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg
def test_removed_function():
removed = removed_function("foo")
with pytest.warns(DeprecationWarning):
removed()
def test_removed_function_from_instance():
class A:
def func(self):
return "a"
a = A()
a.func = removed_function("foo")
with pytest.warns(DeprecationWarning):
a.func()
def test_removed_function_from_class():
class A:
func = removed_function("foo")
a = A()
with pytest.warns(DeprecationWarning):
a.func()
def test_deprecated_function():
def func(a, b):
return a + b
deprecated = deprecated_function(func, "foo")
with pytest.warns(DeprecationWarning):
assert deprecated(1, 2) == 3
def test_deprecated_serialize():
class A:
def serialize(self):
return 1
a = deprecated_serialize(A(), "foo")
with pytest.warns(DeprecationWarning):
assert a.serialize() == 1
def test_deprecated_deserialize():
class A:
def deserialize(self):
return 1
a = deprecated_deserialize(A(), "foo")
with pytest.warns(DeprecationWarning):
assert a.deserialize() == 1
def test_deprecated_class():
class A:
pass
B = deprecated_class(A, "foo")
with pytest.warns(DeprecationWarning):
B()
| 2,618 |
1,927 | <reponame>alimy/scene
/*
* Copyright (C) 2019 ByteDance 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 com.bytedance.scene.animation;
import android.os.Build;
import androidx.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import com.bytedance.scene.Scene;
import com.bytedance.scene.State;
import com.bytedance.scene.navigation.NavigationScene;
import com.bytedance.scene.utlity.CancellationSignal;
import com.bytedance.scene.utlity.CancellationSignalList;
import com.bytedance.scene.utlity.Utility;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by JiangQi on 7/30/18.
*/
public abstract class NavigationAnimationExecutor {
protected ViewGroup mAnimationViewGroup;
public void setAnimationViewGroup(@NonNull ViewGroup viewGroup) {
this.mAnimationViewGroup = viewGroup;
}
public abstract boolean isSupport(@NonNull Class<? extends Scene> from, @NonNull Class<? extends Scene> to);
public final void executePushChange(@NonNull final NavigationScene navigationScene,
@NonNull final View rootView,
@NonNull final AnimationInfo fromInfo,
@NonNull final AnimationInfo toInfo,
@NonNull final CancellationSignalList cancellationSignal,
@NonNull final Runnable endAction) {
navigationScene.requestDisableTouchEvent(true);
final View fromView = fromInfo.mSceneView;
final View toView = toInfo.mSceneView;
// In the case of pushAndClear, it is possible that the Scene come from has been destroyed.
if (fromInfo.mSceneState.value < State.VIEW_CREATED.value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mAnimationViewGroup.getOverlay().add(fromView);
} else {
mAnimationViewGroup.addView(fromView);
}
}
final Runnable pushEndAction = new Runnable() {
@Override
public void run() {
navigationScene.requestDisableTouchEvent(false);
if (fromInfo.mSceneState.value < State.VIEW_CREATED.value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mAnimationViewGroup.getOverlay().remove(fromView);
} else {
mAnimationViewGroup.removeView(fromView);
}
}
endAction.run();
}
};
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
pushEndAction.run();
}
});
/*
* In case of continuous Push, the view of the previous page haven't been layout and has no height and width.
* Need to guarantee it here, otherwise it will affect the subsequent animation.
*/
final boolean isFromViewReady = !(fromView.getWidth() == 0 || fromView.getHeight() == 0);
boolean isToViewReady = !(toView.getWidth() == 0 || toView.getHeight() == 0);
if (!isFromViewReady || !isToViewReady) {
final CancellationSignal layoutCancellationSignal = cancellationSignal.getChildCancellationSignal();
skipDrawUntilViewMeasureReady(rootView, layoutCancellationSignal, new Runnable() {
@Override
public void run() {
if (!isFromViewReady) {
fromView.setVisibility(View.GONE);
}
if (!layoutCancellationSignal.isCanceled()) {
executePushChangeCancelable(fromInfo, toInfo, pushEndAction, cancellationSignal.getChildCancellationSignal());
}
}
});
if (!isFromViewReady) {
fromView.setVisibility(View.VISIBLE);
fromView.requestLayout();
}
if (!isToViewReady) {
toView.requestLayout();
}
} else {
executePushChangeCancelable(fromInfo, toInfo, pushEndAction, cancellationSignal.getChildCancellationSignal());
}
}
public final void executePopChange(@NonNull final NavigationScene navigationScene,
@NonNull final View rootView,
@NonNull final AnimationInfo fromInfo,
@NonNull final AnimationInfo toInfo,
@NonNull final CancellationSignalList cancellationSignal,
@NonNull final Runnable endAction) {
navigationScene.requestDisableTouchEvent(true);
final Runnable popEndAction = new Runnable() {
@Override
public void run() {
navigationScene.requestDisableTouchEvent(false);
endAction.run();
}
};
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
popEndAction.run();
}
});
final View fromView = fromInfo.mSceneView;
final View toView = toInfo.mSceneView;
final boolean isFromViewReady = !(fromView.getWidth() == 0 || fromView.getHeight() == 0);
boolean isToViewReady = !(toView.getWidth() == 0 || toView.getHeight() == 0);
if (!isFromViewReady || !isToViewReady) {
final CancellationSignal layoutCancellationSignal = cancellationSignal.getChildCancellationSignal();
skipDrawUntilViewMeasureReady(rootView, layoutCancellationSignal, new Runnable() {
@Override
public void run() {
if (!isFromViewReady) {
Utility.removeFromParentView(fromView);
fromView.setVisibility(View.GONE);
}
if (!layoutCancellationSignal.isCanceled()) {
executePopChangeCancelable(fromInfo, toInfo, popEndAction, cancellationSignal.getChildCancellationSignal());
}
}
});
if (!isFromViewReady) {
mAnimationViewGroup.addView(fromView);
fromView.setVisibility(View.VISIBLE);
fromView.requestLayout();
}
if (!isToViewReady) {
toView.requestLayout();
}
} else {
executePopChangeCancelable(fromInfo, toInfo, popEndAction, cancellationSignal.getChildCancellationSignal());
}
}
public abstract void executePushChangeCancelable(@NonNull final AnimationInfo fromInfo, @NonNull final AnimationInfo toInfo, @NonNull final Runnable endAction, @NonNull CancellationSignal cancellationSignal);
public abstract void executePopChangeCancelable(@NonNull final AnimationInfo fromInfo, @NonNull final AnimationInfo toInfo, @NonNull final Runnable endAction, @NonNull CancellationSignal cancellationSignal);
/**
* When viewTreeObserver.isAlive(), it is possible that ViewRoot has not attachedToWindow before doing animation
* The original ViewTreeObserver is merged into the ViewTreeObserver of ViewRoot, so this time we need to re-acquire
* Recurring steps: After Activity NavigationSceneUtility.setup(), do a new Push with new Handler().post().
*/
private static void skipDrawUntilViewMeasureReady(@NonNull final View rootView,
@NonNull CancellationSignal cancellationSignal,
@NonNull final Runnable endAction) {
if (rootView != rootView.getRootView()) {
throw new IllegalArgumentException("Need View.getRootView()");
}
final ViewTreeObserver viewTreeObserver = rootView.getViewTreeObserver();
final AtomicBoolean skipDraw = new AtomicBoolean(true);
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
boolean value = skipDraw.get();
if (!value) {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnPreDrawListener(this);
} else {
rootView.getViewTreeObserver().removeOnPreDrawListener(this);
}
return true;
} else {
return false;
}
}
});
final ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(this);
} else {
rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
skipDraw.set(false);
endAction.run();
}
};
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(onGlobalLayoutListener);
} else {
rootView.getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener);
}
skipDraw.set(false);
endAction.run();
}
});
viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener);
}
}
| 4,806 |
1,540 | <reponame>punamsapkale/testng
package test.parameters;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParameterSample {
@Parameters({"first-name"})
@BeforeMethod
public void beforeTest(String firstName) {
Assert.assertEquals(firstName, "Cedric");
}
@Parameters({"first-name"})
@Test(groups = {"singleString"})
public void testSingleString(String firstName) {
Assert.assertEquals(firstName, "Cedric");
}
@Parameters({"this parameter doesn't exist"})
@Test
public void testNonExistentParameter(@Optional String foo) {}
}
| 232 |
302 | package com.jeespring.modules.sys.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 主页
* Created by zhao.weiwei
* create on 2017/1/11 15:15
* the email is <EMAIL>.
*/
@Controller
public class IndexConteoller {
@Value("${adminPath:/a}")
private String adminpath;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "redirect:" + adminpath + "/login";
}
@RequestMapping(value = "/2", method = RequestMethod.GET)
public String index2() {
return "index2";
}
}
| 264 |
10,876 | {
"name": "gzip-hpp",
"version-string": "0.1.0",
"port-version": 1,
"description": "Gzip header-only C++ library",
"homepage": "https://github.com/mapbox/gzip-hpp/",
"dependencies": [
"zlib"
]
}
| 95 |
14,668 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_TRACING_WEB_PROCESS_MEMORY_DUMP_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_TRACING_WEB_PROCESS_MEMORY_DUMP_H_
#include <memory>
#include <unordered_map>
#include "base/gtest_prod_util.h"
#include "base/trace_event/heap_profiler_allocation_context.h"
#include "base/trace_event/memory_dump_request_args.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/web_memory_allocator_dump.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
class SkTraceMemoryDump;
namespace base {
class DiscardableMemory;
namespace trace_event {
class MemoryAllocatorDump;
class ProcessMemoryDump;
class TraceEventMemoryOverhead;
} // namespace base
} // namespace trace_event
namespace skia {
class SkiaTraceMemoryDumpImpl;
} // namespace skia
namespace blink {
// Used to specify the type of memory dump the WebProcessMemoryDump should
// generate on dump requests.
// TODO(hajimehoshi): Remove this and use base::trace_event::
// MemoryDumpLevelOfDetail instead.
enum class WebMemoryDumpLevelOfDetail { kBackground, kLight, kDetailed };
// A container which holds all the dumps for the various allocators for a given
// process. Embedders of WebMemoryDumpProvider are expected to populate a
// WebProcessMemoryDump instance with the stats of their allocators.
class PLATFORM_EXPORT WebProcessMemoryDump final {
USING_FAST_MALLOC(WebProcessMemoryDump);
public:
// Creates a standalone WebProcessMemoryDump, which owns the underlying
// ProcessMemoryDump.
WebProcessMemoryDump();
WebProcessMemoryDump(const WebProcessMemoryDump&) = delete;
WebProcessMemoryDump& operator=(const WebProcessMemoryDump&) = delete;
// Wraps (without owning) an existing ProcessMemoryDump.
explicit WebProcessMemoryDump(
base::trace_event::MemoryDumpLevelOfDetail level_of_detail,
base::trace_event::ProcessMemoryDump* process_memory_dump);
~WebProcessMemoryDump();
// Creates a new MemoryAllocatorDump with the given name and returns the
// empty object back to the caller. |absoluteName| uniquely identifies the
// dump within the scope of a ProcessMemoryDump. It is possible to express
// nesting by means of a slash-separated path naming (e.g.,
// "allocator_name/arena_1/subheap_X").
// |guid| is an optional identifier, unique among all processes within the
// scope of a global dump. This is only relevant when using
// addOwnershipEdge(). If omitted, it will be automatically generated.
blink::WebMemoryAllocatorDump* CreateMemoryAllocatorDump(
const String& absolute_name);
blink::WebMemoryAllocatorDump* CreateMemoryAllocatorDump(
const String& absolute_name,
blink::WebMemoryAllocatorDumpGuid guid);
// Gets a previously created MemoryAllocatorDump given its name.
blink::WebMemoryAllocatorDump* GetMemoryAllocatorDump(
const String& absolute_name) const;
// Removes all the WebMemoryAllocatorDump(s) contained in this instance.
// This WebProcessMemoryDump can be safely reused as if it was new once this
// method returns.
void Clear();
// Merges all WebMemoryAllocatorDump(s) contained in |other| inside this
// WebProcessMemoryDump, transferring their ownership to this instance.
// |other| will be an empty WebProcessMemoryDump after this method returns
// and can be reused as if it was new.
void TakeAllDumpsFrom(blink::WebProcessMemoryDump* other);
// Adds an ownership relationship between two MemoryAllocatorDump(s) with
// the semantics: |source| owns |target|, and has the effect of attributing
// the memory usage of |target| to |source|. |importance| is optional and
// relevant only for the cases of co-ownership, where it acts as a z-index:
// the owner with the highest importance will be attributed |target|'s
// memory.
void AddOwnershipEdge(blink::WebMemoryAllocatorDumpGuid source,
blink::WebMemoryAllocatorDumpGuid target,
int importance);
void AddOwnershipEdge(blink::WebMemoryAllocatorDumpGuid source,
blink::WebMemoryAllocatorDumpGuid target);
// Utility method to add a suballocation relationship with the following
// semantics: |source| is suballocated from |target_node_name|.
// This creates a child node of |target_node_name| and adds an ownership
// edge between |source| and the new child node. As a result, the UI will
// not account the memory of |source| in the target node.
void AddSuballocation(blink::WebMemoryAllocatorDumpGuid source,
const String& target_node_name);
// Returns the SkTraceMemoryDump proxy interface that can be passed to Skia
// to dump into this WebProcessMemoryDump. Multiple SkTraceMemoryDump
// objects can be created using this method. The created dumpers are owned
// by WebProcessMemoryDump and cannot outlive the WebProcessMemoryDump
// object owning them. |dumpNamePrefix| is prefix appended to each dump
// created by the SkTraceMemoryDump implementation, if the dump should be
// placed under different namespace and not "skia".
SkTraceMemoryDump* CreateDumpAdapterForSkia(const String& dump_name_prefix);
const base::trace_event::ProcessMemoryDump* process_memory_dump() const {
return process_memory_dump_;
}
blink::WebMemoryAllocatorDump* CreateDiscardableMemoryAllocatorDump(
const std::string& name,
base::DiscardableMemory* discardable);
// Dumps heap memory usage. |allocatorName| is used as an absolute name for
// base::trace_event::ProcessMemoryDump::DumpHeapUsage().
void DumpHeapUsage(
const std::unordered_map<base::trace_event::AllocationContext,
base::trace_event::AllocationMetrics>&
metrics_by_context,
base::trace_event::TraceEventMemoryOverhead& overhead,
const char* allocator_name);
private:
FRIEND_TEST_ALL_PREFIXES(WebProcessMemoryDumpTest, IntegrationTest);
blink::WebMemoryAllocatorDump* CreateWebMemoryAllocatorDump(
base::trace_event::MemoryAllocatorDump* memory_allocator_dump);
// Only for the case of ProcessMemoryDump being owned (i.e. the default ctor).
std::unique_ptr<base::trace_event::ProcessMemoryDump>
owned_process_memory_dump_;
// The underlying ProcessMemoryDump instance to which the
// createMemoryAllocatorDump() calls will be proxied to.
base::trace_event::ProcessMemoryDump* process_memory_dump_; // Not owned.
// TODO(ssid): Remove it once this information is added to ProcessMemoryDump.
base::trace_event::MemoryDumpLevelOfDetail level_of_detail_;
// Reverse index of MemoryAllocatorDump -> WebMemoryAllocatorDump wrapper.
// By design WebMemoryDumpProvider(s) are not supposed to hold the pointer
// to the WebProcessMemoryDump passed as argument of the onMemoryDump() call.
// Those pointers are valid only within the scope of the call and can be
// safely torn down once the WebProcessMemoryDump itself is destroyed.
HashMap<base::trace_event::MemoryAllocatorDump*,
std::unique_ptr<WebMemoryAllocatorDump>>
memory_allocator_dumps_;
// Stores SkTraceMemoryDump for the current ProcessMemoryDump.
Vector<std::unique_ptr<skia::SkiaTraceMemoryDumpImpl>> sk_trace_dump_list_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_TRACING_WEB_PROCESS_MEMORY_DUMP_H_
| 2,504 |
2,338 | <reponame>mkinsner/llvm
// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK
// RUN: %clang_cc1 -fsanitize=implicit-signed-integer-truncation,implicit-integer-sign-change -fno-sanitize-recover=implicit-signed-integer-truncation,implicit-integer-sign-change -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_implicit_conversion" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER,CHECK-SANITIZE-UNREACHABLE
// RUN: %clang_cc1 -fsanitize=implicit-signed-integer-truncation,implicit-integer-sign-change -fsanitize-recover=implicit-signed-integer-truncation,implicit-integer-sign-change -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_implicit_conversion" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER
// RUN: %clang_cc1 -fsanitize=implicit-signed-integer-truncation,implicit-integer-sign-change -fsanitize-trap=implicit-signed-integer-truncation,implicit-integer-sign-change -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_implicit_conversion" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP,CHECK-SANITIZE-UNREACHABLE
// CHECK-SANITIZE-ANYRECOVER: @[[UNSIGNED_INT:.*]] = {{.*}} c"'unsigned int'\00" }
// CHECK-SANITIZE-ANYRECOVER-NEXT: @[[SIGNED_CHAR:.*]] = {{.*}} c"'signed char'\00" }
// CHECK-SANITIZE-ANYRECOVER-NEXT: @[[LINE_100_SIGNED_TRUNCATION_OR_SIGN_CHANGE:.*]] = {{.*}}, i32 100, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 4 }
// CHECK-SANITIZE-ANYRECOVER-NEXT: @[[LINE_200_SIGN_CHANGE:.*]] = {{.*}}, i32 200, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 3 }
// CHECK-SANITIZE-ANYRECOVER-NEXT: @[[LINE_300_SIGN_CHANGE:.*]] = {{.*}}, i32 300, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 3 }
// CHECK-SANITIZE-ANYRECOVER-NEXT: @[[LINE_400_SIGNED_TRUNCATION:.*]] = {{.*}}, i32 400, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 2 }
//============================================================================//
// Both sanitizers are enabled, and not disabled per-function.
//============================================================================//
// CHECK-LABEL: @unsigned_int_to_signed_char
// CHECK-SAME: (i32 %[[SRC:.*]])
signed char unsigned_int_to_signed_char(unsigned int src) {
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[SRC_ADDR:.*]] = alloca i32
// CHECK-NEXT: store i32 %[[SRC]], i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[DST:.*]] = load i32, i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[CONV:.*]] = trunc i32 %[[DST]] to i8
// CHECK-SANITIZE-NEXT: %[[DST_NEGATIVITYCHECK:.*]] = icmp slt i8 %[[CONV]], 0, !nosanitize
// CHECK-SANITIZE-NEXT: %[[SIGNCHANGECHECK:.*]] = icmp eq i1 false, %[[DST_NEGATIVITYCHECK]], !nosanitize
// CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = sext i8 %[[CONV]] to i32, !nosanitize
// CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[DST]], !nosanitize
// CHECK-SANITIZE-NEXT: %[[BOTHCHECKS:.*]] = and i1 %[[SIGNCHANGECHECK]], %[[TRUNCHECK]], !nosanitize
// CHECK-SANITIZE-NEXT: br i1 %[[BOTHCHECKS]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize
// CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]:
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[DST]] to i64, !nosanitize
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTCONV:.*]] = zext i8 %[[CONV]] to i64, !nosanitize
// CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_100_SIGNED_TRUNCATION_OR_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_100_SIGNED_TRUNCATION_OR_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-TRAP-NEXT: call void @llvm.ubsantrap(i8 7){{.*}}, !nosanitize
// CHECK-SANITIZE-UNREACHABLE-NEXT: unreachable, !nosanitize
// CHECK-SANITIZE: [[CONT]]:
// CHECK-NEXT: ret i8 %[[CONV]]
// CHECK-NEXT: }
#line 100
return src;
}
//============================================================================//
// Truncation sanitizer is disabled per-function.
//============================================================================//
// CHECK-LABEL: @unsigned_int_to_signed_char__no_truncation_sanitizer
// CHECK-SAME: (i32 %[[SRC:.*]])
__attribute__((no_sanitize("implicit-integer-truncation"))) signed char
unsigned_int_to_signed_char__no_truncation_sanitizer(unsigned int src) {
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[SRC_ADDR:.*]] = alloca i32
// CHECK-NEXT: store i32 %[[SRC]], i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[DST:.*]] = load i32, i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[CONV:.*]] = trunc i32 %[[DST]] to i8
// CHECK-SANITIZE-NEXT: %[[DST_NEGATIVITYCHECK:.*]] = icmp slt i8 %[[CONV]], 0, !nosanitize
// CHECK-SANITIZE-NEXT: %[[SIGNCHANGECHECK:.*]] = icmp eq i1 false, %[[DST_NEGATIVITYCHECK]], !nosanitize
// CHECK-SANITIZE-NEXT: br i1 %[[SIGNCHANGECHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize
// CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]:
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[DST]] to i64, !nosanitize
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTCONV:.*]] = zext i8 %[[CONV]] to i64, !nosanitize
// CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_200_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_200_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-TRAP-NEXT: call void @llvm.ubsantrap(i8 7){{.*}}, !nosanitize
// CHECK-SANITIZE-UNREACHABLE-NEXT: unreachable, !nosanitize
// CHECK-SANITIZE: [[CONT]]:
// CHECK-NEXT: ret i8 %[[CONV]]
// CHECK-NEXT: }
#line 200
return src;
}
//============================================================================//
// Signed truncation sanitizer is disabled per-function.
//============================================================================//
// CHECK-LABEL: @unsigned_int_to_signed_char__no_signed_truncation_sanitizer
// CHECK-SAME: (i32 %[[SRC:.*]])
__attribute__((no_sanitize("implicit-signed-integer-truncation"))) signed char
unsigned_int_to_signed_char__no_signed_truncation_sanitizer(unsigned int src) {
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[SRC_ADDR:.*]] = alloca i32
// CHECK-NEXT: store i32 %[[SRC]], i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[DST:.*]] = load i32, i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[CONV:.*]] = trunc i32 %[[DST]] to i8
// CHECK-SANITIZE-NEXT: %[[DST_NEGATIVITYCHECK:.*]] = icmp slt i8 %[[CONV]], 0, !nosanitize
// CHECK-SANITIZE-NEXT: %[[SIGNCHANGECHECK:.*]] = icmp eq i1 false, %[[DST_NEGATIVITYCHECK]], !nosanitize
// CHECK-SANITIZE-NEXT: br i1 %[[SIGNCHANGECHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize
// CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]:
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[DST]] to i64, !nosanitize
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTCONV:.*]] = zext i8 %[[CONV]] to i64, !nosanitize
// CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_300_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_300_SIGN_CHANGE]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-TRAP-NEXT: call void @llvm.ubsantrap(i8 7){{.*}}, !nosanitize
// CHECK-SANITIZE-UNREACHABLE-NEXT: unreachable, !nosanitize
// CHECK-SANITIZE: [[CONT]]:
// CHECK-NEXT: ret i8 %[[CONV]]
// CHECK-NEXT: }
#line 300
return src;
}
//============================================================================//
// Sign change sanitizer is disabled per-function
//============================================================================//
// CHECK-LABEL: @unsigned_int_to_signed_char__no_sign_change_sanitizer
// CHECK-SAME: (i32 %[[SRC:.*]])
__attribute__((no_sanitize("implicit-integer-sign-change"))) signed char
unsigned_int_to_signed_char__no_sign_change_sanitizer(unsigned int src) {
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[SRC_ADDR:.*]] = alloca i32
// CHECK-NEXT: store i32 %[[SRC]], i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[DST:.*]] = load i32, i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[CONV:.*]] = trunc i32 %[[DST]] to i8
// CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = sext i8 %[[CONV]] to i32, !nosanitize
// CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[DST]], !nosanitize
// CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize
// CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]:
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[DST]] to i64, !nosanitize
// CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTCONV:.*]] = zext i8 %[[CONV]] to i64, !nosanitize
// CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_400_SIGNED_TRUNCATION]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_400_SIGNED_TRUNCATION]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTCONV]]){{.*}}, !nosanitize
// CHECK-SANITIZE-TRAP-NEXT: call void @llvm.ubsantrap(i8 7){{.*}}, !nosanitize
// CHECK-SANITIZE-UNREACHABLE-NEXT: unreachable, !nosanitize
// CHECK-SANITIZE: [[CONT]]:
// CHECK-NEXT: ret i8 %[[CONV]]
// CHECK-NEXT: }
#line 400
return src;
}
//============================================================================//
// Both sanitizers are disabled per-function.
//============================================================================//
// CHECK-LABEL: @unsigned_int_to_signed_char__no_sanitizers
// CHECK-SAME: (i32 %[[SRC:.*]])
__attribute__((no_sanitize("implicit-integer-truncation"),
no_sanitize("implicit-integer-sign-change"))) signed char
unsigned_int_to_signed_char__no_sanitizers(unsigned int src) {
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[SRC_ADDR:.*]] = alloca i32
// CHECK-NEXT: store i32 %[[SRC]], i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[DST:.*]] = load i32, i32* %[[SRC_ADDR]]
// CHECK-NEXT: %[[CONV:.*]] = trunc i32 %[[DST]] to i8
// CHECK-NEXT: ret i8 %[[CONV]]
// CHECK-NEXT: }
return src;
}
| 4,667 |
6,989 | import yatest.common as yc
def test_export_metrics(metrics):
metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/fastclp2/fastclp2', threads=8))
| 63 |
1,165 | <filename>api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/domain/RuleDetails.java
/*******************************************************************************
* Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
/**
Copyright (C) 2017 T Mobile Inc - All Rights Reserve
Purpose:
Author :Nidhish
Modified Date: Nov 22, 2017
**/
package com.tmobile.pacman.api.compliance.domain;
/**
* The Class RuleDetails.
*/
public class RuleDetails {
/** The rule id. */
private String ruleId;
/** The reason. */
private String reason;
/** The user id. */
private String userId;
/**
* Gets the rule id.
*
* @return the rule id
*/
public String getRuleId() {
return ruleId;
}
/**
* Sets the rule id.
*
* @param ruleId the new rule id
*/
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
/**
* Gets the reason.
*
* @return the reason
*/
public String getReason() {
return reason;
}
/**
* Sets the reason.
*
* @param reason the new reason
*/
public void setReason(String reason) {
this.reason = reason;
}
/**
* Gets the user id.
*
* @return the user id
*/
public String getUserId() {
return userId;
}
/**
* Sets the user id.
*
* @param userId the new user id
*/
public void setUserId(String userId) {
this.userId = userId;
}
}
| 763 |
12,252 | <gh_stars>1000+
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.scripting;
import org.keycloak.models.ScriptModel;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
* Wraps a {@link ScriptModel} and makes it {@link Invocable}.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class InvocableScriptAdapter implements Invocable {
/**
* Holds the {@ScriptModel}
*/
private final ScriptModel scriptModel;
/**
* Holds the {@link ScriptEngine} instance initialized with the script code.
*/
private final ScriptEngine scriptEngine;
/**
* Creates a new {@link InvocableScriptAdapter} instance.
*
* @param scriptModel must not be {@literal null}
* @param scriptEngine must not be {@literal null}
*/
public InvocableScriptAdapter(ScriptModel scriptModel, ScriptEngine scriptEngine) {
if (scriptModel == null) {
throw new IllegalArgumentException("scriptModel must not be null");
}
if (scriptEngine == null) {
throw new IllegalArgumentException("scriptEngine must not be null");
}
this.scriptModel = scriptModel;
this.scriptEngine = scriptEngine;
}
@Override
public Object invokeMethod(Object thiz, String name, Object... args) throws ScriptExecutionException {
try {
return getInvocableEngine().invokeMethod(thiz, name, args);
} catch (ScriptException | NoSuchMethodException e) {
throw new ScriptExecutionException(scriptModel, e);
}
}
@Override
public Object invokeFunction(String name, Object... args) throws ScriptExecutionException {
try {
return getInvocableEngine().invokeFunction(name, args);
} catch (ScriptException | NoSuchMethodException e) {
throw new ScriptExecutionException(scriptModel, e);
}
}
@Override
public <T> T getInterface(Class<T> clazz) {
return getInvocableEngine().getInterface(clazz);
}
@Override
public <T> T getInterface(Object thiz, Class<T> clazz) {
return getInvocableEngine().getInterface(thiz, clazz);
}
/**
* Returns {@literal true} if the {@link ScriptEngine} has a definition with the given {@code name}.
*
* @param name
* @return
*/
public boolean isDefined(String name) {
Object candidate = scriptEngine.getContext().getAttribute(name);
return candidate != null;
}
private Invocable getInvocableEngine() {
return (Invocable) scriptEngine;
}
}
| 1,139 |
705 | package src;
import becker.robots.*;
public class ICE_02_02_Trace extends Object
{
public static void main(String[] args)
{
City theCity = new City();
Robot Bob = new Robot(theCity, 3, 0, Direction.EAST, 0);
new Thing(theCity, 1, 1);
new Wall(theCity, 3, 0, Direction.EAST);
new Wall(theCity, 3, 0, Direction.SOUTH);
new Wall(theCity, 1, 0, Direction.NORTH);
new Wall(theCity, 1, 1, Direction.NORTH);
Bob.turnLeft();
Bob.move();
Bob.move();
Bob.turnLeft();
Bob.turnLeft();
Bob.turnLeft();
Bob.move();
Bob.pickThing();
Bob.turnLeft();
Bob.turnLeft();
Bob.move();
Bob.turnLeft();
Bob.move();
Bob.move();
Bob.putThing();
Bob.turnLeft();
Bob.turnLeft();
Bob.move();
}
}
| 435 |
648 | {"resourceType":"DataElement","id":"RequestGroup.action.precheckBehavior","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/RequestGroup.action.precheckBehavior","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"RequestGroup.action.precheckBehavior","path":"RequestGroup.action.precheckBehavior","short":"yes | no","definition":"Defines whether the action should usually be preselected.","min":0,"max":"1","type":[{"code":"code"}],"binding":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName","valueString":"ActionPrecheckBehavior"}],"strength":"required","description":"Defines selection frequency behavior for an action or group","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/action-precheck-behavior"}}}]} | 226 |
643 | <reponame>boaz001/pipes
#ifndef PIPES_HPP
#define PIPES_HPP
#include "pipes/adjacent.hpp"
#include "pipes/cartesian_product.hpp"
#include "pipes/combinations.hpp"
#include "pipes/dev_null.hpp"
#include "pipes/do_then.hpp"
#include "pipes/drop.hpp"
#include "pipes/drop_while.hpp"
#include "pipes/filter.hpp"
#include "pipes/for_each.hpp"
#include "pipes/fork.hpp"
#include "pipes/join.hpp"
#include "pipes/insert.hpp"
#include "pipes/intersperse.hpp"
#include "pipes/map_aggregator.hpp"
#include "pipes/mux.hpp"
#include "pipes/override.hpp"
#include "pipes/partition.hpp"
#include "pipes/push_back.hpp"
#include "pipes/read_in_stream.hpp"
#include "pipes/set_aggregator.hpp"
#include "pipes/stride.hpp"
#include "pipes/switch.hpp"
#include "pipes/take.hpp"
#include "pipes/take_while.hpp"
#include "pipes/tee.hpp"
#include "pipes/to_out_stream.hpp"
#include "pipes/transform.hpp"
#include "pipes/unzip.hpp"
#endif /* PIPES_HPP */
| 421 |
487 | /**
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kaczmarzyk.spring.data.jpa.domain;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import net.kaczmarzyk.spring.data.jpa.utils.Converter;
import net.kaczmarzyk.spring.data.jpa.utils.QueryContext;
import java.util.Objects;
/**
* <p>Filters with {@code path between arg1 and arg2} where-clause.</p>
*
* <p>Supports multiple field types: strings, numbers, booleans, enums, dates.</p>
*
* <p>Field types must be Comparable (e.g, implement the Comparable interface); this is
* a JPA constraint.</p>
*
* <p>NOTE: comparisons are dependent on the underlying database.</p>
* <p>Comparisons of floats and doubles (especially floats) may be incorrect due to precision loss.</p>
* <p>Comparisons of booleans may be dependent on the underlying database representation.</p>
* <p>Comparisons of enums will be of their ordinal or string representations, depending on what you specified to JPA,
* e.g., {@code @Enumerated(EnumType.STRING)}, {@code @Enumerated(EnumType.ORDINAL)} or the default ({@code @Enumerated(EnumType.ORDINAL)})</p>
*
* @author Tomasz Kaczmarzyk
* @author <NAME>
*/
public class Between<T> extends PathSpecification<T> {
private static final long serialVersionUID = 1L;
private final String lowerBoundaryStr;
private final String upperBoundaryStr;
private final Converter converter;
public Between(QueryContext queryContext, String path, String[] args, Converter converter) {
super(queryContext, path);
if (args == null || args.length != 2) {
throw new IllegalArgumentException("expected 2 http params (lower and upper boundaries), but was: " + args);
}
this.converter = converter;
this.lowerBoundaryStr = args[0];
this.upperBoundaryStr = args[1];
}
@SuppressWarnings("unchecked")
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
Expression<Comparable<Object>> targetExpression = path(root);
Class<?> typeOnPath = targetExpression.getJavaType();
Comparable<Object> lowerBoundary = (Comparable<Object>) converter.convert(lowerBoundaryStr, typeOnPath);
Comparable<Object> upperBoundary = (Comparable<Object>) converter.convert(upperBoundaryStr, typeOnPath);
return criteriaBuilder.between(targetExpression, lowerBoundary, upperBoundary);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Between<?> between = (Between<?>) o;
return Objects.equals(lowerBoundaryStr, between.lowerBoundaryStr) &&
Objects.equals(upperBoundaryStr, between.upperBoundaryStr) &&
Objects.equals(converter, between.converter);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), lowerBoundaryStr, upperBoundaryStr, converter);
}
@Override
public String toString() {
return "Between[" +
"lowerBoundaryStr='" + lowerBoundaryStr + '\'' +
", upperBoundaryStr='" + upperBoundaryStr + '\'' +
", converter=" + converter +
']';
}
}
| 1,241 |
422 | <reponame>hhoppe/Mesh-processing-library
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#ifndef MESH_PROCESSING_LIBHH_ARRAYOP_H_
#define MESH_PROCESSING_LIBHH_ARRAYOP_H_
#include "libHh/Advanced.h" // do_in_order
#include "libHh/Array.h"
#include "libHh/RangeOp.h" // sort()
#include "libHh/Vec.h" // Vec2<>
namespace hh {
// Concatenate two or more array views.
template <typename T, typename... A> Array<T> concat(CArrayView<T> ar1, A&&... arr) {
Array<T> ar;
int i = ar1.num();
do_in_order{i += arr.num()...};
ar.reserve(i);
// ar.reserve(ar1.num() + narrow_cast<int>(sum(CArrayView<int>{arr.num()...}))); // requires sum()
// Vec<int, sizeof...(arr)> t(arr.num()...); ar.reserve(ar1.num() + narrow_cast<int>(sum(t)));
ar.push_array(ar1);
do_in_order{(ar.push_array(arr), 0)...};
return ar;
}
// Return a sorted, uniquified array of values gathered from a range.
template <typename R, typename = enable_if_range_t<R>> Array<iterator_t<R>> sort_unique(const R& range) {
using T = iterator_t<R>;
using std::begin;
using std::end;
Array<T> ar(begin(range), end(range));
sort(ar);
T* last = std::unique(ar.begin(), ar.end());
ar.sub(narrow_cast<int>(ar.end() - last)); // leave it to client to do shrink_to_fit()
return ar;
}
// Return the two closest values to the median of a list (or the same value twice if the list length is odd).
template <typename R, typename = enable_if_range_t<R>> Vec2<iterator_t<R>> median_two(const R& range) {
using T = iterator_t<R>;
using std::begin;
using std::end;
Array<T> ar(begin(range), end(range));
assertx(ar.num());
const int median_index = ar.num() / 2;
std::nth_element(ar.begin(), &ar[median_index], ar.end()); // place median element at median location
T val0 = ar[median_index];
// List is partially sorted about the median value, so find the min of the second half.
T val1 = ar.num() % 2 == 1 ? val0 : *std::min_element(&ar[median_index + 1], ar.end());
return V(val0, val1);
}
// Return the median value of a list (or the mean of the two nearest values if the list length is even).
template <typename R, typename = enable_if_range_t<R>> mean_type_t<iterator_t<R>> median(const R& range) {
return mean(median_two(range));
}
// Return the element with specified rank within range (where 0 <= rank < size(range) and rank == 0 is min element).
template <typename R, typename = enable_if_range_t<R>> iterator_t<R> rank_element(const R& range, int rank) {
using T = iterator_t<R>;
using std::begin;
using std::end;
Array<T> ar(begin(range), end(range));
assertx(ar.num());
assertx(ar.ok(rank));
std::nth_element(ar.begin(), &ar[rank], ar.end()); // place rank element at rank location
return ar[rank];
}
// Return element with fractional ranking within range (where 0. <= rankf <= 1. and rankf == 0. is min element).
template <typename R, typename = enable_if_range_t<R>> iterator_t<R> rankf_element(const R& range, double rankf) {
assertx(rankf >= 0. && rankf <= 1.);
int num = narrow_cast<int>(distance(range));
int rank = static_cast<int>(floor(rankf * num));
if (rank == num) rank--;
return rank_element(range, rank);
}
} // namespace hh
#endif // MESH_PROCESSING_LIBHH_ARRAYOP_H_
| 1,216 |
5,169 | {
"name": "HBBasic",
"version": "1.0.3",
"summary": "HBBasic iOS Classes",
"description": "Classes for HBBasic",
"platforms": {
"ios": "12.0"
},
"homepage": "https://github.com/hepburnalex/HBBasic",
"license": "MIT",
"authors": {
"hepburn": "<EMAIL>"
},
"source": {
"git": "https://github.com/hepburnalex/HBBasic.git",
"tag": "1.0.3"
},
"source_files": [
"HBBasic",
"HBBasic/*.{h,m}"
],
"public_header_files": "HBBasic/*.h",
"resources": "HBBasic/MBProgressHUD.bundle",
"pod_target_xcconfig": {
"VALID_ARCHS": "x86_64 armv7 arm64"
},
"requires_arc": true,
"dependencies": {
"HBBasicLib": [
],
"AFNetworking": [
],
"MBProgressHUD": [
],
"MJExtension": [
],
"UMCCommon": [
],
"UMCShare/UI": [
],
"UMCShare/Social/WeChat": [
]
}
}
| 425 |
374 | #ifndef SARIBBONBARDESIGNERPLUGIN_H
#define SARIBBONBARDESIGNERPLUGIN_H
#include <QDesignerCustomWidgetInterface>
class QDesignerFormEditorInterface;
class QDesignerFormWindowInterface;
namespace SA_PLUGIN {
/**
* @brief SARibbonBar对应的插件
*/
class SARibbonBarDesignerPlugin : public QObject,
public QDesignerCustomWidgetInterface
{
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
public:
SARibbonBarDesignerPlugin(QObject *p = nullptr);
public:
bool isContainer() const Q_DECL_OVERRIDE;
bool isInitialized() const Q_DECL_OVERRIDE;
QIcon icon() const Q_DECL_OVERRIDE;
QString domXml() const Q_DECL_OVERRIDE;
QString group() const Q_DECL_OVERRIDE;
QString includeFile() const Q_DECL_OVERRIDE;
QString name() const Q_DECL_OVERRIDE;
QString toolTip() const Q_DECL_OVERRIDE;
QString whatsThis() const Q_DECL_OVERRIDE;
QWidget *createWidget(QWidget *parent) Q_DECL_OVERRIDE;
void initialize(QDesignerFormEditorInterface *core) Q_DECL_OVERRIDE;
private slots:
void onFormWindowAdded(QDesignerFormWindowInterface *formWindow);
void onFormWindowRemoved(QDesignerFormWindowInterface *formWindow);
void onWidgetManaged(QWidget *widget);
private:
bool m_isInitialized;
QDesignerFormEditorInterface *m_formEditor;
};
}
#endif // SARIBBONBARDESIGNERPLUGIN_H
| 522 |
5,169 | {
"name": "PayPalHereSDK",
"version": "1.6.6",
"summary": "SDK for interfacing with PayPal card readers and mobile payment processing APIs.",
"license": "COMMERCIAL",
"homepage": "https://developer.paypal.com/docs/integration/paypal-here/ios-dev/overview/",
"authors": {
"PayPal": "paypal"
},
"source": {
"git": "https://github.com/PayPal-Mobile/ios-here-sdk-dist.git",
"tag": "v1.6.6"
},
"platforms": {
"ios": "6.0"
},
"requires_arc": true,
"xcconfig": {
"FRAMEWORK_SEARCH_PATHS": "$(inherited)",
"OTHER_LDFLAGS": "$(inherited) -lstdc++ -stdlib=libstdc++ -ObjC"
},
"ios": {
"libraries": [
"sqlite3",
"z",
"xml2"
],
"frameworks": [
"AudioToolbox",
"MobileCoreServices",
"Security",
"CFNetwork",
"AVFoundation",
"ExternalAccessory",
"MediaPlayer",
"CoreTelephony",
"Foundation",
"CoreBluetooth",
"SystemConfiguration"
]
},
"default_subspecs": "Debug",
"subspecs": [
{
"name": "Debug",
"vendored_frameworks": "SDK/Debug/PayPalHereSDK.framework",
"resources": "SDK/Debug/PayPalHereSDK.bundle"
},
{
"name": "Release",
"vendored_frameworks": "SDK/Release/PayPalHereSDK.framework",
"resources": "SDK/Release/PayPalHereSDK.bundle"
},
{
"name": "Debug-nohw",
"vendored_frameworks": "SDK/nohw/Debug/PayPalHereSDK.framework",
"resources": "SDK/nohw/Debug/PayPalHereSDK.bundle"
},
{
"name": "Release-nohw",
"vendored_frameworks": "SDK/nohw/Release/PayPalHereSDK.framework",
"resources": "SDK/nohw/Release/PayPalHereSDK.bundle"
}
]
}
| 794 |
1,062 | <reponame>larkov/MailTrackerBlocker
//
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <MailFW/MFEWSPersistenceTaskOperation.h>
@class NSSet;
@interface MFEWSPruneFolderHierarchyTaskOperation : MFEWSPersistenceTaskOperation
{
BOOL _prunedSuccessfully; // 8 = 0x8
NSSet *_foundFolderIdStrings; // 16 = 0x10
}
@property(readonly, copy, nonatomic) NSSet *foundFolderIdStrings; // @synthesize foundFolderIdStrings=_foundFolderIdStrings;
@property(nonatomic) BOOL prunedSuccessfully; // @synthesize prunedSuccessfully=_prunedSuccessfully;
// - (void).cxx_destruct; // IMP=0x000000000009d00a
- (void)main; // IMP=0x000000000009ccfc
- (id)init; // IMP=0x000000000009cc2d
- (id)initWithFoundFolderIdStrings:(id)arg1; // IMP=0x000000000009cbb3
@end
| 329 |
852 | <reponame>ckamtsikis/cmssw
#ifndef RecoVertex_VertexHisto
#define RecoVertex_VertexHisto
#include <string>
#include "RecoVertex/VertexPrimitives/interface/TransientVertex.h"
// #include "RecoVertex/ConfigurableVertexReco/test/TrackHisto.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingVertex.h"
#include "SimTracker/TrackAssociation/interface/TrackAssociatorBase.h"
class VertexHisto {
/**
* Vertex histogramming.
*/
public:
VertexHisto( const std::string & filename="vertices.root",
const std::string & trackname="tracks.root" );
~VertexHisto();
void analyse ( const TrackingVertex & sim, const TransientVertex & rec,
const std::string & name ) const;
void saveTracks ( const TransientVertex & rec,
const reco::RecoToSimCollection & p,
const std::string & name ) const;
private:
void stamp();
private:
std::string filename_;
// TrackHisto tracks_;
bool hasStamped;
};
#endif
| 478 |
335 | <gh_stars>100-1000
{
"word": "Nadir",
"definitions": [
"The lowest or most unsuccessful point in a situation.",
"The point on the celestial sphere directly below an observer."
],
"parts-of-speech": "Noun"
} | 92 |
2,706 | /* Copyright (c) 2013-2015 <NAME>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <mgba/internal/gba/io.h>
#include <mgba/internal/arm/macros.h>
#include <mgba/internal/gba/dma.h>
#include <mgba/internal/gba/gba.h>
#include <mgba/internal/gba/rr/rr.h>
#include <mgba/internal/gba/serialize.h>
mLOG_DEFINE_CATEGORY(GBA_IO, "GBA I/O", "gba.io");
const char* const GBAIORegisterNames[] = {
// Video
"DISPCNT",
0,
"DISPSTAT",
"VCOUNT",
"BG0CNT",
"BG1CNT",
"BG2CNT",
"BG3CNT",
"BG0HOFS",
"BG0VOFS",
"BG1HOFS",
"BG1VOFS",
"BG2HOFS",
"BG2VOFS",
"BG3HOFS",
"BG3VOFS",
"BG2PA",
"BG2PB",
"BG2PC",
"BG2PD",
"BG2X_LO",
"BG2X_HI",
"BG2Y_LO",
"BG2Y_HI",
"BG3PA",
"BG3PB",
"BG3PC",
"BG3PD",
"BG3X_LO",
"BG3X_HI",
"BG3Y_LO",
"BG3Y_HI",
"WIN0H",
"WIN1H",
"WIN0V",
"WIN1V",
"WININ",
"WINOUT",
"MOSAIC",
0,
"BLDCNT",
"BLDALPHA",
"BLDY",
0,
0,
0,
0,
0,
// Sound
"SOUND1CNT_LO",
"SOUND1CNT_HI",
"SOUND1CNT_X",
0,
"SOUND2CNT_LO",
0,
"SOUND2CNT_HI",
0,
"SOUND3CNT_LO",
"SOUND3CNT_HI",
"SOUND3CNT_X",
0,
"SOUND4CNT_LO",
0,
"SOUND4CNT_HI",
0,
"SOUNDCNT_LO",
"SOUNDCNT_HI",
"SOUNDCNT_X",
0,
"SOUNDBIAS",
0,
0,
0,
"WAVE_RAM0_LO",
"WAVE_RAM0_HI",
"WAVE_RAM1_LO",
"WAVE_RAM1_HI",
"WAVE_RAM2_LO",
"WAVE_RAM2_HI",
"WAVE_RAM3_LO",
"WAVE_RAM3_HI",
"FIFO_A_LO",
"FIFO_A_HI",
"FIFO_B_LO",
"FIFO_B_HI",
0,
0,
0,
0,
// DMA
"DMA0SAD_LO",
"DMA0SAD_HI",
"DMA0DAD_LO",
"DMA0DAD_HI",
"DMA0CNT_LO",
"DMA0CNT_HI",
"DMA1SAD_LO",
"DMA1SAD_HI",
"DMA1DAD_LO",
"DMA1DAD_HI",
"DMA1CNT_LO",
"DMA1CNT_HI",
"DMA2SAD_LO",
"DMA2SAD_HI",
"DMA2DAD_LO",
"DMA2DAD_HI",
"DMA2CNT_LO",
"DMA2CNT_HI",
"DMA3SAD_LO",
"DMA3SAD_HI",
"DMA3DAD_LO",
"DMA3DAD_HI",
"DMA3CNT_LO",
"DMA3CNT_HI",
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Timers
"TM0CNT_LO",
"TM0CNT_HI",
"TM1CNT_LO",
"TM1CNT_HI",
"TM2CNT_LO",
"TM2CNT_HI",
"TM3CNT_LO",
"TM3CNT_HI",
0, 0, 0, 0, 0, 0, 0, 0,
// SIO
"SIOMULTI0",
"SIOMULTI1",
"SIOMULTI2",
"SIOMULTI3",
"SIOCNT",
"SIOMLT_SEND",
0,
0,
"KEYINPUT",
"KEYCNT",
"RCNT",
0,
0,
0,
0,
0,
"JOYCNT",
0,
0,
0,
0,
0,
0,
0,
"JOY_RECV_LO",
"JOY_RECV_HI",
"JOY_TRANS_LO",
"JOY_TRANS_HI",
"JOYSTAT",
0,
0,
0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Interrupts, etc
"IE",
"IF",
"WAITCNT",
0,
"IME"
};
static const int _isValidRegister[REG_MAX >> 1] = {
// Video
1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 0, 0, 0, 0, 0,
// Audio
1, 1, 1, 0, 1, 0, 1, 0,
1, 1, 1, 0, 1, 0, 1, 0,
1, 1, 1, 0, 1, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0,
// DMA
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Timers
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
// SIO
1, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Interrupts
1, 1, 1, 0, 1
};
static const int _isRSpecialRegister[REG_MAX >> 1] = {
// Video
0, 0, 1, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
// Audio
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 1, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0,
// DMA
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Timers
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
// SIO
1, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Interrupts
};
static const int _isWSpecialRegister[REG_MAX >> 1] = {
// Video
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Audio
1, 1, 1, 0, 1, 0, 1, 0,
1, 1, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0,
// DMA
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Timers
1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
// SIO
1, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// Interrupts
1, 1, 0, 0, 1
};
void GBAIOInit(struct GBA* gba) {
gba->memory.io[REG_DISPCNT >> 1] = 0x0080;
gba->memory.io[REG_RCNT >> 1] = RCNT_INITIAL;
gba->memory.io[REG_KEYINPUT >> 1] = 0x3FF;
gba->memory.io[REG_SOUNDBIAS >> 1] = 0x200;
gba->memory.io[REG_BG2PA >> 1] = 0x100;
gba->memory.io[REG_BG2PD >> 1] = 0x100;
gba->memory.io[REG_BG3PA >> 1] = 0x100;
gba->memory.io[REG_BG3PD >> 1] = 0x100;
if (!gba->biosVf) {
gba->memory.io[REG_VCOUNT >> 1] = 0x7E;
gba->memory.io[REG_POSTFLG >> 1] = 1;
}
}
void GBAIOWrite(struct GBA* gba, uint32_t address, uint16_t value) {
if (address < REG_SOUND1CNT_LO && (address > REG_VCOUNT || address == REG_DISPCNT)) {
value = gba->video.renderer->writeVideoRegister(gba->video.renderer, address, value);
} else {
switch (address) {
// Video
case REG_DISPSTAT:
value &= 0xFFF8;
GBAVideoWriteDISPSTAT(&gba->video, value);
return;
case REG_VCOUNT:
mLOG(GBA_IO, GAME_ERROR, "Write to read-only I/O register: %03X", address);
return;
// Audio
case REG_SOUND1CNT_LO:
GBAAudioWriteSOUND1CNT_LO(&gba->audio, value);
value &= 0x007F;
break;
case REG_SOUND1CNT_HI:
GBAAudioWriteSOUND1CNT_HI(&gba->audio, value);
break;
case REG_SOUND1CNT_X:
GBAAudioWriteSOUND1CNT_X(&gba->audio, value);
value &= 0x47FF;
break;
case REG_SOUND2CNT_LO:
GBAAudioWriteSOUND2CNT_LO(&gba->audio, value);
break;
case REG_SOUND2CNT_HI:
GBAAudioWriteSOUND2CNT_HI(&gba->audio, value);
value &= 0x47FF;
break;
case REG_SOUND3CNT_LO:
GBAAudioWriteSOUND3CNT_LO(&gba->audio, value);
value &= 0x00E0;
break;
case REG_SOUND3CNT_HI:
GBAAudioWriteSOUND3CNT_HI(&gba->audio, value);
value &= 0xE03F;
break;
case REG_SOUND3CNT_X:
GBAAudioWriteSOUND3CNT_X(&gba->audio, value);
// TODO: The low bits need to not be readable, but still 8-bit writable
value &= 0x47FF;
break;
case REG_SOUND4CNT_LO:
GBAAudioWriteSOUND4CNT_LO(&gba->audio, value);
value &= 0xFF3F;
break;
case REG_SOUND4CNT_HI:
GBAAudioWriteSOUND4CNT_HI(&gba->audio, value);
value &= 0x40FF;
break;
case REG_SOUNDCNT_LO:
GBAAudioWriteSOUNDCNT_LO(&gba->audio, value);
value &= 0xFF77;
break;
case REG_SOUNDCNT_HI:
GBAAudioWriteSOUNDCNT_HI(&gba->audio, value);
value &= 0x770F;
break;
case REG_SOUNDCNT_X:
GBAAudioWriteSOUNDCNT_X(&gba->audio, value);
value &= 0x0080;
value |= gba->memory.io[REG_SOUNDCNT_X >> 1] & 0xF;
break;
case REG_SOUNDBIAS:
GBAAudioWriteSOUNDBIAS(&gba->audio, value);
break;
case REG_WAVE_RAM0_LO:
case REG_WAVE_RAM1_LO:
case REG_WAVE_RAM2_LO:
case REG_WAVE_RAM3_LO:
GBAIOWrite32(gba, address, (gba->memory.io[(address >> 1) + 1] << 16) | value);
break;
case REG_WAVE_RAM0_HI:
case REG_WAVE_RAM1_HI:
case REG_WAVE_RAM2_HI:
case REG_WAVE_RAM3_HI:
GBAIOWrite32(gba, address - 2, gba->memory.io[(address >> 1) - 1] | (value << 16));
break;
case REG_FIFO_A_LO:
case REG_FIFO_B_LO:
GBAIOWrite32(gba, address, (gba->memory.io[(address >> 1) + 1] << 16) | value);
break;
case REG_FIFO_A_HI:
case REG_FIFO_B_HI:
GBAIOWrite32(gba, address - 2, gba->memory.io[(address >> 1) - 1] | (value << 16));
break;
// DMA
case REG_DMA0SAD_LO:
case REG_DMA0DAD_LO:
case REG_DMA1SAD_LO:
case REG_DMA1DAD_LO:
case REG_DMA2SAD_LO:
case REG_DMA2DAD_LO:
case REG_DMA3SAD_LO:
case REG_DMA3DAD_LO:
GBAIOWrite32(gba, address, (gba->memory.io[(address >> 1) + 1] << 16) | value);
break;
case REG_DMA0SAD_HI:
case REG_DMA0DAD_HI:
case REG_DMA1SAD_HI:
case REG_DMA1DAD_HI:
case REG_DMA2SAD_HI:
case REG_DMA2DAD_HI:
case REG_DMA3SAD_HI:
case REG_DMA3DAD_HI:
GBAIOWrite32(gba, address - 2, gba->memory.io[(address >> 1) - 1] | (value << 16));
break;
case REG_DMA0CNT_LO:
GBADMAWriteCNT_LO(gba, 0, value);
break;
case REG_DMA0CNT_HI:
value = GBADMAWriteCNT_HI(gba, 0, value);
break;
case REG_DMA1CNT_LO:
GBADMAWriteCNT_LO(gba, 1, value);
break;
case REG_DMA1CNT_HI:
value = GBADMAWriteCNT_HI(gba, 1, value);
break;
case REG_DMA2CNT_LO:
GBADMAWriteCNT_LO(gba, 2, value);
break;
case REG_DMA2CNT_HI:
value = GBADMAWriteCNT_HI(gba, 2, value);
break;
case REG_DMA3CNT_LO:
GBADMAWriteCNT_LO(gba, 3, value);
break;
case REG_DMA3CNT_HI:
value = GBADMAWriteCNT_HI(gba, 3, value);
break;
// Timers
case REG_TM0CNT_LO:
GBATimerWriteTMCNT_LO(gba, 0, value);
return;
case REG_TM1CNT_LO:
GBATimerWriteTMCNT_LO(gba, 1, value);
return;
case REG_TM2CNT_LO:
GBATimerWriteTMCNT_LO(gba, 2, value);
return;
case REG_TM3CNT_LO:
GBATimerWriteTMCNT_LO(gba, 3, value);
return;
case REG_TM0CNT_HI:
value &= 0x00C7;
GBATimerWriteTMCNT_HI(gba, 0, value);
break;
case REG_TM1CNT_HI:
value &= 0x00C7;
GBATimerWriteTMCNT_HI(gba, 1, value);
break;
case REG_TM2CNT_HI:
value &= 0x00C7;
GBATimerWriteTMCNT_HI(gba, 2, value);
break;
case REG_TM3CNT_HI:
value &= 0x00C7;
GBATimerWriteTMCNT_HI(gba, 3, value);
break;
// SIO
case REG_SIOCNT:
GBASIOWriteSIOCNT(&gba->sio, value);
break;
case REG_RCNT:
value &= 0xC1FF;
GBASIOWriteRCNT(&gba->sio, value);
break;
case REG_JOY_TRANS_LO:
case REG_JOY_TRANS_HI:
gba->memory.io[REG_JOYSTAT >> 1] |= JOYSTAT_TRANS_BIT;
// Fall through
case REG_SIOMLT_SEND:
case REG_JOYCNT:
case REG_JOYSTAT:
case REG_JOY_RECV_LO:
case REG_JOY_RECV_HI:
value = GBASIOWriteRegister(&gba->sio, address, value);
break;
// Interrupts and misc
case REG_KEYCNT:
value &= 0xC3FF;
gba->memory.io[address >> 1] = value;
GBATestKeypadIRQ(gba);
return;
case REG_WAITCNT:
value &= 0x5FFF;
GBAAdjustWaitstates(gba, value);
break;
case REG_IE:
GBAWriteIE(gba, value);
break;
case REG_IF:
gba->springIRQ &= ~value;
value = gba->memory.io[REG_IF >> 1] & ~value;
break;
case REG_IME:
GBAWriteIME(gba, value);
break;
case REG_MAX:
// Some bad interrupt libraries will write to this
break;
case REG_DEBUG_ENABLE:
gba->debug = value == 0xC0DE;
return;
case REG_DEBUG_FLAGS:
if (gba->debug) {
GBADebug(gba, value);
return;
}
// Fall through
default:
if (address >= REG_DEBUG_STRING && address - REG_DEBUG_STRING < sizeof(gba->debugString)) {
STORE_16LE(value, address - REG_DEBUG_STRING, gba->debugString);
return;
}
mLOG(GBA_IO, STUB, "Stub I/O register write: %03X", address);
if (address >= REG_MAX) {
mLOG(GBA_IO, GAME_ERROR, "Write to unused I/O register: %03X", address);
return;
}
break;
}
}
gba->memory.io[address >> 1] = value;
}
void GBAIOWrite8(struct GBA* gba, uint32_t address, uint8_t value) {
if (address == REG_HALTCNT) {
value &= 0x80;
if (!value) {
GBAHalt(gba);
} else {
GBAStop(gba);
}
return;
}
if (address == REG_POSTFLG) {
gba->memory.io[(address & (SIZE_IO - 1)) >> 1] = value;
return;
}
if (address >= REG_DEBUG_STRING && address - REG_DEBUG_STRING < sizeof(gba->debugString)) {
gba->debugString[address - REG_DEBUG_STRING] = value;
return;
}
if (address > SIZE_IO) {
return;
}
uint16_t value16 = value << (8 * (address & 1));
value16 |= (gba->memory.io[(address & (SIZE_IO - 1)) >> 1]) & ~(0xFF << (8 * (address & 1)));
GBAIOWrite(gba, address & 0xFFFFFFFE, value16);
}
void GBAIOWrite32(struct GBA* gba, uint32_t address, uint32_t value) {
switch (address) {
case REG_WAVE_RAM0_LO:
GBAAudioWriteWaveRAM(&gba->audio, 0, value);
break;
case REG_WAVE_RAM1_LO:
GBAAudioWriteWaveRAM(&gba->audio, 1, value);
break;
case REG_WAVE_RAM2_LO:
GBAAudioWriteWaveRAM(&gba->audio, 2, value);
break;
case REG_WAVE_RAM3_LO:
GBAAudioWriteWaveRAM(&gba->audio, 3, value);
break;
case REG_FIFO_A_LO:
case REG_FIFO_B_LO:
GBAAudioWriteFIFO(&gba->audio, address, value);
break;
case REG_DMA0SAD_LO:
value = GBADMAWriteSAD(gba, 0, value);
break;
case REG_DMA0DAD_LO:
value = GBADMAWriteDAD(gba, 0, value);
break;
case REG_DMA1SAD_LO:
value = GBADMAWriteSAD(gba, 1, value);
break;
case REG_DMA1DAD_LO:
value = GBADMAWriteDAD(gba, 1, value);
break;
case REG_DMA2SAD_LO:
value = GBADMAWriteSAD(gba, 2, value);
break;
case REG_DMA2DAD_LO:
value = GBADMAWriteDAD(gba, 2, value);
break;
case REG_DMA3SAD_LO:
value = GBADMAWriteSAD(gba, 3, value);
break;
case REG_DMA3DAD_LO:
value = GBADMAWriteDAD(gba, 3, value);
break;
default:
if (address >= REG_DEBUG_STRING && address - REG_DEBUG_STRING < sizeof(gba->debugString)) {
STORE_32LE(value, address - REG_DEBUG_STRING, gba->debugString);
return;
}
GBAIOWrite(gba, address, value & 0xFFFF);
GBAIOWrite(gba, address | 2, value >> 16);
return;
}
gba->memory.io[address >> 1] = value;
gba->memory.io[(address >> 1) + 1] = value >> 16;
}
bool GBAIOIsReadConstant(uint32_t address) {
switch (address) {
default:
return false;
case REG_BG0CNT:
case REG_BG1CNT:
case REG_BG2CNT:
case REG_BG3CNT:
case REG_WININ:
case REG_WINOUT:
case REG_BLDCNT:
case REG_BLDALPHA:
case REG_SOUND1CNT_LO:
case REG_SOUND1CNT_HI:
case REG_SOUND1CNT_X:
case REG_SOUND2CNT_LO:
case REG_SOUND2CNT_HI:
case REG_SOUND3CNT_LO:
case REG_SOUND3CNT_HI:
case REG_SOUND3CNT_X:
case REG_SOUND4CNT_LO:
case REG_SOUND4CNT_HI:
case REG_SOUNDCNT_LO:
case REG_SOUNDCNT_HI:
case REG_TM0CNT_HI:
case REG_TM1CNT_HI:
case REG_TM2CNT_HI:
case REG_TM3CNT_HI:
case REG_KEYINPUT:
case REG_KEYCNT:
case REG_IE:
return true;
}
}
uint16_t GBAIORead(struct GBA* gba, uint32_t address) {
if (!GBAIOIsReadConstant(address)) {
// Most IO reads need to disable idle removal
gba->haltPending = false;
}
switch (address) {
// Reading this takes two cycles (1N+1I), so let's remove them preemptively
case REG_TM0CNT_LO:
GBATimerUpdateRegister(gba, 0, 4);
break;
case REG_TM1CNT_LO:
GBATimerUpdateRegister(gba, 1, 4);
break;
case REG_TM2CNT_LO:
GBATimerUpdateRegister(gba, 2, 4);
break;
case REG_TM3CNT_LO:
GBATimerUpdateRegister(gba, 3, 4);
break;
case REG_KEYINPUT:
if (gba->rr && gba->rr->isPlaying(gba->rr)) {
return 0x3FF ^ gba->rr->queryInput(gba->rr);
} else {
uint16_t input = 0x3FF;
if (gba->keyCallback) {
input = gba->keyCallback->readKeys(gba->keyCallback);
if (gba->keySource) {
*gba->keySource = input;
}
} else if (gba->keySource) {
input = *gba->keySource;
}
if (!gba->allowOpposingDirections) {
unsigned rl = input & 0x030;
unsigned ud = input & 0x0C0;
input &= 0x30F;
if (rl != 0x030) {
input |= rl;
}
if (ud != 0x0C0) {
input |= ud;
}
}
if (gba->rr && gba->rr->isRecording(gba->rr)) {
gba->rr->logInput(gba->rr, input);
}
return 0x3FF ^ input;
}
case REG_SIOCNT:
return gba->sio.siocnt;
case REG_RCNT:
return gba->sio.rcnt;
case REG_BG0HOFS:
case REG_BG0VOFS:
case REG_BG1HOFS:
case REG_BG1VOFS:
case REG_BG2HOFS:
case REG_BG2VOFS:
case REG_BG3HOFS:
case REG_BG3VOFS:
case REG_BG2PA:
case REG_BG2PB:
case REG_BG2PC:
case REG_BG2PD:
case REG_BG2X_LO:
case REG_BG2X_HI:
case REG_BG2Y_LO:
case REG_BG2Y_HI:
case REG_BG3PA:
case REG_BG3PB:
case REG_BG3PC:
case REG_BG3PD:
case REG_BG3X_LO:
case REG_BG3X_HI:
case REG_BG3Y_LO:
case REG_BG3Y_HI:
case REG_WIN0H:
case REG_WIN1H:
case REG_WIN0V:
case REG_WIN1V:
case REG_MOSAIC:
case REG_BLDY:
case REG_FIFO_A_LO:
case REG_FIFO_A_HI:
case REG_FIFO_B_LO:
case REG_FIFO_B_HI:
case REG_DMA0SAD_LO:
case REG_DMA0SAD_HI:
case REG_DMA0DAD_LO:
case REG_DMA0DAD_HI:
case REG_DMA1SAD_LO:
case REG_DMA1SAD_HI:
case REG_DMA1DAD_LO:
case REG_DMA1DAD_HI:
case REG_DMA2SAD_LO:
case REG_DMA2SAD_HI:
case REG_DMA2DAD_LO:
case REG_DMA2DAD_HI:
case REG_DMA3SAD_LO:
case REG_DMA3SAD_HI:
case REG_DMA3DAD_LO:
case REG_DMA3DAD_HI:
// Write-only register
mLOG(GBA_IO, GAME_ERROR, "Read from write-only I/O register: %03X", address);
return GBALoadBad(gba->cpu);
case REG_DMA0CNT_LO:
case REG_DMA1CNT_LO:
case REG_DMA2CNT_LO:
case REG_DMA3CNT_LO:
// Write-only register
mLOG(GBA_IO, GAME_ERROR, "Read from write-only I/O register: %03X", address);
return 0;
case REG_JOY_RECV_LO:
case REG_JOY_RECV_HI:
gba->memory.io[REG_JOYSTAT >> 1] &= ~JOYSTAT_RECV_BIT;
break;
case REG_SOUNDBIAS:
case REG_POSTFLG:
mLOG(GBA_IO, STUB, "Stub I/O register read: %03x", address);
break;
case REG_SOUND1CNT_LO:
case REG_SOUND1CNT_HI:
case REG_SOUND1CNT_X:
case REG_SOUND2CNT_LO:
case REG_SOUND2CNT_HI:
case REG_SOUND3CNT_LO:
case REG_SOUND3CNT_HI:
case REG_SOUND3CNT_X:
case REG_SOUND4CNT_LO:
case REG_SOUND4CNT_HI:
case REG_SOUNDCNT_LO:
case REG_SOUNDCNT_HI:
if (!GBAudioEnableIsEnable(gba->memory.io[REG_SOUNDCNT_X >> 1])) {
// TODO: Is writing allowed when the circuit is disabled?
return 0;
}
// Fall through
case REG_DISPCNT:
case REG_DISPSTAT:
case REG_VCOUNT:
case REG_BG0CNT:
case REG_BG1CNT:
case REG_BG2CNT:
case REG_BG3CNT:
case REG_WININ:
case REG_WINOUT:
case REG_BLDCNT:
case REG_BLDALPHA:
case REG_SOUNDCNT_X:
case REG_WAVE_RAM0_LO:
case REG_WAVE_RAM0_HI:
case REG_WAVE_RAM1_LO:
case REG_WAVE_RAM1_HI:
case REG_WAVE_RAM2_LO:
case REG_WAVE_RAM2_HI:
case REG_WAVE_RAM3_LO:
case REG_WAVE_RAM3_HI:
case REG_DMA0CNT_HI:
case REG_DMA1CNT_HI:
case REG_DMA2CNT_HI:
case REG_DMA3CNT_HI:
case REG_TM0CNT_HI:
case REG_TM1CNT_HI:
case REG_TM2CNT_HI:
case REG_TM3CNT_HI:
case REG_KEYCNT:
case REG_SIOMULTI0:
case REG_SIOMULTI1:
case REG_SIOMULTI2:
case REG_SIOMULTI3:
case REG_SIOMLT_SEND:
case REG_JOYCNT:
case REG_JOY_TRANS_LO:
case REG_JOY_TRANS_HI:
case REG_JOYSTAT:
case REG_IE:
case REG_IF:
case REG_WAITCNT:
case REG_IME:
// Handled transparently by registers
break;
case REG_MAX:
// Some bad interrupt libraries will read from this
case 0x066:
case 0x06E:
case 0x076:
case 0x07A:
case 0x07E:
case 0x086:
case 0x08A:
case 0x136:
case 0x142:
case 0x15A:
case 0x206:
mLOG(GBA_IO, GAME_ERROR, "Read from unused I/O register: %03X", address);
return 0;
case REG_DEBUG_ENABLE:
if (gba->debug) {
return 0x1DEA;
}
// Fall through
default:
mLOG(GBA_IO, GAME_ERROR, "Read from unused I/O register: %03X", address);
return GBALoadBad(gba->cpu);
}
return gba->memory.io[address >> 1];
}
void GBAIOSerialize(struct GBA* gba, struct GBASerializedState* state) {
int i;
for (i = 0; i < REG_MAX; i += 2) {
if (_isRSpecialRegister[i >> 1]) {
STORE_16(gba->memory.io[i >> 1], i, state->io);
} else if (_isValidRegister[i >> 1]) {
uint16_t reg = GBAIORead(gba, i);
STORE_16(reg, i, state->io);
}
}
for (i = 0; i < 4; ++i) {
STORE_16(gba->memory.io[(REG_DMA0CNT_LO + i * 12) >> 1], (REG_DMA0CNT_LO + i * 12), state->io);
STORE_16(gba->timers[i].reload, 0, &state->timers[i].reload);
STORE_32(gba->timers[i].lastEvent - mTimingCurrentTime(&gba->timing), 0, &state->timers[i].lastEvent);
STORE_32(gba->timers[i].event.when - mTimingCurrentTime(&gba->timing), 0, &state->timers[i].nextEvent);
STORE_32(gba->timers[i].irq.when - mTimingCurrentTime(&gba->timing), 0, &state->timers[i].nextIrq);
STORE_32(gba->timers[i].flags, 0, &state->timers[i].flags);
STORE_32(gba->memory.dma[i].nextSource, 0, &state->dma[i].nextSource);
STORE_32(gba->memory.dma[i].nextDest, 0, &state->dma[i].nextDest);
STORE_32(gba->memory.dma[i].nextCount, 0, &state->dma[i].nextCount);
STORE_32(gba->memory.dma[i].when, 0, &state->dma[i].when);
}
state->dmaTransferRegister = gba->memory.dmaTransferRegister;
GBAHardwareSerialize(&gba->memory.hw, state);
}
void GBAIODeserialize(struct GBA* gba, const struct GBASerializedState* state) {
int i;
for (i = 0; i < REG_MAX; i += 2) {
if (_isWSpecialRegister[i >> 1]) {
LOAD_16(gba->memory.io[i >> 1], i, state->io);
} else if (_isValidRegister[i >> 1]) {
uint16_t reg;
LOAD_16(reg, i, state->io);
GBAIOWrite(gba, i, reg);
}
}
uint32_t when;
for (i = 0; i < 4; ++i) {
LOAD_16(gba->timers[i].reload, 0, &state->timers[i].reload);
LOAD_32(gba->timers[i].flags, 0, &state->timers[i].flags);
if (i > 0 && GBATimerFlagsIsCountUp(gba->timers[i].flags)) {
// Overwrite invalid values in savestate
gba->timers[i].lastEvent = 0;
} else {
LOAD_32(when, 0, &state->timers[i].lastEvent);
gba->timers[i].lastEvent = when + mTimingCurrentTime(&gba->timing);
}
LOAD_32(when, 0, &state->timers[i].nextEvent);
if (GBATimerFlagsIsEnable(gba->timers[i].flags)) {
mTimingSchedule(&gba->timing, &gba->timers[i].event, when);
}
LOAD_32(when, 0, &state->timers[i].nextIrq);
if (GBATimerFlagsIsIrqPending(gba->timers[i].flags)) {
mTimingSchedule(&gba->timing, &gba->timers[i].irq, when);
}
LOAD_16(gba->memory.dma[i].reg, (REG_DMA0CNT_HI + i * 12), state->io);
LOAD_32(gba->memory.dma[i].nextSource, 0, &state->dma[i].nextSource);
LOAD_32(gba->memory.dma[i].nextDest, 0, &state->dma[i].nextDest);
LOAD_32(gba->memory.dma[i].nextCount, 0, &state->dma[i].nextCount);
LOAD_32(gba->memory.dma[i].when, 0, &state->dma[i].when);
if (GBADMARegisterGetTiming(gba->memory.dma[i].reg) != GBA_DMA_TIMING_NOW) {
GBADMASchedule(gba, i, &gba->memory.dma[i]);
}
}
GBAAudioWriteSOUNDCNT_X(&gba->audio, gba->memory.io[REG_SOUNDCNT_X >> 1]);
gba->memory.dmaTransferRegister = state->dmaTransferRegister;
GBADMAUpdate(gba);
GBAHardwareDeserialize(&gba->memory.hw, state);
}
| 12,282 |
537 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.25 at 05:48:09 PM CEST
//
package es.rickyepoderi.wbxml.bind.wvcsp;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"clientID",
"result",
"nonce",
"digestSchema",
"sessionID",
"keepAliveTime",
"capabilityRequest"
})
@XmlRootElement(name = "Login-Response")
public class LoginResponse {
@XmlElement(name = "ClientID", required = true)
protected ClientID clientID;
@XmlElement(name = "Result", required = true)
protected Result result;
@XmlElement(name = "Nonce")
protected String nonce;
@XmlElement(name = "DigestSchema")
protected String digestSchema;
@XmlElement(name = "SessionID")
protected String sessionID;
@XmlElement(name = "KeepAliveTime")
protected String keepAliveTime;
@XmlElement(name = "CapabilityRequest")
protected String capabilityRequest;
/**
* Gets the value of the clientID property.
*
* @return
* possible object is
* {@link ClientID }
*
*/
public ClientID getClientID() {
return clientID;
}
/**
* Sets the value of the clientID property.
*
* @param value
* allowed object is
* {@link ClientID }
*
*/
public void setClientID(ClientID value) {
this.clientID = value;
}
/**
* Gets the value of the result property.
*
* @return
* possible object is
* {@link Result }
*
*/
public Result getResult() {
return result;
}
/**
* Sets the value of the result property.
*
* @param value
* allowed object is
* {@link Result }
*
*/
public void setResult(Result value) {
this.result = value;
}
/**
* Gets the value of the nonce property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNonce() {
return nonce;
}
/**
* Sets the value of the nonce property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNonce(String value) {
this.nonce = value;
}
/**
* Gets the value of the digestSchema property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDigestSchema() {
return digestSchema;
}
/**
* Sets the value of the digestSchema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDigestSchema(String value) {
this.digestSchema = value;
}
/**
* Gets the value of the sessionID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSessionID() {
return sessionID;
}
/**
* Sets the value of the sessionID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSessionID(String value) {
this.sessionID = value;
}
/**
* Gets the value of the keepAliveTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeepAliveTime() {
return keepAliveTime;
}
/**
* Sets the value of the keepAliveTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeepAliveTime(String value) {
this.keepAliveTime = value;
}
/**
* Gets the value of the capabilityRequest property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCapabilityRequest() {
return capabilityRequest;
}
/**
* Sets the value of the capabilityRequest property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCapabilityRequest(String value) {
this.capabilityRequest = value;
}
}
| 2,112 |
22,779 | <gh_stars>1000+
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp 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.
*/
package org.jkiss.dbeaver.lang.parser;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.jkiss.dbeaver.lang.SCMToken;
public class LiteralRule implements IRule {
private static Token WORD_TOKEN = new Token(SCMToken.LITERAL);
@Override
public IToken evaluate(ICharacterScanner scanner) {
int c = scanner.read();
if (c != ICharacterScanner.EOF && isWordStart((char) c)) {
do {
c = scanner.read();
}
while (c != ICharacterScanner.EOF && isWordPart((char) c));
scanner.unread();
return WORD_TOKEN;
}
scanner.unread();
return Token.UNDEFINED;
}
private boolean isWordStart(char c) {
return Character.isLetter(c);
}
private boolean isWordPart(char c) {
return Character.isJavaIdentifierPart(c);
}
}
| 618 |
6,304 | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// given a prospective edge, compute its initial winding by projecting a ray
// if the ray hits another edge
// if the edge doesn't have a winding yet, hop up to that edge and start over
// concern : check for hops forming a loop
// if the edge is unsortable, or
// the intersection is nearly at the ends, or
// the tangent at the intersection is nearly coincident to the ray,
// choose a different ray and try again
// concern : if it is unable to succeed after N tries, try another edge? direction?
// if no edge is hit, compute the winding directly
// given the top span, project the most perpendicular ray and look for intersections
// let's try up and then down. What the hey
// bestXY is initialized by caller with basePt
#include "src/core/SkTSort.h"
#include "src/pathops/SkOpContour.h"
#include "src/pathops/SkOpSegment.h"
#include "src/pathops/SkPathOpsCurve.h"
#include <utility>
enum class SkOpRayDir {
kLeft,
kTop,
kRight,
kBottom,
};
#if DEBUG_WINDING
const char* gDebugRayDirName[] = {
"kLeft",
"kTop",
"kRight",
"kBottom"
};
#endif
static int xy_index(SkOpRayDir dir) {
return static_cast<int>(dir) & 1;
}
static SkScalar pt_xy(const SkPoint& pt, SkOpRayDir dir) {
return (&pt.fX)[xy_index(dir)];
}
static SkScalar pt_yx(const SkPoint& pt, SkOpRayDir dir) {
return (&pt.fX)[!xy_index(dir)];
}
static double pt_dxdy(const SkDVector& v, SkOpRayDir dir) {
return (&v.fX)[xy_index(dir)];
}
static double pt_dydx(const SkDVector& v, SkOpRayDir dir) {
return (&v.fX)[!xy_index(dir)];
}
static SkScalar rect_side(const SkRect& r, SkOpRayDir dir) {
return (&r.fLeft)[static_cast<int>(dir)];
}
static bool sideways_overlap(const SkRect& rect, const SkPoint& pt, SkOpRayDir dir) {
int i = !xy_index(dir);
return approximately_between((&rect.fLeft)[i], (&pt.fX)[i], (&rect.fRight)[i]);
}
static bool less_than(SkOpRayDir dir) {
return static_cast<bool>((static_cast<int>(dir) & 2) == 0);
}
static bool ccw_dxdy(const SkDVector& v, SkOpRayDir dir) {
bool vPartPos = pt_dydx(v, dir) > 0;
bool leftBottom = ((static_cast<int>(dir) + 1) & 2) != 0;
return vPartPos == leftBottom;
}
struct SkOpRayHit {
SkOpRayDir makeTestBase(SkOpSpan* span, double t) {
fNext = nullptr;
fSpan = span;
fT = span->t() * (1 - t) + span->next()->t() * t;
SkOpSegment* segment = span->segment();
fSlope = segment->dSlopeAtT(fT);
fPt = segment->ptAtT(fT);
fValid = true;
return fabs(fSlope.fX) < fabs(fSlope.fY) ? SkOpRayDir::kLeft : SkOpRayDir::kTop;
}
SkOpRayHit* fNext;
SkOpSpan* fSpan;
SkPoint fPt;
double fT;
SkDVector fSlope;
bool fValid;
};
void SkOpContour::rayCheck(const SkOpRayHit& base, SkOpRayDir dir, SkOpRayHit** hits,
SkArenaAlloc* allocator) {
// if the bounds extreme is outside the best, we're done
SkScalar baseXY = pt_xy(base.fPt, dir);
SkScalar boundsXY = rect_side(fBounds, dir);
bool checkLessThan = less_than(dir);
if (!approximately_equal(baseXY, boundsXY) && (baseXY < boundsXY) == checkLessThan) {
return;
}
SkOpSegment* testSegment = &fHead;
do {
testSegment->rayCheck(base, dir, hits, allocator);
} while ((testSegment = testSegment->next()));
}
void SkOpSegment::rayCheck(const SkOpRayHit& base, SkOpRayDir dir, SkOpRayHit** hits,
SkArenaAlloc* allocator) {
if (!sideways_overlap(fBounds, base.fPt, dir)) {
return;
}
SkScalar baseXY = pt_xy(base.fPt, dir);
SkScalar boundsXY = rect_side(fBounds, dir);
bool checkLessThan = less_than(dir);
if (!approximately_equal(baseXY, boundsXY) && (baseXY < boundsXY) == checkLessThan) {
return;
}
double tVals[3];
SkScalar baseYX = pt_yx(base.fPt, dir);
int roots = (*CurveIntercept[fVerb * 2 + xy_index(dir)])(fPts, fWeight, baseYX, tVals);
for (int index = 0; index < roots; ++index) {
double t = tVals[index];
if (base.fSpan->segment() == this && approximately_equal(base.fT, t)) {
continue;
}
SkDVector slope;
SkPoint pt;
SkDEBUGCODE(sk_bzero(&slope, sizeof(slope)));
bool valid = false;
if (approximately_zero(t)) {
pt = fPts[0];
} else if (approximately_equal(t, 1)) {
pt = fPts[SkPathOpsVerbToPoints(fVerb)];
} else {
SkASSERT(between(0, t, 1));
pt = this->ptAtT(t);
if (SkDPoint::ApproximatelyEqual(pt, base.fPt)) {
if (base.fSpan->segment() == this) {
continue;
}
} else {
SkScalar ptXY = pt_xy(pt, dir);
if (!approximately_equal(baseXY, ptXY) && (baseXY < ptXY) == checkLessThan) {
continue;
}
slope = this->dSlopeAtT(t);
if (fVerb == SkPath::kCubic_Verb && base.fSpan->segment() == this
&& roughly_equal(base.fT, t)
&& SkDPoint::RoughlyEqual(pt, base.fPt)) {
#if DEBUG_WINDING
SkDebugf("%s (rarely expect this)\n", __FUNCTION__);
#endif
continue;
}
if (fabs(pt_dydx(slope, dir) * 10000) > fabs(pt_dxdy(slope, dir))) {
valid = true;
}
}
}
SkOpSpan* span = this->windingSpanAtT(t);
if (!span) {
valid = false;
} else if (!span->windValue() && !span->oppValue()) {
continue;
}
SkOpRayHit* newHit = allocator->make<SkOpRayHit>();
newHit->fNext = *hits;
newHit->fPt = pt;
newHit->fSlope = slope;
newHit->fSpan = span;
newHit->fT = t;
newHit->fValid = valid;
*hits = newHit;
}
}
SkOpSpan* SkOpSegment::windingSpanAtT(double tHit) {
SkOpSpan* span = &fHead;
SkOpSpanBase* next;
do {
next = span->next();
if (approximately_equal(tHit, next->t())) {
return nullptr;
}
if (tHit < next->t()) {
return span;
}
} while (!next->final() && (span = next->upCast()));
return nullptr;
}
static bool hit_compare_x(const SkOpRayHit* a, const SkOpRayHit* b) {
return a->fPt.fX < b->fPt.fX;
}
static bool reverse_hit_compare_x(const SkOpRayHit* a, const SkOpRayHit* b) {
return b->fPt.fX < a->fPt.fX;
}
static bool hit_compare_y(const SkOpRayHit* a, const SkOpRayHit* b) {
return a->fPt.fY < b->fPt.fY;
}
static bool reverse_hit_compare_y(const SkOpRayHit* a, const SkOpRayHit* b) {
return b->fPt.fY < a->fPt.fY;
}
static double get_t_guess(int tTry, int* dirOffset) {
double t = 0.5;
*dirOffset = tTry & 1;
int tBase = tTry >> 1;
int tBits = 0;
while (tTry >>= 1) {
t /= 2;
++tBits;
}
if (tBits) {
int tIndex = (tBase - 1) & ((1 << tBits) - 1);
t += t * 2 * tIndex;
}
return t;
}
bool SkOpSpan::sortableTop(SkOpContour* contourHead) {
SkSTArenaAlloc<1024> allocator;
int dirOffset;
double t = get_t_guess(fTopTTry++, &dirOffset);
SkOpRayHit hitBase;
SkOpRayDir dir = hitBase.makeTestBase(this, t);
if (hitBase.fSlope.fX == 0 && hitBase.fSlope.fY == 0) {
return false;
}
SkOpRayHit* hitHead = &hitBase;
dir = static_cast<SkOpRayDir>(static_cast<int>(dir) + dirOffset);
if (hitBase.fSpan && hitBase.fSpan->segment()->verb() > SkPath::kLine_Verb
&& !pt_dydx(hitBase.fSlope, dir)) {
return false;
}
SkOpContour* contour = contourHead;
do {
if (!contour->count()) {
continue;
}
contour->rayCheck(hitBase, dir, &hitHead, &allocator);
} while ((contour = contour->next()));
// sort hits
SkSTArray<1, SkOpRayHit*> sorted;
SkOpRayHit* hit = hitHead;
while (hit) {
sorted.push_back(hit);
hit = hit->fNext;
}
int count = sorted.count();
SkTQSort(sorted.begin(), sorted.end(),
xy_index(dir) ? less_than(dir) ? hit_compare_y : reverse_hit_compare_y
: less_than(dir) ? hit_compare_x : reverse_hit_compare_x);
// verify windings
#if DEBUG_WINDING
SkDebugf("%s dir=%s seg=%d t=%1.9g pt=(%1.9g,%1.9g)\n", __FUNCTION__,
gDebugRayDirName[static_cast<int>(dir)], hitBase.fSpan->segment()->debugID(),
hitBase.fT, hitBase.fPt.fX, hitBase.fPt.fY);
for (int index = 0; index < count; ++index) {
hit = sorted[index];
SkOpSpan* span = hit->fSpan;
SkOpSegment* hitSegment = span ? span->segment() : nullptr;
bool operand = span ? hitSegment->operand() : false;
bool ccw = ccw_dxdy(hit->fSlope, dir);
SkDebugf("%s [%d] valid=%d operand=%d span=%d ccw=%d ", __FUNCTION__, index,
hit->fValid, operand, span ? span->debugID() : -1, ccw);
if (span) {
hitSegment->dumpPtsInner();
}
SkDebugf(" t=%1.9g pt=(%1.9g,%1.9g) slope=(%1.9g,%1.9g)\n", hit->fT,
hit->fPt.fX, hit->fPt.fY, hit->fSlope.fX, hit->fSlope.fY);
}
#endif
const SkPoint* last = nullptr;
int wind = 0;
int oppWind = 0;
for (int index = 0; index < count; ++index) {
hit = sorted[index];
if (!hit->fValid) {
return false;
}
bool ccw = ccw_dxdy(hit->fSlope, dir);
// SkASSERT(!approximately_zero(hit->fT) || !hit->fValid);
SkOpSpan* span = hit->fSpan;
if (!span) {
return false;
}
SkOpSegment* hitSegment = span->segment();
if (span->windValue() == 0 && span->oppValue() == 0) {
continue;
}
if (last && SkDPoint::ApproximatelyEqual(*last, hit->fPt)) {
return false;
}
if (index < count - 1) {
const SkPoint& next = sorted[index + 1]->fPt;
if (SkDPoint::ApproximatelyEqual(next, hit->fPt)) {
return false;
}
}
bool operand = hitSegment->operand();
if (operand) {
using std::swap;
swap(wind, oppWind);
}
int lastWind = wind;
int lastOpp = oppWind;
int windValue = ccw ? -span->windValue() : span->windValue();
int oppValue = ccw ? -span->oppValue() : span->oppValue();
wind += windValue;
oppWind += oppValue;
bool sumSet = false;
int spanSum = span->windSum();
int windSum = SkOpSegment::UseInnerWinding(lastWind, wind) ? wind : lastWind;
if (spanSum == SK_MinS32) {
span->setWindSum(windSum);
sumSet = true;
} else {
// the need for this condition suggests that UseInnerWinding is flawed
// happened when last = 1 wind = -1
#if 0
SkASSERT((hitSegment->isXor() ? (windSum & 1) == (spanSum & 1) : windSum == spanSum)
|| (abs(wind) == abs(lastWind)
&& (windSum ^ wind ^ lastWind) == spanSum));
#endif
}
int oSpanSum = span->oppSum();
int oppSum = SkOpSegment::UseInnerWinding(lastOpp, oppWind) ? oppWind : lastOpp;
if (oSpanSum == SK_MinS32) {
span->setOppSum(oppSum);
} else {
#if 0
SkASSERT(hitSegment->oppXor() ? (oppSum & 1) == (oSpanSum & 1) : oppSum == oSpanSum
|| (abs(oppWind) == abs(lastOpp)
&& (oppSum ^ oppWind ^ lastOpp) == oSpanSum));
#endif
}
if (sumSet) {
if (this->globalState()->phase() == SkOpPhase::kFixWinding) {
hitSegment->contour()->setCcw(ccw);
} else {
(void) hitSegment->markAndChaseWinding(span, span->next(), windSum, oppSum, nullptr);
(void) hitSegment->markAndChaseWinding(span->next(), span, windSum, oppSum, nullptr);
}
}
if (operand) {
using std::swap;
swap(wind, oppWind);
}
last = &hit->fPt;
this->globalState()->bumpNested();
}
return true;
}
SkOpSpan* SkOpSegment::findSortableTop(SkOpContour* contourHead) {
SkOpSpan* span = &fHead;
SkOpSpanBase* next;
do {
next = span->next();
if (span->done()) {
continue;
}
if (span->windSum() != SK_MinS32) {
return span;
}
if (span->sortableTop(contourHead)) {
return span;
}
} while (!next->final() && (span = next->upCast()));
return nullptr;
}
SkOpSpan* SkOpContour::findSortableTop(SkOpContour* contourHead) {
bool allDone = true;
if (fCount) {
SkOpSegment* testSegment = &fHead;
do {
if (testSegment->done()) {
continue;
}
allDone = false;
SkOpSpan* result = testSegment->findSortableTop(contourHead);
if (result) {
return result;
}
} while ((testSegment = testSegment->next()));
}
if (allDone) {
fDone = true;
}
return nullptr;
}
SkOpSpan* FindSortableTop(SkOpContourHead* contourHead) {
for (int index = 0; index < SkOpGlobalState::kMaxWindingTries; ++index) {
SkOpContour* contour = contourHead;
do {
if (contour->done()) {
continue;
}
SkOpSpan* result = contour->findSortableTop(contourHead);
if (result) {
return result;
}
} while ((contour = contour->next()));
}
return nullptr;
}
| 6,858 |
32,544 | <reponame>DBatOWL/tutorials
package com.baeldung.jvmbitversion;
import com.sun.jna.Platform;
public class JVMBitVersion {
public String getUsingSystemClass() {
return System.getProperty("sun.arch.data.model") + "-bit";
}
public String getUsingNativeClass() {
if (com.sun.jna.Native.POINTER_SIZE == 8) {
return "64-bit";
} else if (com.sun.jna.Native.POINTER_SIZE == 4) {
return "32-bit";
} else
return "unknown";
}
public boolean getUsingPlatformClass() {
return (Platform.is64Bit());
}
}
| 265 |
14,425 | <reponame>amahussein/hadoop
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred.nativetask.utils;
import org.apache.hadoop.thirdparty.com.google.common.primitives.Ints;
import org.apache.hadoop.thirdparty.com.google.common.primitives.Longs;
import org.junit.Assert;
import org.junit.Test;
import org.apache.hadoop.mapred.nativetask.util.BytesUtil;
public class TestBytesUtil {
@Test
public void testBytesIntConversion() {
final int a = 1000;
final byte[] intBytes = Ints.toByteArray(a);
Assert.assertEquals(a, BytesUtil.toInt(intBytes, 0));
}
@Test
public void testBytesLongConversion() {
final long l = 1000000L;
final byte[] longBytes = Longs.toByteArray(l);
Assert.assertEquals(l, BytesUtil.toLong(longBytes, 0));
}
@Test
public void testBytesFloatConversion() {
final float f = 3.14f;
final byte[] floatBytes = BytesUtil.toBytes(f);
Assert.assertEquals(f, BytesUtil.toFloat(floatBytes), 0.0f);
}
@Test
public void testBytesDoubleConversion() {
final double d = 3.14;
final byte[] doubleBytes = BytesUtil.toBytes(d);
Assert.assertEquals(d, BytesUtil.toDouble(doubleBytes), 0.0);
}
@Test
public void testToStringBinary() {
Assert.assertEquals("\\x01\\x02ABC",
BytesUtil.toStringBinary(new byte[] { 1, 2, 65, 66, 67 }));
Assert.assertEquals("\\x10\\x11",
BytesUtil.toStringBinary(new byte[] { 16, 17 }));
}
}
| 753 |
3,227 | <reponame>ffteja/cgal<gh_stars>1000+
/*!
* \ingroup PkgArrangementOnSurface2ConceptsTraits
* \cgalConcept
*
* A model of the concept `ArrangementContractedBottomTraits_2` must be used
* when the parameter space of the surface, the arrangement is embedded on, is
* contracted on the bottom side and curves inserted into the arrangement are
* expected to reach this boundary side. A model of this concept can handle
* curves that reach the bottom boundary side when it is contracted.
*
* \cgalRefines `ArrangementBottomSideTraits_2`
*
* \sa `ArrangementContractedLeftTraits_2`,
* `ArrangementContractedRightTraits_2`,
* `ArrangementContractedTopTraits_2`,
* `ArrangementClosedBottomTraits_2`,
* `ArrangementContractedBottomTraits_2`, and
* `ArrangementIdentifiedHorizontalTraits_2`
*/
class ArrangementContractedBottomTraits_2 {
public:
/// \name Categories
/// @{
//! Must be convertible to `CGAL::Arr_contracted_side_tag`.
typedef unspecified_type Bottom_side_category;
/// @}
/// \name Types
/// @{
/// @}
/// \name Functor Types
/// @{
/// \name Accessing Functor Objects
/// @{
/// @}
}
| 384 |
900 | package foam.dao;
import foam.core.FObject;
import foam.core.Property;
import foam.core.X;
/**
* A ProxyDAO that injects a new ID for any item that doesn't already have one.
*
* TODO(braden): Support arbitrary sequence numbering. In practice it's ID 99% of the time.
* TODO(braden): Also assumes that the ID is an int.
*/
public class SeqNoDAO extends ProxyDAO {
private int nextID = -1;
public SeqNoDAO(DAO delegate) {
super(delegate);
}
private void findMax(X x) throws DAOInternalException, DAOException {
MLang.MaxSink sink = (MLang.MaxSink) getDelegate().select(x, MLang.MAX(getModel().getID()));
if (sink != null) {
Integer max = (Integer) sink.getMax();
nextID = max == null ? 1 : max.intValue() + 1;
}
}
@Override
public FObject put(X x, FObject o) throws DAOInternalException, DAOException {
// Check if the object has an ID value.
Property<Integer> ID = getModel().getID();
int id = ID.get(o);
if (id == 0) {
if (nextID < 0) findMax(x);
o = o.fclone();
ID.set(o, nextID);
nextID++;
}
return getDelegate().put(x, o);
}
}
| 434 |
701 | <filename>sources/kernel/riscv64/sifive_uart.h
#pragma once
#include <uart/uart.h>
// todo: find uart addr from device tree
#define SIFIVE_UART0_BASE 0x10010000
#define SIFIVE_UART1_BASE 0x10011000
enum sifive_uart_registers
{
SIFIVE_UART_TX_DATA = 0,
SIFIVE_UART_RX_DATA = 4,
SIFIVE_UART_TX_CTRL = 8,
SIFIVE_UART_RX_CTRL = 12,
SIFIVE_UART_INT_ENABLE = 16,
SIFIVE_UART_INT_PENDING = 20,
SIFIVE_UART_BAUD_DIV = 24,
};
#define SIFIVE_UART_TX_TRANSMIT 0xff
#define SIFIVE_UART_TX_FULL (1 << 31)
#define SIFIVE_UART_RX_RECEIVE 0xff
#define SIFIVE_UART_RX_EMPTY (1 << 31)
enum sifive_uart_tx_control_bit
{
SIFIVE_UART_TX_ENABLE = (1 << 0), // size: 1
SIFIVE_UART_TX_STOP_NUM = (1 << 1), // size: 1
SIFIVE_UART_TX_WATERMARK = (1 << 16), // size: 2
};
enum sifive_uart_rx_control_bit
{
SIFIVE_UART_RX_ENABLE = (1 << 0),
SIFIVE_UART_RX_WATERMARK = (1 << 16),
};
enum sifive_uart_int_enable_bit
{
SIFIVE_UART_INT_TX_WATERMARK_ENABLE = (1 << 0),
SIFIVE_UART_INT_RX_WATERMARK_DISABLE = (1 << 1),
};
enum sifive_uart_int_pending_bit
{
SIFIVE_UART_INT_TX_WATERMARK_PENDING = (1 << 0),
SIFIVE_UART_INT_RX_WATERMARK_PENDING = (1 << 1),
};
#define SIFIVE_UART_BAUD_DIV_BIT (0xfffff)
Uart *sifive_uart_init(void);
| 663 |
1,188 | <gh_stars>1000+
/*
* Copyright 2017 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.javadeobfuscator.deobfuscator.transformers.stringer.v3.utils;
import com.javadeobfuscator.deobfuscator.transformers.MethodFinder;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.reflect.Modifier;
import java.util.*;
public class InvokedynamicMethodFinder implements MethodFinder {
@Override
public Map<ClassNode, Set<MethodNode>> find(Collection<ClassNode> classes) {
Map<ClassNode, Set<MethodNode>> result = new HashMap<>();
for (ClassNode classNode : classes) {
Set<MethodNode> remove = new HashSet<>();
for (MethodNode methodNode : classNode.methods) {
if (Modifier.isPrivate(methodNode.access)
&& Modifier.isStatic(methodNode.access)
&& methodNode.desc.equals("(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")
&& methodNode.name.length() == 2) {
remove.add(methodNode);
}
}
if (!remove.isEmpty()) {
result.put(classNode, remove);
}
}
return result;
}
}
| 712 |
575 | <reponame>Ron423c/chromium<filename>chrome/browser/ui/webui/chromeos/login/testapi/oobe_test_api_handler.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 "chrome/browser/ui/webui/chromeos/login/testapi/oobe_test_api_handler.h"
#include "build/branding_buildflags.h"
namespace chromeos {
OobeTestAPIHandler::OobeTestAPIHandler(JSCallsContainer* js_calls_container)
: BaseWebUIHandler(js_calls_container) {
DCHECK(js_calls_container);
}
OobeTestAPIHandler::~OobeTestAPIHandler() {}
void OobeTestAPIHandler::DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) {}
void OobeTestAPIHandler::Initialize() {}
void OobeTestAPIHandler::GetAdditionalParameters(base::DictionaryValue* dict) {
dict->SetBoolean("isBrandedBuild", BUILDFLAG(GOOGLE_CHROME_BRANDING));
}
} // namespace chromeos
| 319 |
320 | <gh_stars>100-1000
import logging
import datetime
import xml.etree.cElementTree as ET
import core
from core.helpers import Url
logging = logging.getLogger(__name__)
'''
Does not supply rss feed -- backlog searches only.
'''
def search(imdbid, term):
proxy_enabled = core.CONFIG['Server']['Proxy']['enabled']
logging.info('Searching Zooqle for {}.'.format(term))
url = 'https://zooqle.com/search?q={}&fmt=rss'.format(term)
try:
if proxy_enabled and core.proxy.whitelist('https://www.zooqle.com') is True:
response = Url.open(url, proxy_bypass=True).text
else:
response = Url.open(url).text
if response:
return _parse(response, imdbid)
else:
return []
except (SystemExit, KeyboardInterrupt):
raise
except Exception as e:
logging.error('Zooqle search failed.', exc_info=True)
return []
def get_rss():
return []
def _parse(xml, imdbid):
logging.info('Parsing Zooqle results.')
tree = ET.fromstring(xml)
items = tree[0].findall('item')
results = []
for i in items:
result = {}
try:
result['score'] = 0
size, suffix = i.find('description').text.strip().split(', ')[-1].split(' ')
m = (1024 ** 2) if suffix == 'MB' else (1024 ** 3)
result['size'] = int(float(size.replace(',', '')) * m)
result['status'] = 'Available'
pd = i.find('pubDate').text
result['pubdate'] = datetime.datetime.strftime(datetime.datetime.strptime(pd, '%a, %d %b %Y %H:%M:%S %z'), '%d %b %Y')
result['title'] = i.find('title').text
result['imdbid'] = imdbid
result['indexer'] = 'Zooqle'
result['info_link'] = i.find('guid').text
result['torrentfile'] = i[8].text
result['guid'] = i[7].text.lower()
result['type'] = 'magnet'
result['downloadid'] = None
result['freeleech'] = 0
result['download_client'] = None
result['seeders'] = int(i[9].text)
results.append(result)
except Exception as e:
logging.error('Error parsing Zooqle XML.', exc_info=True)
continue
logging.info('Found {} results from Zooqle.'.format(len(results)))
return results
| 1,079 |
387 | # -*- coding: utf-8 -*-
"""Unit test package for neo-python-core."""
| 28 |
859 | from SLCT import * | 5 |
399 | package com.frostwire.jlibtorrent.alerts;
import com.frostwire.jlibtorrent.swig.block_finished_alert;
/**
* This alert is generated when a block request receives a response.
*
* @author gubatron
* @author aldenml
*/
public final class BlockFinishedAlert extends PeerAlert<block_finished_alert> {
BlockFinishedAlert(block_finished_alert alert) {
super(alert);
}
/**
* @return the block index
*/
public int blockIndex() {
return alert.getBlock_index();
}
/**
* @return the piece index
*/
public int pieceIndex() {
return alert.getPiece_index();
}
}
| 237 |
809 | <reponame>nikitavlaev/embox
#ifndef R1_CCF_H
#define R1_CCF_H
#define __I volatile const
#define __O volatile
#define __IO volatile
#ifndef uint32
#define uint32
typedef unsigned int uint32_t;
#endif
//bit macro
#define SET_BIT(ELEMENT, BIT_NUM) ELEMENT |= (1 << BIT_NUM));
#define CLR_BIT(ELEMENT, BIT_NUM) ELEMENT &= (~(1 << BIT_NUM));
#endif
| 168 |
717 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gmock/gmock.h>
#include <mariana-trench/LocalPositionSet.h>
#include <mariana-trench/tests/Test.h>
namespace marianatrench {
class LocalPositionSetTest : public test::Test {};
TEST_F(LocalPositionSetTest, Constructor) {
auto context = test::make_empty_context();
EXPECT_TRUE(LocalPositionSet::bottom().is_bottom());
EXPECT_TRUE(LocalPositionSet::top().is_top());
EXPECT_TRUE(LocalPositionSet().empty());
EXPECT_TRUE(
(LocalPositionSet{context.positions->get(std::nullopt, 1)}).is_value());
}
TEST_F(LocalPositionSetTest, Leq) {
auto context = test::make_empty_context();
const auto* one = context.positions->get(std::nullopt, 1);
const auto* two = context.positions->get(std::nullopt, 2);
EXPECT_FALSE((LocalPositionSet{one}).leq(LocalPositionSet::bottom()));
EXPECT_TRUE((LocalPositionSet{one}).leq(LocalPositionSet::top()));
EXPECT_FALSE((LocalPositionSet{one}).leq(LocalPositionSet{}));
EXPECT_TRUE((LocalPositionSet{one}).leq(LocalPositionSet{one}));
EXPECT_TRUE((LocalPositionSet{one}).leq(LocalPositionSet{one, two}));
EXPECT_FALSE((LocalPositionSet{}).leq(LocalPositionSet::bottom()));
EXPECT_TRUE((LocalPositionSet{}).leq(LocalPositionSet::top()));
EXPECT_TRUE((LocalPositionSet{}).leq(LocalPositionSet{}));
EXPECT_TRUE((LocalPositionSet{}).leq(LocalPositionSet{one}));
EXPECT_FALSE((LocalPositionSet{one, two}).leq(LocalPositionSet{}));
EXPECT_FALSE((LocalPositionSet{one, two}).leq(LocalPositionSet{one}));
EXPECT_TRUE((LocalPositionSet{one, two}).leq(LocalPositionSet{one, two}));
}
TEST_F(LocalPositionSetTest, Equals) {
auto context = test::make_empty_context();
const auto* one = context.positions->get(std::nullopt, 1);
const auto* two = context.positions->get(std::nullopt, 2);
EXPECT_FALSE((LocalPositionSet{one}).equals(LocalPositionSet::bottom()));
EXPECT_FALSE((LocalPositionSet{one}).equals(LocalPositionSet::top()));
EXPECT_FALSE((LocalPositionSet{one}).equals(LocalPositionSet{}));
EXPECT_TRUE((LocalPositionSet{one}).equals(LocalPositionSet{one}));
EXPECT_FALSE((LocalPositionSet{one}).equals(LocalPositionSet{one, two}));
EXPECT_FALSE((LocalPositionSet{}).equals(LocalPositionSet::bottom()));
EXPECT_FALSE((LocalPositionSet{}).equals(LocalPositionSet::top()));
EXPECT_TRUE((LocalPositionSet{}).equals(LocalPositionSet{}));
EXPECT_FALSE((LocalPositionSet{}).equals(LocalPositionSet{one}));
EXPECT_FALSE((LocalPositionSet{one, two}).equals(LocalPositionSet{}));
EXPECT_FALSE((LocalPositionSet{one, two}).equals(LocalPositionSet{one}));
EXPECT_TRUE((LocalPositionSet{one, two}).equals(LocalPositionSet{one, two}));
}
TEST_F(LocalPositionSetTest, Join) {
auto context = test::make_empty_context();
const auto* one = context.positions->get(std::nullopt, 1);
const auto* two = context.positions->get(std::nullopt, 2);
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet::bottom()),
LocalPositionSet{one});
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet::top()),
LocalPositionSet::top());
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet{}), LocalPositionSet{one});
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet{one}),
LocalPositionSet{one});
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet{two}),
(LocalPositionSet{one, two}));
EXPECT_EQ(
(LocalPositionSet{one}).join(LocalPositionSet{one, two}),
(LocalPositionSet{one, two}));
EXPECT_EQ(
(LocalPositionSet{}).join(LocalPositionSet::bottom()),
LocalPositionSet{});
EXPECT_EQ(
(LocalPositionSet{}).join(LocalPositionSet::top()),
LocalPositionSet::top());
EXPECT_EQ((LocalPositionSet{}).join(LocalPositionSet{}), LocalPositionSet{});
EXPECT_EQ(
(LocalPositionSet{}).join(LocalPositionSet{one}), LocalPositionSet{one});
EXPECT_EQ(
(LocalPositionSet{one, two}).join(LocalPositionSet{}),
(LocalPositionSet{one, two}));
EXPECT_EQ(
(LocalPositionSet{one, two}).join(LocalPositionSet{one}),
(LocalPositionSet{one, two}));
EXPECT_EQ(
(LocalPositionSet{one, two}).join(LocalPositionSet{one, two}),
(LocalPositionSet{one, two}));
auto set = LocalPositionSet{};
for (std::size_t i = 0; i < Heuristics::kMaxNumberLocalPositions; i++) {
set.join_with(LocalPositionSet{context.positions->get(std::nullopt, i)});
}
EXPECT_TRUE(set.is_value());
EXPECT_EQ(set.elements().size(), Heuristics::kMaxNumberLocalPositions);
set.join_with(LocalPositionSet{context.positions->get(
std::nullopt, Heuristics::kMaxNumberLocalPositions)});
EXPECT_TRUE(set.is_top());
}
TEST_F(LocalPositionSetTest, Add) {
auto context = test::make_empty_context();
const auto* one = context.positions->get(std::nullopt, 1);
const auto* two = context.positions->get(std::nullopt, 2);
auto set = LocalPositionSet::bottom();
set.add(one);
EXPECT_EQ(set, LocalPositionSet::bottom());
set = LocalPositionSet::top();
set.add(one);
EXPECT_EQ(set, LocalPositionSet::top());
set = LocalPositionSet();
set.add(one);
EXPECT_EQ(set, LocalPositionSet{one});
set.add(two);
EXPECT_EQ(set, (LocalPositionSet{one, two}));
set = LocalPositionSet();
for (std::size_t i = 0; i < Heuristics::kMaxNumberLocalPositions; i++) {
set.add(context.positions->get(std::nullopt, i));
}
EXPECT_TRUE(set.is_value());
EXPECT_EQ(set.elements().size(), Heuristics::kMaxNumberLocalPositions);
set.add(context.positions->get(
std::nullopt, Heuristics::kMaxNumberLocalPositions));
EXPECT_TRUE(set.is_top());
}
} // namespace marianatrench
| 2,146 |
764 | {"symbol": "GDR","address": "0x874D4C9B980f1a13dD44CBcDB912e24Ef0671eD0","overview":{"en": ""},"email": "","website": "https://guider.travel","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/guider_official","telegram": "https://t.me/Guider_official","github": "https://github.com/GuiderDev/token/blob/master/smart"}} | 130 |
587 | <gh_stars>100-1000
""" Vision Transformer (ViT) in PyTorch
A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929
The official jax code is released and available at https://github.com/google-research/vision_transformer
Acknowledgments:
* The paper authors for releasing code and weights, thanks!
* I fixed my class token impl based on <NAME>'s https://github.com/lucidrains/vit-pytorch ... check it out
for some einops/einsum fun
* Simple transformer style inspired by <NAME>'s https://github.com/karpathy/minGPT
* Bert reference code checks against Huggingface Transformers and Tensorflow Bert
DeiT model defs and weights from https://github.com/facebookresearch/deit,
paper `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877
Hacked together by / Copyright 2020 <NAME>
"""
import math
import logging
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
import hashlib
import os
import urllib
import warnings
from functools import partial
from tqdm import tqdm
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models.helpers import load_pretrained
from timm.models.layers import StdConv2dSame, DropPath, to_2tuple, trunc_normal_
from timm.models.resnet import resnet26d, resnet50d
from timm.models.resnetv2 import ResNetV2
from timm.models.registry import register_model
from torchvision import transforms
_logger = logging.getLogger(__name__)
def download_clip(
url: str = "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
root: str = os.path.expanduser("~/.cache/clip"),
):
os.makedirs(root, exist_ok=True)
filename = os.path.basename(url)
expected_sha256 = url.split("/")[-2]
download_target = os.path.join(root, filename)
if os.path.exists(download_target) and not os.path.isfile(download_target):
raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target):
if (
hashlib.sha256(open(download_target, "rb").read()).hexdigest()
== expected_sha256
):
return download_target
else:
warnings.warn(
f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file"
)
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
with tqdm(total=int(source.info().get("Content-Length")), ncols=80) as loop:
while True:
buffer = source.read(8192)
if not buffer:
break
output.write(buffer)
loop.update(len(buffer))
if (
hashlib.sha256(open(download_target, "rb").read()).hexdigest()
!= expected_sha256
):
raise RuntimeError(
f"Model has been downloaded but the SHA256 checksum does not not match"
)
return download_target
class UnNormalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, tensor):
for t, m, s in zip(tensor, self.mean, self.std):
t.mul_(s).add_(m)
return tensor
inception_unnormalize = transforms.Compose(
[UnNormalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])]
)
def _cfg(url="", **kwargs):
return {
"url": url,
"num_classes": 1000,
"input_size": (3, 224, 224),
"pool_size": None,
"crop_pct": 0.9,
"interpolation": "bicubic",
"mean": IMAGENET_DEFAULT_MEAN,
"std": IMAGENET_DEFAULT_STD,
"first_conv": "patch_embed.proj",
"classifier": "head",
**kwargs,
}
default_cfgs = {
# patch models (my experiments)
"vit_small_patch16_224": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/vit_small_p16_224-15ec54c9.pth",
),
# patch models (weights ported from official Google JAX impl)
"vit_base_patch16_224": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth",
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_base_patch32_224": _cfg(
url="", # no official model weights for this combo, only for in21k
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_base_patch16_384": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_384-83fb41ba.pth",
input_size=(3, 384, 384),
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=1.0,
),
"vit_base_patch32_384": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p32_384-830016f5.pth",
input_size=(3, 384, 384),
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=1.0,
),
"vit_large_patch16_224": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_224-4ee7a4dc.pth",
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_large_patch32_224": _cfg(
url="", # no official model weights for this combo, only for in21k
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_large_patch16_384": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_384-b3be5167.pth",
input_size=(3, 384, 384),
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=1.0,
),
"vit_large_patch32_384": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth",
input_size=(3, 384, 384),
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=1.0,
),
# patch models, imagenet21k (weights ported from official Google JAX impl)
"vit_base_patch16_224_in21k": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_patch16_224_in21k-e5005f0a.pth",
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_base_patch32_224_in21k": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_patch32_224_in21k-8db57226.pth",
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_large_patch16_224_in21k": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch16_224_in21k-606da67d.pth",
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_large_patch32_224_in21k": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth",
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
"vit_huge_patch14_224_in21k": _cfg(
url="", # FIXME I have weights for this but > 2GB limit for github release binaries
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
),
# hybrid models (weights ported from official Google JAX impl)
"vit_base_resnet50_224_in21k": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_resnet50_224_in21k-6f7c7740.pth",
num_classes=21843,
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=0.9,
first_conv="patch_embed.backbone.stem.conv",
),
"vit_base_resnet50_384": _cfg(
url="https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_resnet50_384-9fd3c705.pth",
input_size=(3, 384, 384),
mean=(0.5, 0.5, 0.5),
std=(0.5, 0.5, 0.5),
crop_pct=1.0,
first_conv="patch_embed.backbone.stem.conv",
),
# hybrid models (my experiments)
"vit_small_resnet26d_224": _cfg(),
"vit_small_resnet50d_s3_224": _cfg(),
"vit_base_resnet26d_224": _cfg(),
"vit_base_resnet50d_224": _cfg(),
# deit models (FB weights)
"vit_deit_tiny_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth"
),
"vit_deit_small_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth"
),
"vit_deit_base_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth",
),
"vit_deit_base_patch16_384": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth",
input_size=(3, 384, 384),
crop_pct=1.0,
),
"vit_deit_tiny_distilled_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth"
),
"vit_deit_small_distilled_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth"
),
"vit_deit_base_distilled_patch16_224": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth",
),
"vit_deit_base_distilled_patch16_384": _cfg(
url="https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth",
input_size=(3, 384, 384),
crop_pct=1.0,
),
}
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(
self,
dim,
num_heads=8,
qkv_bias=False,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, mask=None):
B, N, C = x.shape
qkv = (
self.qkv(x)
.reshape(B, N, 3, self.num_heads, C // self.num_heads)
.permute(2, 0, 3, 1, 4)
)
q, k, v = (
qkv[0],
qkv[1],
qkv[2],
) # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
if mask is not None:
mask = mask.bool()
attn = attn.masked_fill(~mask[:, None, None, :], float("-inf"))
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x, attn
class Block(nn.Module):
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=False,
qk_scale=None,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attn_drop=attn_drop,
proj_drop=drop,
)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
in_features=dim,
hidden_features=mlp_hidden_dim,
act_layer=act_layer,
drop=drop,
)
def forward(self, x, mask=None):
_x, attn = self.attn(self.norm1(x), mask=mask)
x = x + self.drop_path(_x)
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x, attn
class PatchEmbed(nn.Module):
""" Image to Patch Embedding"""
def __init__(
self,
img_size=224,
patch_size=16,
in_chans=3,
embed_dim=768,
no_patch_embed_bias=False,
):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = num_patches
self.proj = nn.Conv2d(
in_chans,
embed_dim,
kernel_size=patch_size,
stride=patch_size,
bias=False if no_patch_embed_bias else True,
)
def forward(self, x):
B, C, H, W = x.shape
# FIXME look at relaxing size constraints
x = self.proj(x)
return x
class VisionTransformer(nn.Module):
""" Vision Transformer
A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
https://arxiv.org/abs/2010.11929
"""
def __init__(
self,
img_size=224,
patch_size=16,
in_chans=3,
num_classes=1000,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
representation_size=None,
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.0,
norm_layer=None,
add_norm_before_transformer=False,
no_patch_embed_bias=False,
config=None,
):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_chans (int): number of input channels
num_classes (int): number of classes for classification head
embed_dim (int): embedding dimension
depth (int): depth of transformer
num_heads (int): number of attention heads
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
qkv_bias (bool): enable bias for qkv if True
qk_scale (float): override default qk scale of head_dim ** -0.5 if set
representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
drop_rate (float): dropout rate
attn_drop_rate (float): attention dropout rate
drop_path_rate (float): stochastic depth rate
hybrid_backbone (nn.Module): CNN backbone to use in-place of PatchEmbed module
norm_layer: (nn.Module): normalization layer
"""
super().__init__()
drop_rate = drop_rate if config is None else config["drop_rate"]
self.num_classes = num_classes
self.num_features = (
self.embed_dim
) = embed_dim # num_features for consistency with other models
norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
self.add_norm_before_transformer = add_norm_before_transformer
self.patch_embed = PatchEmbed(
img_size=img_size,
patch_size=patch_size,
in_chans=in_chans,
embed_dim=embed_dim,
)
num_patches = self.patch_embed.num_patches
self.patch_size = patch_size
self.patch_dim = img_size // patch_size
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if add_norm_before_transformer:
self.pre_norm = norm_layer(embed_dim)
dpr = [
x.item() for x in torch.linspace(0, drop_path_rate, depth)
] # stochastic depth decay rule
self.blocks = nn.ModuleList(
[
Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr[i],
norm_layer=norm_layer,
)
for i in range(depth)
]
)
self.norm = norm_layer(embed_dim)
trunc_normal_(self.pos_embed, std=0.02)
trunc_normal_(self.cls_token, std=0.02)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token"}
def mask_tokens(self, orig_image, feats):
"""
Prepare masked tokens inputs/labels for masked patch prediction: 80% MASK, 10% random, 10% original.
"""
img_unnorm = orig_image * 0.5 + 0.5
_, _, ph, pw = self.patch_embed.proj.weight.shape
with torch.no_grad():
img_unnorm_patch = F.conv2d(
img_unnorm,
weight=torch.ones(3, 1, ph, pw).to(img_unnorm) / (ph * pw),
bias=None,
stride=(ph, pw),
padding=0,
groups=3,
)
labels = (
((img_unnorm_patch * 255).long().flatten(start_dim=2, end_dim=3))
.permute(0, 2, 1)
.contiguous()
)
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
probability_matrix = torch.full(labels.shape[:-1], 0.15)
masked_indices = torch.bernoulli(probability_matrix).bool()
labels[~masked_indices] = -100 # We only compute loss on masked tokens
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
indices_replaced = (
torch.bernoulli(torch.full(labels.shape[:-1], 0.8)).bool() & masked_indices
)
feats[indices_replaced] = self.mask_token.to(feats)
return feats, labels
def visual_embed(self, _x, max_image_len=200, mask_it=False):
_, _, ph, pw = self.patch_embed.proj.weight.shape
x = self.patch_embed(_x)
x_mask = (_x.sum(dim=1) != 0).float()[:, None, :, :]
x_mask = F.interpolate(x_mask, size=(x.shape[2], x.shape[3])).long()
x_h = x_mask[:, 0].sum(dim=1)[:, 0]
x_w = x_mask[:, 0].sum(dim=2)[:, 0]
B, C, H, W = x.shape
spatial_pos = (
self.pos_embed[:, 1:, :]
.transpose(1, 2)
.view(1, C, self.patch_dim, self.patch_dim)
)
pos_embed = torch.cat(
[
F.pad(
F.interpolate(
spatial_pos, size=(h, w), mode="bilinear", align_corners=True,
),
(0, W - w, 0, H - h),
)
for h, w in zip(x_h, x_w)
],
dim=0,
)
pos_embed = pos_embed.flatten(2).transpose(1, 2)
x = x.flatten(2).transpose(1, 2)
patch_index = (
torch.stack(
torch.meshgrid(
torch.arange(x_mask.shape[-2]), torch.arange(x_mask.shape[-1])
),
dim=-1,
)[None, None, :, :, :]
.expand(x_mask.shape[0], x_mask.shape[1], -1, -1, -1)
.flatten(1, 3)
)
x_mask = x_mask.flatten(1)
if mask_it:
x, label = self.mask_tokens(_x, x)
if (
max_image_len < 0
or max_image_len is None
or not isinstance(max_image_len, int)
):
# suppose aug is 800 x 1333, then, maximum effective res is 800 x 1333 (if one side gets bigger, the other will be constrained and be shrinked)
# (800 // self.patch_size) * (1333 // self.patch_size) is the maximum number of patches that single image can get.
# if self.patch_size = 32, 25 * 41 = 1025
# if res is 384 x 640, 12 * 20 = 240
eff = x_h * x_w
max_image_len = eff.max()
else:
eff = x_h * x_w
max_image_len = min(eff.max(), max_image_len)
valid_idx = x_mask.nonzero(as_tuple=False)
non_valid_idx = (1 - x_mask).nonzero(as_tuple=False)
unique_rows = valid_idx[:, 0].unique()
valid_row_idx = [valid_idx[valid_idx[:, 0] == u] for u in unique_rows]
non_valid_row_idx = [
non_valid_idx[non_valid_idx[:, 0] == u] for u in unique_rows
]
valid_nums = [v.size(0) for v in valid_row_idx]
non_valid_nums = [v.size(0) for v in non_valid_row_idx]
pad_nums = [max_image_len - v for v in valid_nums]
select = list()
for i, (v, nv, p) in enumerate(zip(valid_nums, non_valid_nums, pad_nums)):
if p <= 0:
valid_choice = torch.multinomial(torch.ones(v).float(), max_image_len)
select.append(valid_row_idx[i][valid_choice])
else:
pad_choice = torch.multinomial(
torch.ones(nv).float(), p, replacement=True
)
select.append(
torch.cat(
[valid_row_idx[i], non_valid_row_idx[i][pad_choice]], dim=0,
)
)
select = torch.cat(select, dim=0)
x = x[select[:, 0], select[:, 1]].view(B, -1, C)
x_mask = x_mask[select[:, 0], select[:, 1]].view(B, -1)
patch_index = patch_index[select[:, 0], select[:, 1]].view(B, -1, 2)
pos_embed = pos_embed[select[:, 0], select[:, 1]].view(B, -1, C)
if mask_it:
label = label[select[:, 0], select[:, 1]].view(B, -1, 3)
label[x_mask == 0] = -100
label = torch.cat(
[torch.full((label.shape[0], 1, 3), -100).to(label), label,], dim=1,
)
cls_tokens = self.cls_token.expand(B, -1, -1)
x = torch.cat((cls_tokens, x), dim=1)
pos_embed = torch.cat(
(self.pos_embed[:, 0, :][:, None, :].expand(B, -1, -1), pos_embed), dim=1
)
x = x + pos_embed
x = self.pos_drop(x)
if self.add_norm_before_transformer:
x = self.pre_norm(x)
x_mask = torch.cat([torch.ones(x_mask.shape[0], 1).to(x_mask), x_mask], dim=1)
if mask_it:
return x, x_mask, (patch_index, (H, W)), label
else:
return x, x_mask, (patch_index, (H, W)), None
def forward_features(self, _x, max_image_len=144, mask_it=False):
x, x_mask, patch_index, label = self.visual_embed(
_x, max_image_len=max_image_len, mask_it=mask_it
)
for blk in self.blocks:
x, _ = blk(x, mask=x_mask)
x = self.norm(x)
return x, x_mask, label
def forward(self, x, max_image_len=-1):
x, _, _ = self.forward_features(x, max_image_len=max_image_len)
x = x[:, 0]
x = self.head(x)
return x
class DistilledVisionTransformer(VisionTransformer):
""" Vision Transformer with distillation token.
Paper: `Training data-efficient image transformers & distillation through attention` -
https://arxiv.org/abs/2012.12877
This impl of distilled ViT is taken from https://github.com/facebookresearch/deit
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dist_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
num_patches = self.patch_embed.num_patches
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 2, self.embed_dim))
trunc_normal_(self.dist_token, std=0.02)
trunc_normal_(self.pos_embed, std=0.02)
def visual_embed(self, _x, max_image_len=200, mask_it=False):
_, _, ph, pw = self.patch_embed.proj.weight.shape
x = self.patch_embed(_x)
x_mask = (_x.sum(dim=1) != 0).float()[:, None, :, :]
x_mask = F.interpolate(x_mask, size=(x.shape[2], x.shape[3])).long()
x_h = x_mask[:, 0].sum(dim=1)[:, 0]
x_w = x_mask[:, 0].sum(dim=2)[:, 0]
B, C, H, W = x.shape
spatial_pos = (
self.pos_embed[:, 2:, :]
.transpose(1, 2)
.view(1, C, self.patch_dim, self.patch_dim)
)
pos_embed = torch.cat(
[
F.pad(
F.interpolate(
spatial_pos, size=(h, w), mode="bilinear", align_corners=True,
),
(0, W - w, 0, H - h),
)
for h, w in zip(x_h, x_w)
],
dim=0,
)
pos_embed = pos_embed.flatten(2).transpose(1, 2)
x = x.flatten(2).transpose(1, 2)
patch_index = (
torch.stack(
torch.meshgrid(
torch.arange(x_mask.shape[-2]), torch.arange(x_mask.shape[-1])
),
dim=-1,
)[None, None, :, :, :]
.expand(x_mask.shape[0], x_mask.shape[1], -1, -1, -1)
.flatten(1, 3)
)
x_mask = x_mask.flatten(1)
if mask_it:
x, label = self.mask_tokens(_x, x)
if (
max_image_len < 0
or max_image_len is None
or not isinstance(max_image_len, int)
):
# suppose aug is 800 x 1333, then, maximum effective res is 800 x 1333 (if one side gets bigger, the other will be constrained and be shrinked)
# (800 // self.patch_size) * (1333 // self.patch_size) is the maximum number of patches that single image can get.
# if self.patch_size = 32, 25 * 41 = 1025
# if res is 384 x 640, 12 * 20 = 240
eff = x_h * x_w
max_image_len = eff.max()
else:
eff = x_h * x_w
max_image_len = min(eff.max(), max_image_len)
valid_idx = x_mask.nonzero(as_tuple=False)
non_valid_idx = (1 - x_mask).nonzero(as_tuple=False)
unique_rows = valid_idx[:, 0].unique()
valid_row_idx = [valid_idx[valid_idx[:, 0] == u] for u in unique_rows]
non_valid_row_idx = [
non_valid_idx[non_valid_idx[:, 0] == u] for u in unique_rows
]
valid_nums = [v.size(0) for v in valid_row_idx]
non_valid_nums = [v.size(0) for v in non_valid_row_idx]
pad_nums = [max_image_len - v for v in valid_nums]
select = list()
for i, (v, nv, p) in enumerate(zip(valid_nums, non_valid_nums, pad_nums)):
if p <= 0:
valid_choice = torch.multinomial(torch.ones(v).float(), max_image_len)
select.append(valid_row_idx[i][valid_choice])
else:
pad_choice = torch.multinomial(
torch.ones(nv).float(), p, replacement=True
)
select.append(
torch.cat(
[valid_row_idx[i], non_valid_row_idx[i][pad_choice]], dim=0,
)
)
select = torch.cat(select, dim=0)
x = x[select[:, 0], select[:, 1]].view(B, -1, C)
x_mask = x_mask[select[:, 0], select[:, 1]].view(B, -1)
patch_index = patch_index[select[:, 0], select[:, 1]].view(B, -1, 2)
pos_embed = pos_embed[select[:, 0], select[:, 1]].view(B, -1, C)
if mask_it:
label = label[select[:, 0], select[:, 1]].view(B, -1, 3)
label[x_mask == 0] = -100
label = torch.cat(
[torch.full((label.shape[0], 1, 3), -100).to(label), label,], dim=1,
)
cls_tokens = self.cls_token.expand(B, -1, -1)
dist_token = self.dist_token.expand(B, -1, -1)
x = torch.cat((cls_tokens, dist_token, x), dim=1)
pos_embed = torch.cat(
(self.pos_embed[:, :2, :].expand(B, -1, -1), pos_embed), dim=1
)
x = x + pos_embed
x = self.pos_drop(x)
if self.add_norm_before_transformer:
x = self.pre_norm(x)
x_mask = torch.cat([torch.ones(x_mask.shape[0], 2).to(x_mask), x_mask], dim=1)
if mask_it:
return x, x_mask, (patch_index, (H, W)), label
else:
return x, x_mask, (patch_index, (H, W)), None
def forward_features(self, _x, max_image_len=144, mask_it=False):
x, x_mask, patch_index, label = self.visual_embed(
_x, max_image_len=max_image_len, mask_it=mask_it
)
for blk in self.blocks:
x, _ = blk(x, mask=x_mask)
x = self.norm(x)
return x, x_mask, label
def forward(self, x, max_image_len=-1):
x, _, _ = self.forward_features(x, max_image_len=max_image_len)
x = x[:, 0]
x = self.head(x)
return x
def resize_pos_embed(posemb, posemb_new):
# Rescale the grid of position embeddings when loading from state_dict. Adapted from
# https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224
_logger.info("Resized position embedding: %s to %s", posemb.shape, posemb_new.shape)
ntok_new = posemb_new.shape[1]
if True:
posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:]
ntok_new -= 1
else:
posemb_tok, posemb_grid = posemb[:, :0], posemb[0]
gs_old = int(math.sqrt(len(posemb_grid)))
gs_new = int(math.sqrt(ntok_new))
_logger.info("Position embedding grid-size from %s to %s", gs_old, gs_new)
posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
posemb_grid = F.interpolate(posemb_grid, size=(gs_new, gs_new), mode="bilinear")
posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new * gs_new, -1)
posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
return posemb
def checkpoint_filter_fn(state_dict, model):
""" convert patch embedding weight from manual patchify + linear proj to conv"""
out_dict = {}
if "model" in state_dict:
# For deit models
state_dict = state_dict["model"]
for k, v in state_dict.items():
if "patch_embed.proj.weight" in k and len(v.shape) < 4:
# For old models that I trained prior to conv based patchification
O, I, H, W = model.patch_embed.proj.weight.shape
v = v.reshape(O, -1, H, W)
elif k == "pos_embed" and v.shape != model.pos_embed.shape:
# To resize pos embedding when using model at different size from pretrained weights
v = resize_pos_embed(v, model.pos_embed)
out_dict[k] = v
return out_dict
def _create_vision_transformer(variant, pretrained=False, distilled=False, **kwargs):
default_cfg = default_cfgs[variant]
default_num_classes = default_cfg["num_classes"]
default_img_size = default_cfg["input_size"][-1]
num_classes = kwargs.pop("num_classes", default_num_classes)
img_size = kwargs.pop("img_size", default_img_size)
repr_size = kwargs.pop("representation_size", None)
if repr_size is not None and num_classes != default_num_classes:
# Remove representation layer if fine-tuning. This may not always be the desired action,
# but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface?
_logger.warning("Removing representation layer for fine-tuning.")
repr_size = None
model_cls = DistilledVisionTransformer if distilled else VisionTransformer
model = model_cls(
img_size=img_size,
num_classes=num_classes,
representation_size=repr_size,
**kwargs,
)
model.default_cfg = default_cfg
if pretrained:
load_pretrained(
model,
num_classes=num_classes,
in_chans=kwargs.get("in_chans", 3),
filter_fn=partial(checkpoint_filter_fn, model=model),
strict=False,
)
return model
@register_model
def vit_small_patch16_224(pretrained=False, **kwargs):
""" My custom 'small' ViT model. Depth=8, heads=8= mlp_ratio=3."""
model_kwargs = dict(
patch_size=16,
embed_dim=768,
depth=8,
num_heads=8,
mlp_ratio=3.0,
qkv_bias=False,
norm_layer=nn.LayerNorm,
**kwargs,
)
if pretrained:
# NOTE my scale was wrong for original weights, leaving this here until I have better ones for this model
model_kwargs.setdefault("qk_scale", 768 ** -0.5)
model = _create_vision_transformer(
"vit_small_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch16_224(pretrained=False, **kwargs):
""" ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_base_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch32_224(pretrained=False, **kwargs):
""" ViT-Base (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929). No pretrained weights.
"""
model_kwargs = dict(patch_size=32, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_base_patch32_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch16_384(pretrained=False, **kwargs):
""" ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_base_patch16_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch32_384(pretrained=False, **kwargs):
""" ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=32, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_base_patch32_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch16_224(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(
"vit_large_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch32_224(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929). No pretrained weights.
"""
model_kwargs = dict(patch_size=32, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(
"vit_large_patch32_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch16_384(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(
"vit_large_patch16_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch32_384(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(patch_size=32, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(
"vit_large_patch32_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch16_224_in21k(pretrained=False, **kwargs):
""" ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=16,
embed_dim=768,
depth=12,
num_heads=12,
representation_size=768,
**kwargs,
)
model = _create_vision_transformer(
"vit_base_patch16_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_patch32_224_in21k(pretrained=False, **kwargs):
""" ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=32,
embed_dim=768,
depth=12,
num_heads=12,
representation_size=768,
**kwargs,
)
model = _create_vision_transformer(
"vit_base_patch32_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch16_224_in21k(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=16,
embed_dim=1024,
depth=24,
num_heads=16,
representation_size=1024,
**kwargs,
)
model = _create_vision_transformer(
"vit_large_patch16_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_large_patch32_224_in21k(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=32,
embed_dim=1024,
depth=24,
num_heads=16,
representation_size=1024,
**kwargs,
)
model = _create_vision_transformer(
"vit_large_patch32_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_huge_patch14_224_in21k(pretrained=False, **kwargs):
""" ViT-Huge model (ViT-H/14) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
NOTE: converted weights not currently available, too large for github release hosting.
"""
model_kwargs = dict(
patch_size=14,
embed_dim=1280,
depth=32,
num_heads=16,
representation_size=1280,
**kwargs,
)
model = _create_vision_transformer(
"vit_huge_patch14_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_resnet50_224_in21k(pretrained=False, **kwargs):
""" R50+ViT-B/16 hybrid model from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
# create a ResNetV2 w/o pre-activation, that uses StdConv and GroupNorm and has 3 stages, no head
backbone = ResNetV2(
layers=(3, 4, 9),
num_classes=0,
global_pool="",
in_chans=kwargs.get("in_chans", 3),
preact=False,
stem_type="same",
conv_layer=StdConv2dSame,
)
model_kwargs = dict(
embed_dim=768,
depth=12,
num_heads=12,
hybrid_backbone=backbone,
representation_size=768,
**kwargs,
)
model = _create_vision_transformer(
"vit_base_resnet50_224_in21k", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_resnet50_384(pretrained=False, **kwargs):
""" R50+ViT-B/16 hybrid from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer.
"""
# create a ResNetV2 w/o pre-activation, that uses StdConv and GroupNorm and has 3 stages, no head
backbone = ResNetV2(
layers=(3, 4, 9),
num_classes=0,
global_pool="",
in_chans=kwargs.get("in_chans", 3),
preact=False,
stem_type="same",
conv_layer=StdConv2dSame,
)
model_kwargs = dict(
embed_dim=768, depth=12, num_heads=12, hybrid_backbone=backbone, **kwargs
)
model = _create_vision_transformer(
"vit_base_resnet50_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_small_resnet26d_224(pretrained=False, **kwargs):
""" Custom ViT small hybrid w/ ResNet26D stride 32. No pretrained weights.
"""
backbone = resnet26d(
pretrained=pretrained,
in_chans=kwargs.get("in_chans", 3),
features_only=True,
out_indices=[4],
)
model_kwargs = dict(
embed_dim=768,
depth=8,
num_heads=8,
mlp_ratio=3,
hybrid_backbone=backbone,
**kwargs,
)
model = _create_vision_transformer(
"vit_small_resnet26d_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_small_resnet50d_s3_224(pretrained=False, **kwargs):
""" Custom ViT small hybrid w/ ResNet50D 3-stages, stride 16. No pretrained weights.
"""
backbone = resnet50d(
pretrained=pretrained,
in_chans=kwargs.get("in_chans", 3),
features_only=True,
out_indices=[3],
)
model_kwargs = dict(
embed_dim=768,
depth=8,
num_heads=8,
mlp_ratio=3,
hybrid_backbone=backbone,
**kwargs,
)
model = _create_vision_transformer(
"vit_small_resnet50d_s3_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_resnet26d_224(pretrained=False, **kwargs):
""" Custom ViT base hybrid w/ ResNet26D stride 32. No pretrained weights.
"""
backbone = resnet26d(
pretrained=pretrained,
in_chans=kwargs.get("in_chans", 3),
features_only=True,
out_indices=[4],
)
model_kwargs = dict(
embed_dim=768, depth=12, num_heads=12, hybrid_backbone=backbone, **kwargs
)
model = _create_vision_transformer(
"vit_base_resnet26d_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_base_resnet50d_224(pretrained=False, **kwargs):
""" Custom ViT base hybrid w/ ResNet50D stride 32. No pretrained weights.
"""
backbone = resnet50d(
pretrained=pretrained,
in_chans=kwargs.get("in_chans", 3),
features_only=True,
out_indices=[4],
)
model_kwargs = dict(
embed_dim=768, depth=12, num_heads=12, hybrid_backbone=backbone, **kwargs
)
model = _create_vision_transformer(
"vit_base_resnet50d_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_deit_tiny_patch16_224(pretrained=False, **kwargs):
""" DeiT-tiny model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=192, depth=12, num_heads=3, **kwargs)
model = _create_vision_transformer(
"vit_deit_tiny_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_deit_small_patch16_224(pretrained=False, **kwargs):
""" DeiT-small model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs)
model = _create_vision_transformer(
"vit_deit_small_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_deit_base_patch16_224(pretrained=False, **kwargs):
""" DeiT base model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_deit_base_patch16_224", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_deit_base_patch16_384(pretrained=False, **kwargs):
""" DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_deit_base_patch16_384", pretrained=pretrained, **model_kwargs
)
return model
@register_model
def vit_deit_tiny_distilled_patch16_224(pretrained=False, **kwargs):
""" DeiT-tiny distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=192, depth=12, num_heads=3, **kwargs)
model = _create_vision_transformer(
"vit_deit_tiny_distilled_patch16_224",
pretrained=pretrained,
distilled=True,
**model_kwargs,
)
return model
@register_model
def vit_deit_small_distilled_patch16_224(pretrained=False, **kwargs):
""" DeiT-small distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs)
model = _create_vision_transformer(
"vit_deit_small_distilled_patch16_224",
pretrained=pretrained,
distilled=True,
**model_kwargs,
)
return model
@register_model
def vit_deit_base_distilled_patch16_224(pretrained=False, **kwargs):
""" DeiT-base distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_deit_base_distilled_patch16_224",
pretrained=pretrained,
distilled=True,
**model_kwargs,
)
return model
@register_model
def vit_deit_base_distilled_patch16_384(pretrained=False, **kwargs):
""" DeiT-base distilled model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(
"vit_deit_base_distilled_patch16_384",
pretrained=pretrained,
distilled=True,
**model_kwargs,
)
return model
| 23,752 |
12,718 | /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _ASM_STHYI_H
#define _ASM_STHYI_H
#define STHYI_FC_CP_IFL_CAP 0
#endif /* _ASM_STHYI_H */ | 81 |
964 | <reponame>Ilanad/kics<filename>assets/queries/azureResourceManager/sql_alert_policy_without_emails/test/positive_expected_result.json
[
{
"queryName": "SQL Alert Policy Without Emails",
"severity": "INFO",
"line": 46,
"filename": "positive1.json"
},
{
"queryName": "SQL Alert Policy Without Emails",
"severity": "INFO",
"line": 48,
"filename": "positive3.json"
},
{
"queryName": "SQL Alert Policy Without Emails",
"severity": "INFO",
"line": 48,
"filename": "positive2.json"
}
]
| 211 |
684 | <filename>modules/activiti-engine/src/main/java/org/activiti/engine/management/TableMetaData.java
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.management;
import java.util.ArrayList;
import java.util.List;
/**
* Structure containing meta data (column names, column types, etc.)
* about a certain database table.
*
* @author <NAME>
*/
public class TableMetaData {
protected String tableName;
protected List<String> columnNames = new ArrayList<String>();
protected List<String> columnTypes = new ArrayList<String>();
public TableMetaData() {
}
public TableMetaData(String tableName) {
this.tableName = tableName;
}
public void addColumnMetaData(String columnName, String columnType) {
columnNames.add(columnName);
columnTypes.add(columnType);
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<String> getColumnNames() {
return columnNames;
}
public void setColumnNames(List<String> columnNames) {
this.columnNames = columnNames;
}
public List<String> getColumnTypes() {
return columnTypes;
}
public void setColumnTypes(List<String> columnTypes) {
this.columnTypes = columnTypes;
}
}
| 557 |
370 | //==============================================================================
//=== sfmult_AN_XN_YN ==========================================================
//==============================================================================
// y = A*x A is m-by-n, x is n-by-k, y is m-by-k
// compare with sfmult_AN_XN_YT for kernel usage
// compare with sfmult_AN_XT_YN for outer loop structure but different kernels
#include "sfmult.h"
mxArray *sfmult_AN_XN_YN // y = A*x
(
const mxArray *A,
const mxArray *X,
int ac, // if true: conj(A) if false: A. ignored if A real
int xc, // if true: conj(x) if false: x. ignored if x real
int yc // if true: conj(y) if false: y. ignored if y real
)
{
mxArray *Y ;
double *Ax, *Az, *Xx, *Xz, *Yx, *Yz, *Wx, *Wz ;
Int *Ap, *Ai ;
Int m, n, k, k1, i ;
int Acomplex, Xcomplex, Ycomplex ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
m = mxGetM (A) ;
n = mxGetN (A) ;
k = mxGetN (X) ;
if (n != mxGetM (X)) sfmult_invalid ( ) ;
Acomplex = mxIsComplex (A) ;
Xcomplex = mxIsComplex (X) ;
Ap = mxGetJc (A) ;
Ai = mxGetIr (A) ;
Ax = mxGetPr (A) ;
Az = mxGetPi (A) ;
Xx = mxGetPr (X) ;
Xz = mxGetPi (X) ;
//--------------------------------------------------------------------------
// allocate result
//--------------------------------------------------------------------------
Ycomplex = Acomplex || Xcomplex ;
Y = sfmult_yalloc (m, k, Ycomplex) ;
Yx = mxGetPr (Y) ;
Yz = mxGetPi (Y) ;
//--------------------------------------------------------------------------
// special cases
//--------------------------------------------------------------------------
if (k == 0 || m == 0 || n == 0 || Ap [n] == 0)
{
// Y = 0
return (sfmult_yzero (Y)) ;
}
if (k == 1)
{
// Y = A*X
sfmult_AN_x_1 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
return (Y) ;
}
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
sfmult_walloc ((k == 2) ? 2 : 4, m, &Wx, &Wz) ;
//--------------------------------------------------------------------------
// Y = A*X, in blocks of up to 4 columns of X, using sfmult_anxnyt
//--------------------------------------------------------------------------
k1 = k % 4 ;
if (k1 == 1)
{
// Y (:,1) = A * X(:,1)
sfmult_AN_x_1 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
Yx += m ;
Yz += m ;
Xx += n ;
Xz += n ;
}
else if (k1 == 2)
{
// W = (A * X(:,1:2))'
sfmult_AN_XN_YT_2 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
// Y (:,1:2) = W'
#if 0
for (i = 0 ; i < m ; i++) Yx [i] = Wx [2*i ] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [2*i+1] ; Yx += m ; Yz += m ;
#else
for (i = 0 ; i < m ; i++)
{
Yx [i ] = Wx [2*i ] ;
Yx [i+m] = Wx [2*i+1] ;
}
Yx += 2*m ;
Yz += 2*m ;
#endif
Xx += 2*n ;
Xz += 2*n ;
}
else if (k1 == 3)
{
// W = (A * X(:,1:3))'
sfmult_AN_XN_YT_3 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
// Y (:,1:3) = W'
#if 0
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i ] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i+1] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i+2] ; Yx += m ; Yz += m ;
#else
for (i = 0 ; i < m ; i++)
{
Yx [i ] = Wx [4*i ] ;
Yx [i+ m] = Wx [4*i+1] ;
Yx [i+2*m] = Wx [4*i+2] ;
}
Yx += 3*m ;
Yz += 3*m ;
#endif
Xx += 3*n ;
Xz += 3*n ;
}
for ( ; k1 < k ; k1 += 4)
{
// W = (A * X(:,1:4))'
sfmult_AN_XN_YT_4 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
// Y (:,k1+(1:4),:) = W'
#if 0
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i ] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i+1] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i+2] ; Yx += m ; Yz += m ;
for (i = 0 ; i < m ; i++) Yx [i] = Wx [4*i+3] ; Yx += m ; Yz += m ;
#else
for (i = 0 ; i < m ; i++)
{
Yx [i ] = Wx [4*i ] ;
Yx [i+ m] = Wx [4*i+1] ;
Yx [i+2*m] = Wx [4*i+2] ;
Yx [i+3*m] = Wx [4*i+3] ;
}
Yx += 4*m ;
Yz += 4*m ;
#endif
Xx += 4*n ;
Xz += 4*n ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
mxFree (Wx) ;
return (Y) ;
}
| 2,119 |
496 | /*******************************************************************************
* Project: Nebula
* @file StepReportToBeacon.hpp
* @brief 向注册中心上报
* @author Bwar
* @date: 2019年9月22日
* @note
* Modify history:
******************************************************************************/
#ifndef SRC_ACTOR_STEP_SYS_STEP_MANAGER_STEPREPORTTOBEACON_HPP_
#define SRC_ACTOR_STEP_SYS_STEP_MANAGER_STEPREPORTTOBEACON_HPP_
#include "actor/ActorSys.hpp"
#include "actor/step/PbStep.hpp"
namespace neb
{
class SessionManager;
class StepReportToBeacon: public PbStep,
public DynamicCreator<StepReportToBeacon, ev_tstamp>, public ActorSys
{
public:
StepReportToBeacon(ev_tstamp dTimeout);
virtual ~StepReportToBeacon();
virtual E_CMD_STATUS Emit(
int iErrno = 0,
const std::string& strErrMsg = "",
void* data = NULL);
virtual E_CMD_STATUS Callback(
std::shared_ptr<SocketChannel> pChannel,
const MsgHead& oInMsgHead,
const MsgBody& oInMsgBody,
void* data = NULL);
virtual E_CMD_STATUS Timeout();
private:
std::shared_ptr<SessionManager> m_pSessionManager;
};
} /* namespace neb */
#endif /* SRC_ACTOR_STEP_SYS_STEP_MANAGER_STEPREPORTTOBEACON_HPP_ */
| 536 |
5,169 | {
"name": "CXPageView",
"version": "0.1.5",
"summary": "CXPageView summary",
"description": "CXPageView s.description",
"homepage": "https://github.com/chuxia98/CXPageView",
"license": "MIT",
"authors": {
"chuxia": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/chuxia98/CXPageView.git",
"tag": "0.1.5"
},
"source_files": "CXPageView/Classes/**/*",
"exclude_files": "Classes/Exclude",
"frameworks": "UIKit",
"pushed_with_swift_version": "4.0"
}
| 238 |
3,102 | // RUN: %clang_cc1 -emit-llvm %s -o /dev/null
static int unused_func(void) {
return 1;
}
int foo(void) {
(void)unused_func; /* avoid compiler warning */
return 2;
}
| 73 |
3,997 | <gh_stars>1000+
# Shows a user's saved tracks (need to be authenticated via oauth)
import spotipy
from spotipy.oauth2 import SpotifyOAuth
scope = 'user-library-read'
def show_tracks(results):
for item in results['items']:
track = item['track']
print("%32.32s %s" % (track['artists'][0]['name'], track['name']))
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
results = sp.current_user_saved_tracks()
show_tracks(results)
while results['next']:
results = sp.next(results)
show_tracks(results)
| 203 |
607 | <reponame>CrazyForks/Pixiv-Illustration-Collection-Backend<filename>src/main/java/dev/cheerfun/pixivic/biz/crawler/pixiv/secmapper/ImageMapper.java
package dev.cheerfun.pixivic.biz.crawler.pixiv.secmapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface ImageMapper {
@Select("select illust_id from image_sync where is_finish=0 order by illust_id limit 1")
Integer queryLatest();
@Select("select illust_id from image_sync where is_finish=0 and illust_id >#{flag} order by illust_id limit 10")
List<Integer> queryIllustIdList(int flag);
@Update("update image_sync set is_finish =1 where illust_id=#{illustId}")
void updateImageSync(int illustId);
}
| 272 |
1,016 | package com.thinkbiganalytics.datalake.authorization.groups.ldap;
import com.thinkbiganalytics.datalake.authorization.client.SentryClient;
/*-
* #%L
* thinkbig-sentry-client
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.datalake.authorization.client.SentryClientConfig;
import com.thinkbiganalytics.datalake.authorization.model.HadoopAuthorizationGroup;
import com.thinkbiganalytics.datalake.authorization.model.SentryGroup;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.LdapQuery;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
/*-
* #%L
* thinkbig-sentry-client
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public class LdapGroupList {
private static final Logger log = LoggerFactory.getLogger(LdapGroupList.class);
private String OWNER = "kylo";
private String DESCRIPTION = "Kylo Authorization Group";
private String DEFAULT_ID="1";
List<String> groupInfo;
public void getAllGroups(LdapTemplate ldapTemplate , String groupBaseDnPattern) {
try
{
groupInfo =new ArrayList<>();
LdapQuery query = query().base(groupBaseDnPattern);
groupInfo = ldapTemplate.list(query.base());
}
catch(NamingException e)
{
log.error("Unable to Groups from LDAP " + e.getMessage());
throw new RuntimeException(e);
}
}
public List<HadoopAuthorizationGroup> getHadoopAuthorizationList(SentryClientConfig clientConfig , LdapTemplate ldapTemplate)
{
List<HadoopAuthorizationGroup> sentryHadoopAuthorizationGroups = new ArrayList<>();
SentryGroup hadoopAuthorizationGroup = new SentryGroup();
getAllGroups(ldapTemplate, clientConfig.getLdapGroupDnPattern() );
for(String group:groupInfo){
if(group.contains("cn"))
{
/**
* Skip Processing - Do not include CN in group list
*/
}
else
{
if(group.contains("ou"))
{
group = group.split("=")[1];
hadoopAuthorizationGroup.setId(DEFAULT_ID);
hadoopAuthorizationGroup.setDescription(DESCRIPTION);
hadoopAuthorizationGroup.setName(group);
hadoopAuthorizationGroup.setOwner(OWNER);
sentryHadoopAuthorizationGroups.add(hadoopAuthorizationGroup);
hadoopAuthorizationGroup = new SentryGroup();
}
}
}
return sentryHadoopAuthorizationGroups;
}
}
| 1,527 |
429 | <reponame>grom72/daos<filename>src/common/tests/btree.c
/**
* (C) Copyright 2016-2021 Intel Corporation.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*/
#define D_LOGFAC DD_FAC(tests)
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <setjmp.h>
#include <cmocka.h>
#include <daos/btree.h>
#include <daos/dtx.h>
#include <daos/tests_lib.h>
#include "utest_common.h"
enum ik_btr_opc {
BTR_OPC_UPDATE,
BTR_OPC_LOOKUP,
BTR_OPC_DELETE,
BTR_OPC_DELETE_RETAIN,
};
struct test_input_value {
bool input;
enum ik_btr_opc opc;
char *optval;
};
struct test_input_value tst_fn_val;
/**
* An example for integer key btree.
*/
#define IK_ORDER_DEF 16
static int ik_order = IK_ORDER_DEF;
struct utest_context *ik_utx;
struct umem_attr *ik_uma;
static umem_off_t ik_root_off;
static struct btr_root *ik_root;
static daos_handle_t ik_toh;
/** integer key record */
struct ik_rec {
uint64_t ir_key;
uint32_t ir_val_size;
uint32_t ir_val_msize;
umem_off_t ir_val_off;
};
static char **test_group_args;
static int test_group_start;
static int test_group_stop;
#define IK_TREE_CLASS 100
#define POOL_NAME "/mnt/daos/btree-test"
#define POOL_SIZE ((1024 * 1024 * 1024ULL))
/** customized functions for btree */
static int
ik_hkey_size(void)
{
struct ik_rec irec;
return sizeof(irec.ir_key);
}
static void
ik_hkey_gen(struct btr_instance *tins, d_iov_t *key_iov, void *hkey)
{
uint64_t *ikey;
ikey = (uint64_t *)key_iov->iov_buf;
/* ikey = dummy_hash(ikey); */
memcpy(hkey, ikey, sizeof(*ikey));
}
static int
ik_rec_alloc(struct btr_instance *tins, d_iov_t *key_iov,
d_iov_t *val_iov, struct btr_record *rec)
{
umem_off_t irec_off;
struct ik_rec *irec;
char *vbuf;
irec_off = umem_zalloc(&tins->ti_umm, sizeof(struct ik_rec));
D_ASSERT(!UMOFF_IS_NULL(irec_off)); /* lazy bone... */
irec = umem_off2ptr(&tins->ti_umm, irec_off);
irec->ir_key = *(int *)key_iov->iov_buf;
irec->ir_val_size = irec->ir_val_msize = val_iov->iov_len;
irec->ir_val_off = umem_alloc(&tins->ti_umm, val_iov->iov_len);
D_ASSERT(!UMOFF_IS_NULL(irec->ir_val_off));
vbuf = umem_off2ptr(&tins->ti_umm, irec->ir_val_off);
memcpy(vbuf, (char *)val_iov->iov_buf, val_iov->iov_len);
rec->rec_off = irec_off;
return 0;
}
static int
ik_rec_free(struct btr_instance *tins, struct btr_record *rec, void *args)
{
struct umem_instance *umm = &tins->ti_umm;
struct ik_rec *irec;
irec = umem_off2ptr(umm, rec->rec_off);
if (args != NULL) {
umem_off_t *rec_ret = (umem_off_t *) args;
/** Provide the buffer to user */
*rec_ret = rec->rec_off;
return 0;
}
utest_free(ik_utx, irec->ir_val_off);
utest_free(ik_utx, rec->rec_off);
return 0;
}
static int
ik_rec_fetch(struct btr_instance *tins, struct btr_record *rec,
d_iov_t *key_iov, d_iov_t *val_iov)
{
struct ik_rec *irec;
char *val;
int val_size;
int key_size;
if (key_iov == NULL && val_iov == NULL)
return -EINVAL;
irec = (struct ik_rec *)umem_off2ptr(&tins->ti_umm, rec->rec_off);
val_size = irec->ir_val_size;
key_size = sizeof(irec->ir_key);
val = umem_off2ptr(&tins->ti_umm, irec->ir_val_off);
if (key_iov != NULL) {
key_iov->iov_len = key_size;
if (key_iov->iov_buf == NULL)
key_iov->iov_buf = &irec->ir_key;
else if (key_iov->iov_buf_len >= key_size)
memcpy(key_iov->iov_buf, &irec->ir_key, key_size);
}
if (val_iov != NULL) {
val_iov->iov_len = val_size;
if (val_iov->iov_buf == NULL)
val_iov->iov_buf = val;
else if (val_iov->iov_buf_len >= val_size)
memcpy(val_iov->iov_buf, val, val_size);
}
return 0;
}
static char *
ik_rec_string(struct btr_instance *tins, struct btr_record *rec,
bool leaf, char *buf, int buf_len)
{
struct ik_rec *irec = NULL;
char *val;
int nob;
uint64_t ikey;
if (!leaf) { /* NB: no record body on intermediate node */
memcpy(&ikey, &rec->rec_hkey[0], sizeof(ikey));
snprintf(buf, buf_len, DF_U64, ikey);
return buf;
}
irec = (struct ik_rec *)umem_off2ptr(&tins->ti_umm, rec->rec_off);
ikey = irec->ir_key;
nob = snprintf(buf, buf_len, DF_U64, ikey);
buf[nob++] = ':';
buf_len -= nob;
val = umem_off2ptr(&tins->ti_umm, irec->ir_val_off);
strncpy(buf + nob, val, min(irec->ir_val_size, buf_len));
return buf;
}
static int
ik_rec_update(struct btr_instance *tins, struct btr_record *rec,
d_iov_t *key, d_iov_t *val_iov)
{
struct umem_instance *umm = &tins->ti_umm;
struct ik_rec *irec;
char *val;
irec = umem_off2ptr(umm, rec->rec_off);
if (irec->ir_val_msize >= val_iov->iov_len) {
umem_tx_add(umm, irec->ir_val_off, irec->ir_val_msize);
} else {
umem_tx_add(umm, rec->rec_off, sizeof(*irec));
umem_free(umm, irec->ir_val_off);
irec->ir_val_msize = val_iov->iov_len;
irec->ir_val_off = umem_alloc(umm, val_iov->iov_len);
D_ASSERT(!UMOFF_IS_NULL(irec->ir_val_off));
}
val = umem_off2ptr(umm, irec->ir_val_off);
memcpy(val, val_iov->iov_buf, val_iov->iov_len);
irec->ir_val_size = val_iov->iov_len;
return 0;
}
static int
ik_rec_stat(struct btr_instance *tins, struct btr_record *rec,
struct btr_rec_stat *stat)
{
struct umem_instance *umm = &tins->ti_umm;
struct ik_rec *irec;
irec = umem_off2ptr(umm, rec->rec_off);
stat->rs_ksize = sizeof(irec->ir_key);
stat->rs_vsize = irec->ir_val_size;
return 0;
}
static btr_ops_t ik_ops = {
.to_hkey_size = ik_hkey_size,
.to_hkey_gen = ik_hkey_gen,
.to_rec_alloc = ik_rec_alloc,
.to_rec_free = ik_rec_free,
.to_rec_fetch = ik_rec_fetch,
.to_rec_update = ik_rec_update,
.to_rec_string = ik_rec_string,
.to_rec_stat = ik_rec_stat,
};
#define IK_SEP ','
#define IK_SEP_VAL ':'
static void
ik_btr_open_create(void **state)
{
bool inplace = false;
uint64_t feats = 0;
int rc;
bool create;
char *arg;
char outbuf[64];
create = tst_fn_val.input;
arg = tst_fn_val.optval;
if (daos_handle_is_valid(ik_toh)) {
fail_msg("Tree has been opened\n");
}
if (create && arg != NULL) {
if (arg[0] == '+') {
feats = BTR_FEAT_UINT_KEY;
arg += 1;
}
if (arg[0] == 'i') { /* inplace create/open */
inplace = true;
if (arg[1] != IK_SEP) {
sprintf(outbuf, "wrong parameter format %s\n",
arg);
fail_msg("%s", outbuf);
}
arg += 2;
}
if (arg[0] != 'o' || arg[1] != IK_SEP_VAL) {
sprintf(outbuf, "incorrect format for tree order: %s\n",
arg);
fail_msg("%s", outbuf);
}
ik_order = atoi(&arg[2]);
if (ik_order < BTR_ORDER_MIN || ik_order > BTR_ORDER_MAX) {
sprintf(outbuf, "Invalid tree order %d\n", ik_order);
fail_msg("%s", outbuf);
}
} else if (!create) {
inplace = (ik_root->tr_class != 0);
if (UMOFF_IS_NULL(ik_root_off) && !inplace)
fail_msg("Please create tree first\n");
}
if (create) {
D_PRINT("Create btree with order %d%s feats "DF_X64"\n",
ik_order, inplace ? " inplace" : "", feats);
if (inplace) {
rc = dbtree_create_inplace(IK_TREE_CLASS, feats,
ik_order, ik_uma, ik_root,
&ik_toh);
} else {
rc = dbtree_create(IK_TREE_CLASS, feats, ik_order,
ik_uma, &ik_root_off, &ik_toh);
}
} else {
D_PRINT("Open btree%s\n", inplace ? " inplace" : "");
if (inplace) {
rc = dbtree_open_inplace(ik_root,
ik_uma,
&ik_toh);
} else {
rc = dbtree_open(ik_root_off, ik_uma, &ik_toh);
}
}
if (rc != 0) {
sprintf(outbuf, "Tree %s failed: %d\n",
create ? "create" : "open", rc);
fail_msg("%s", outbuf);
}
}
static void
ik_btr_close_destroy(void **state)
{
int rc;
bool destroy;
char outbuf[64];
destroy = tst_fn_val.input;
if (daos_handle_is_inval(ik_toh)) {
fail_msg("Invalid tree open handle\n");
}
if (destroy) {
D_PRINT("Destroy btree\n");
rc = dbtree_destroy(ik_toh, NULL);
} else {
D_PRINT("Close btree\n");
rc = dbtree_close(ik_toh);
}
ik_toh = DAOS_HDL_INVAL;
if (rc != 0) {
sprintf(outbuf, "Tree %s failed: %d\n",
destroy ? "destroy" : "close", rc);
fail_msg("%s", outbuf);
}
}
static int
btr_rec_verify_delete(umem_off_t *rec, d_iov_t *key)
{
struct umem_instance *umm;
struct ik_rec *irec;
umm = utest_utx2umm(ik_utx);
irec = umem_off2ptr(umm, *rec);
if ((sizeof(irec->ir_key) != key->iov_len) ||
(irec->ir_key != *((uint64_t *)key->iov_buf))) {
D_ERROR("Preserved record mismatch while delete\n");
return -1;
}
utest_free(ik_utx, irec->ir_val_off);
utest_free(ik_utx, *rec);
return 0;
}
static char *
btr_opc2str(void)
{
enum ik_btr_opc opc;
opc = tst_fn_val.opc;
switch (opc) {
default:
return "unknown";
case BTR_OPC_UPDATE:
return "update";
case BTR_OPC_LOOKUP:
return "lookup";
case BTR_OPC_DELETE:
return "delete";
case BTR_OPC_DELETE_RETAIN:
return "delete and retain";
}
}
static void
ik_btr_kv_operate(void **state)
{
int count = 0;
umem_off_t rec_off;
int rc;
enum ik_btr_opc opc;
char *str;
bool verbose;
char outbuf[64];
opc = tst_fn_val.opc;
str = tst_fn_val.optval;
verbose = tst_fn_val.input;
if (daos_handle_is_inval(ik_toh)) {
fail_msg("Can't find opened tree\n");
}
while (str != NULL && !isspace(*str) && *str != '\0') {
char *val = NULL;
d_iov_t key_iov;
d_iov_t val_iov;
uint64_t key;
key = strtoul(str, NULL, 0);
if (opc == BTR_OPC_UPDATE) {
val = strchr(str, IK_SEP_VAL);
if (val == NULL) {
sprintf(outbuf,
"Invalid parameters %s(errno %d)\n",
str, errno);
fail_msg("%s", outbuf);
}
str = ++val;
}
str = strchr(str, IK_SEP);
if (str != NULL) {
*str = '\0';
str++;
}
d_iov_set(&key_iov, &key, sizeof(key));
switch (opc) {
default:
fail_msg("Invalid opcode\n");
break;
case BTR_OPC_UPDATE:
d_iov_set(&val_iov, val, strlen(val) + 1);
rc = dbtree_update(ik_toh, &key_iov, &val_iov);
if (rc != 0) {
sprintf(outbuf,
"Failed to update "DF_U64":%s\n", key, val);
fail_msg("%s", outbuf);
}
break;
case BTR_OPC_DELETE:
rc = dbtree_delete(ik_toh, BTR_PROBE_EQ,
&key_iov, NULL);
if (rc != 0) {
sprintf(outbuf,
"Failed to delete "DF_U64"\n", key);
fail_msg("%s", outbuf);
}
if (verbose)
D_PRINT("Deleted key "DF_U64"\n", key);
if (dbtree_is_empty(ik_toh) && verbose)
D_PRINT("Tree is empty now\n");
break;
case BTR_OPC_DELETE_RETAIN:
rc = dbtree_delete(ik_toh, BTR_PROBE_EQ,
&key_iov, &rec_off);
if (rc != 0) {
sprintf(outbuf,
"Failed to delete "DF_U64"\n", key);
fail_msg("%s", outbuf);
}
/** Verify and delete rec_off here */
rc = btr_rec_verify_delete(&rec_off, &key_iov);
if (rc != 0) {
fail_msg("Failed to verify and delete rec\n");
}
if (verbose)
D_PRINT("Deleted key "DF_U64"\n", key);
if (dbtree_is_empty(ik_toh) && verbose)
D_PRINT("Tree is empty now\n");
break;
case BTR_OPC_LOOKUP:
D_DEBUG(DB_TEST, "Looking for "DF_U64"\n", key);
d_iov_set(&val_iov, NULL, 0); /* get address */
rc = dbtree_lookup(ik_toh, &key_iov, &val_iov);
if (rc != 0) {
sprintf(outbuf,
"Failed to lookup "DF_U64"\n", key);
fail_msg("%s", outbuf);
}
if (verbose) {
D_PRINT("Found key "DF_U64", value %s\n",
key, (char *)val_iov.iov_buf);
}
break;
}
count++;
}
if (verbose)
D_PRINT("%s %d record(s)\n", btr_opc2str(), count);
}
static void
ik_btr_query(void **state)
{
struct btr_attr attr;
struct btr_stat stat;
int rc;
char outbuf[64];
rc = dbtree_query(ik_toh, &attr, &stat);
if (rc != 0) {
sprintf(outbuf, "Failed to query btree: %d\n", rc);
fail_msg("%s", outbuf);
}
D_PRINT("tree [order=%d, depth=%d]\n", attr.ba_order, attr.ba_depth);
D_PRINT("node [total="DF_U64"]\n"
"record [total="DF_U64"]\n"
"key [total="DF_U64", max="DF_U64"]\n"
"val [total="DF_U64", max="DF_U64"]\n",
stat.bs_node_nr, stat.bs_rec_nr,
stat.bs_key_sum, stat.bs_key_max,
stat.bs_val_sum, stat.bs_val_max);
}
static void
ik_btr_iterate(void **state)
{
daos_handle_t ih;
int i;
int d;
int del;
int rc;
int opc;
char *err;
char *arg;
arg = tst_fn_val.optval;
if (daos_handle_is_inval(ik_toh)) {
fail_msg("Can't find opened tree\n");
}
rc = dbtree_iter_prepare(ik_toh, BTR_ITER_EMBEDDED, &ih);
if (rc != 0) {
err = "Failed to initialize tree\n";
goto failed;
}
if (arg[0] == 'b')
opc = BTR_PROBE_LAST;
else
opc = BTR_PROBE_FIRST;
if (arg[1] == ':')
del = atoi(&arg[2]);
else
del = 0;
for (i = d = 0;; i++) {
d_iov_t key_iov;
d_iov_t val_iov;
uint64_t key;
if (i == 0 || (del != 0 && d <= del)) {
rc = dbtree_iter_probe(ih, opc, DAOS_INTENT_DEFAULT,
NULL, NULL);
if (rc == -DER_NONEXIST)
break;
if (rc != 0) {
err = "probe failure\n";
goto failed;
}
if (del != 0) {
if (d == del)
del = d = 0; /* done */
else
d++;
}
}
d_iov_set(&key_iov, NULL, 0);
d_iov_set(&val_iov, NULL, 0);
rc = dbtree_iter_fetch(ih, &key_iov, &val_iov, NULL);
if (rc != 0) {
err = "fetch failure\n";
goto failed;
}
D_ASSERT(key_iov.iov_len == sizeof(key));
memcpy(&key, key_iov.iov_buf, sizeof(key));
if (d != 0) { /* delete */
D_PRINT("Delete "DF_U64": %s\n",
key, (char *)val_iov.iov_buf);
rc = dbtree_iter_delete(ih, NULL);
if (rc != 0) {
err = "delete failure\n";
goto failed;
}
} else { /* iterate */
D_PRINT(DF_U64": %s\n", key, (char *)val_iov.iov_buf);
if (opc == BTR_PROBE_LAST)
rc = dbtree_iter_prev(ih);
else
rc = dbtree_iter_next(ih);
if (rc == -DER_NONEXIST)
break;
if (rc != 0) {
err = "move failure\n";
goto failed;
}
}
}
D_PRINT("%s iterator: total %d, deleted %d\n",
opc == BTR_PROBE_FIRST ? "forward" : "backward", i, d);
dbtree_iter_finish(ih);
goto pass;
failed:
dbtree_iter_finish(ih);
fail_msg("%s", err);
pass:
print_message("Test Passed\n");
}
/* fill in @arr with natural number from 1 to key_nr, randomize their order */
void
ik_btr_gen_keys(unsigned int *arr, unsigned int key_nr)
{
int nr;
int i;
for (i = 0; i < key_nr; i++)
arr[i] = i + 1;
for (nr = key_nr; nr > 0; nr--) {
unsigned int tmp;
int j;
j = rand() % nr;
if (j != nr - 1) {
tmp = arr[j];
arr[j] = arr[nr - 1];
arr[nr - 1] = tmp;
}
}
}
#define DEL_BATCH 10000
/**
* batch btree operations:
* 1) insert @key_nr number of integer keys
* 2) lookup all the rest keys
* 3) delete nr=DEL_BATCH keys
* 4) repeat 2) and 3) util all keys are deleted
*/
static void
ik_btr_batch_oper(void **state)
{
unsigned int *arr;
char buf[64];
int i;
unsigned int key_nr;
bool verbose;
key_nr = atoi(tst_fn_val.optval);
verbose = key_nr < 20;
if (key_nr == 0 || key_nr > (1U << 28)) {
D_PRINT("Invalid key number: %d\n", key_nr);
fail();
}
D_ALLOC_ARRAY(arr, key_nr);
if (arr == NULL)
fail_msg("Array allocation failed");
D_PRINT("Batch add %d records.\n", key_nr);
ik_btr_gen_keys(arr, key_nr);
for (i = 0; i < key_nr; i++) {
sprintf(buf, "%d:%d", arr[i], arr[i]);
tst_fn_val.opc = BTR_OPC_UPDATE;
tst_fn_val.optval = buf;
tst_fn_val.input = verbose;
ik_btr_kv_operate(NULL);
}
ik_btr_query(NULL);
/* lookup all rest records, delete 10000 of them, and repeat until
* deleting all records.
*/
ik_btr_gen_keys(arr, key_nr);
for (i = 0; i < key_nr;) {
int j;
D_PRINT("Batch lookup %d records.\n", key_nr - i);
for (j = i; j < key_nr; j++) {
sprintf(buf, "%d", arr[j]);
tst_fn_val.opc = BTR_OPC_LOOKUP;
tst_fn_val.optval = buf;
tst_fn_val.input = verbose;
ik_btr_kv_operate(NULL);
}
D_PRINT("Batch delete %d records.\n",
min(key_nr - i, DEL_BATCH));
for (j = 0; i < key_nr && j < DEL_BATCH; i++, j++) {
sprintf(buf, "%d", arr[i]);
tst_fn_val.opc = BTR_OPC_DELETE;
tst_fn_val.optval = buf;
tst_fn_val.input = verbose;
ik_btr_kv_operate(NULL);
}
}
ik_btr_query(NULL);
D_FREE(arr);
}
static void
ik_btr_perf(void **state)
{
unsigned int *arr;
char buf[64];
int i;
double then;
double now;
unsigned int key_nr;
key_nr = atoi(tst_fn_val.optval);
if (key_nr == 0 || key_nr > (1U << 28)) {
D_PRINT("Invalid key number: %d\n", key_nr);
fail();
}
D_PRINT("Btree performance test, order=%u, keys=%u\n",
ik_order, key_nr);
D_ALLOC_ARRAY(arr, key_nr);
if (arr == NULL)
fail_msg("Array allocation failed\n");
/* step-1: Insert performance */
ik_btr_gen_keys(arr, key_nr);
then = dts_time_now();
for (i = 0; i < key_nr; i++) {
sprintf(buf, "%d:%d", arr[i], arr[i]);
tst_fn_val.opc = BTR_OPC_UPDATE;
tst_fn_val.optval = buf;
tst_fn_val.input = false;
ik_btr_kv_operate(NULL);
}
now = dts_time_now();
D_PRINT("insert = %10.2f/sec\n", key_nr / (now - then));
/* step-2: lookup performance */
ik_btr_gen_keys(arr, key_nr);
then = dts_time_now();
for (i = 0; i < key_nr; i++) {
sprintf(buf, "%d", arr[i]);
tst_fn_val.opc = BTR_OPC_LOOKUP;
tst_fn_val.optval = buf;
tst_fn_val.input = false;
ik_btr_kv_operate(NULL);
}
now = dts_time_now();
D_PRINT("lookup = %10.2f/sec\n", key_nr / (now - then));
/* step-3: delete performance */
ik_btr_gen_keys(arr, key_nr);
then = dts_time_now();
for (i = 0; i < key_nr; i++) {
sprintf(buf, "%d", arr[i]);
tst_fn_val.opc = BTR_OPC_DELETE;
tst_fn_val.optval = buf;
tst_fn_val.input = false;
ik_btr_kv_operate(NULL);
}
now = dts_time_now();
D_PRINT("delete = %10.2f/sec\n", key_nr / (now - then));
D_FREE(arr);
}
static void
ik_btr_drain(void **state)
{
static const int drain_keys = 10000;
static const int drain_creds = 23;
unsigned int *arr;
unsigned int drained = 0;
char buf[64];
int i;
D_ALLOC_ARRAY(arr, drain_keys);
if (arr == NULL)
fail_msg("Array allocation failed");
D_PRINT("Batch add %d records.\n", drain_keys);
ik_btr_gen_keys(arr, drain_keys);
for (i = 0; i < drain_keys; i++) {
sprintf(buf, "%d:%d", arr[i], arr[i]);
tst_fn_val.opc = BTR_OPC_UPDATE;
tst_fn_val.optval = buf;
tst_fn_val.input = false;
ik_btr_kv_operate(NULL);
}
ik_btr_query(NULL);
while (1) {
int creds = drain_creds;
bool empty = false;
int rc;
rc = dbtree_drain(ik_toh, &creds, NULL, &empty);
if (rc) {
fail_msg("Failed to drain btree: %s\n", d_errstr(rc));
fail();
}
drained += drain_creds - creds;
D_PRINT("Drained %d of %d KVs, empty=%d\n",
drained, drain_keys, empty);
if (empty)
break;
}
D_FREE(arr);
}
static struct option btr_ops[] = {
{ "create", required_argument, NULL, 'C' },
{ "destroy", no_argument, NULL, 'D' },
{ "drain", no_argument, NULL, 'e' },
{ "open", no_argument, NULL, 'o' },
{ "close", no_argument, NULL, 'c' },
{ "update", required_argument, NULL, 'u' },
{ "find", required_argument, NULL, 'f' },
{ "dyn_tree", no_argument, NULL, 't' },
{ "delete", required_argument, NULL, 'd' },
{ "del_retain", required_argument, NULL, 'r' },
{ "query", no_argument, NULL, 'q' },
{ "iterate", required_argument, NULL, 'i' },
{ "batch", required_argument, NULL, 'b' },
{ "perf", required_argument, NULL, 'p' },
{ NULL, 0, NULL, 0 },
};
static int
use_pmem() {
int rc;
D_PRINT("Using pmem\n");
rc = utest_pmem_create(POOL_NAME, POOL_SIZE,
sizeof(*ik_root),
&ik_utx);
D_ASSERT(rc == 0);
return rc;
}
static void
ts_group(void **state) {
int opt = 0;
void **st = NULL;
while ((opt = getopt_long(test_group_stop-test_group_start+1,
test_group_args+test_group_start,
"tmC:Deocqu:d:r:f:i:b:p:",
btr_ops,
NULL)) != -1) {
tst_fn_val.optval = optarg;
tst_fn_val.input = true;
switch (opt) {
case 'C':
ik_btr_open_create(st);
break;
case 'D':
tst_fn_val.input = true;
ik_btr_close_destroy(st);
break;
case 'o':
tst_fn_val.input = false;
tst_fn_val.optval = NULL;
ik_btr_open_create(st);
break;
case 'c':
tst_fn_val.input = false;
ik_btr_close_destroy(st);
break;
case 'e':
ik_btr_drain(st);
break;
case 'q':
ik_btr_query(st);
break;
case 'u':
tst_fn_val.opc = BTR_OPC_UPDATE;
ik_btr_kv_operate(st);
break;
case 'f':
tst_fn_val.opc = BTR_OPC_LOOKUP;
ik_btr_kv_operate(st);
break;
case 'd':
tst_fn_val.opc = BTR_OPC_DELETE;
ik_btr_kv_operate(st);
break;
case 'r':
tst_fn_val.opc = BTR_OPC_DELETE_RETAIN;
ik_btr_kv_operate(st);
break;
case 'i':
ik_btr_iterate(st);
break;
case 'b':
ik_btr_batch_oper(st);
break;
case 'p':
ik_btr_perf(st);
break;
default:
D_PRINT("Unsupported command %c\n", opt);
case 'm':
case 't':
/* handled previously */
break;
}
}
}
static int
run_cmd_line_test(char *test_name, char **args, int start_idx, int stop_idx)
{
const struct CMUnitTest btree_test[] = {
{test_name, ts_group, NULL, NULL},
};
test_group_args = args;
test_group_start = start_idx;
test_group_stop = stop_idx;
return cmocka_run_group_tests_name(test_name,
btree_test,
NULL,
NULL);
}
int
main(int argc, char **argv)
{
struct timeval tv;
int rc = 0;
int opt;
int dynamic_flag = 0;
int start_idx;
char *test_name;
int stop_idx;
d_register_alt_assert(mock_assert);
gettimeofday(&tv, NULL);
srand(tv.tv_usec);
ik_toh = DAOS_HDL_INVAL;
ik_root_off = UMOFF_NULL;
rc = daos_debug_init(DAOS_LOG_DEFAULT);
if (rc != 0)
return rc;
if (argc == 1) {
print_message("Invalid format.\n");
return -1;
}
stop_idx = argc-1;
if (strcmp(argv[1], "--start-test") == 0) {
start_idx = 2;
test_name = argv[2];
if (strcmp(argv[3], "-t") == 0) {
D_PRINT("Using dynamic tree order\n");
dynamic_flag = BTR_FEAT_DYNAMIC_ROOT;
if (strcmp(argv[4], "-m") == 0)
rc = use_pmem();
} else if (strcmp(argv[3], "-m") == 0) {
rc = use_pmem();
if (strcmp(argv[4], "-t") == 0) {
D_PRINT("Using dynamic tree order\n");
dynamic_flag = BTR_FEAT_DYNAMIC_ROOT;
}
}
} else {
start_idx = 0;
test_name = "Btree testing tool";
optind = 0;
/* Check for -m option first */
while ((opt = getopt_long(argc, argv, "tmC:Deocqu:d:r:f:i:b:p:",
btr_ops, NULL)) != -1) {
if (opt == 'm') {
rc = use_pmem();
break;
}
if (opt == 't') {
D_PRINT("Using dynamic tree order\n");
dynamic_flag = BTR_FEAT_DYNAMIC_ROOT;
}
}
}
rc = dbtree_class_register(IK_TREE_CLASS,
dynamic_flag | BTR_FEAT_UINT_KEY, &ik_ops);
D_ASSERT(rc == 0);
if (ik_utx == NULL) {
D_PRINT("Using vmem\n");
rc = utest_vmem_create(sizeof(*ik_root), &ik_utx);
D_ASSERT(rc == 0);
}
ik_root = utest_utx2root(ik_utx);
ik_uma = utest_utx2uma(ik_utx);
/* start over */
optind = 0;
rc = run_cmd_line_test(test_name, argv, start_idx, stop_idx);
daos_debug_fini();
rc += utest_utx_destroy(ik_utx);
if (rc != 0)
printf("Error: %d\n", rc);
return rc;
}
| 11,478 |
6,617 | <reponame>dmhalejr/patch-package
{
"name": "custom-resolutions",
"version": "1.0.0",
"description": "integration test for patch-package",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"dependency": "file:./dependency"
},
"resolutions": {
"blahblahblah-definitely-not-a-real-package-name": "file:./blahblahblah-definitely-not-a-real-package-name"
}
}
| 165 |
2,023 | class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
"""Fetch and character using the termios module."""
def __init__(self):
import tty, sys
from select import select
def __call__(self):
import sys, tty, termios
from select import select
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
# [ Wait until ready for reading,
# wait until ready for writing
# wait for an "exception condition" ]
# The below line times out after 1 second
# This can be changed to a floating-point value if necessary
[i, o, e] = select([sys.stdin.fileno()], [], [], 1)
if i:
ch = sys.stdin.read(1)
else:
ch = None
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
"""Fetch a character using the Microsoft Visual C Runtime."""
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
import time
# Delay timeout to match UNIX behaviour
time.sleep(1)
# Check if there is a character waiting, otherwise this would block
if msvcrt.kbhit():
return msvcrt.getch()
else:
return
getch = _Getch()
| 775 |
560 | <filename>src/androidTest/java/dk/jens/backup/schedules/TestBootReceiver.java
package dk.jens.backup.schedules;
import android.content.Context;
import dk.jens.backup.schedules.db.ScheduleDao;
import static org.mockito.Mockito.mock;
public class TestBootReceiver extends BootReceiver {
static HandleAlarms handleAlarms = mock(HandleAlarms.class);
static ScheduleDao scheduleDao = mock(ScheduleDao.class);
@Override
long getCurrentTime() {
return 1546770125;
}
@Override
HandleAlarms getHandleAlarms(Context context) {
return handleAlarms;
}
@Override
ScheduleDao getScheduleDao(Context context, String databasename) {
return scheduleDao;
}
}
| 270 |
6,992 | /*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.convention.versions;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
class TransitiveDependencyLookupUtils {
static String OIDC_SDK_NAME = "oauth2-oidc-sdk";
static String NIMBUS_JOSE_JWT_NAME = "nimbus-jose-jwt";
private static OkHttpClient client = new OkHttpClient();
static String lookupJwtVersion(String oauthSdcVersion) {
Request request = new Request.Builder()
.get()
.url("https://repo.maven.apache.org/maven2/com/nimbusds/" + OIDC_SDK_NAME + "/" + oauthSdcVersion + "/" + OIDC_SDK_NAME + "-" + oauthSdcVersion + ".pom")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
InputStream inputStream = response.body().byteStream();
return getVersion(inputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getVersion(InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
return xPath.evaluate("/project/dependencies/dependency/version[../artifactId/text() = \"" + NIMBUS_JOSE_JWT_NAME + "\"]", doc);
}
}
| 843 |
496 | //
// BCMutableMeshTransform+DemoTransforms.h
// BCMeshTransformView
//
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "BCMeshTransform.h"
@interface BCMeshTransform (DemoTransforms)
+ (instancetype)curtainMeshTransformAtPoint:(CGPoint)point
boundsSize:(CGSize)boundsSize;
+ (instancetype)buldgeMeshTransformAtPoint:(CGPoint)point
withRadius:(CGFloat)radius
boundsSize:(CGSize)size;
+ (instancetype)shiverTransformWithPhase:(CGFloat)phase magnitude:(CGFloat)magnitude;
+ (instancetype)ellipseMeshTransform;
+ (instancetype)rippleMeshTransform;
@end
| 298 |
5,169 | {
"name": "practiceProject",
"version": "0.0.5",
"summary": "练习pod库",
"description": "“这是描述部分”",
"homepage": "<EMAIL>:LJJHD/practiceProject.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"malagu": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/LJJHD/practiceProject.git",
"tag": "0.0.5"
},
"source_files": "praticeProject/Classes/Print.{h,m}",
"requires_arc": true,
"subspecs": [
{
"name": "Tools",
"source_files": "praticeProject/Classes/functionOne.{h,m}"
},
{
"name": "Tools2",
"source_files": "praticeProject/Classes/functionTwo.{h,m}"
}
]
}
| 347 |
763 | <filename>projects/question/src/main/java/org/batfish/question/evpnl3vniproperties/EvpnL3VniPropertiesQuestion.java<gh_stars>100-1000
package org.batfish.question.evpnl3vniproperties;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.questions.Question;
/** A question that returns a table with VXLAN network segments and their properties. */
@ParametersAreNonnullByDefault
public final class EvpnL3VniPropertiesQuestion extends Question {
private static final String PROP_NODES = "nodes";
@Nullable private String _nodes;
@Override
public boolean getDataPlane() {
return false;
}
@Override
public String getName() {
return "evpnL3VniProperties";
}
@JsonCreator
private static @Nonnull EvpnL3VniPropertiesQuestion create(
@Nullable @JsonProperty(PROP_NODES) String nodes) {
return new EvpnL3VniPropertiesQuestion(nodes);
}
public EvpnL3VniPropertiesQuestion(@Nullable String nodes) {
_nodes = nodes;
}
@JsonProperty(PROP_NODES)
public @Nullable String getNodes() {
return _nodes;
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof EvpnL3VniPropertiesQuestion)) {
return false;
}
EvpnL3VniPropertiesQuestion that = (EvpnL3VniPropertiesQuestion) o;
return Objects.equals(_nodes, that._nodes);
}
@Override
public int hashCode() {
return Objects.hashCode(_nodes);
}
}
| 573 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_INFOBARS_OVERLAYS_BROWSER_AGENT_INTERACTION_HANDLERS_SAVE_CARD_SAVE_CARD_INFOBAR_MODAL_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_
#define IOS_CHROME_BROWSER_INFOBARS_OVERLAYS_BROWSER_AGENT_INTERACTION_HANDLERS_SAVE_CARD_SAVE_CARD_INFOBAR_MODAL_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_
#import "ios/chrome/browser/infobars/overlays/browser_agent/interaction_handlers/common/infobar_modal_overlay_request_callback_installer.h"
#include "base/memory/weak_ptr.h"
class SaveCardInfobarModalInteractionHandler;
// Callback installer for SaveCard infobar modal interaction events.
class SaveCardInfobarModalOverlayRequestCallbackInstaller
: public InfobarModalOverlayRequestCallbackInstaller {
public:
// Constructor for an instance that installs callbacks that forward
// interaction events to |interaction_handler|.
explicit SaveCardInfobarModalOverlayRequestCallbackInstaller(
SaveCardInfobarModalInteractionHandler* interaction_handler);
~SaveCardInfobarModalOverlayRequestCallbackInstaller() override;
private:
// Used as a callback for OverlayResponses dispatched through |request|'s
// callback manager. The OverlayDispatchCallback is created with an
// OverlayResponseSupport that guarantees that |response| is created with an
// save_card_infobar_modal_responses::SaveCardMainAction.
void SaveCardCredentialsCallback(OverlayRequest* request,
OverlayResponse* response);
// Used as a callback for OverlayResponses dispatched through |request|'s
// callback manager. The OverlayDispatchCallback is created with an
// OverlayResponseSupport that guarantees that |response| is created with a
// save_card_infobar_modal_responses::SaveCardLoadURL.
void LoadURLCallback(OverlayRequest* request, OverlayResponse* response);
// OverlayRequestCallbackInstaller:
void InstallCallbacksInternal(OverlayRequest* request) override;
// The handler for received responses.
SaveCardInfobarModalInteractionHandler* interaction_handler_ = nullptr;
base::WeakPtrFactory<SaveCardInfobarModalOverlayRequestCallbackInstaller>
weak_factory_{this};
};
#endif // IOS_CHROME_BROWSER_INFOBARS_OVERLAYS_BROWSER_AGENT_INTERACTION_HANDLERS_SAVE_CARD_SAVE_CARD_INFOBAR_MODAL_OVERLAY_REQUEST_CALLBACK_INSTALLER_H_
| 794 |
562 | from conans import ConanFile, tools
import os
class LibdivideConan(ConanFile):
name = "libdivide"
description = "Header-only C/C++ library for optimizing integer division."
topics = ("conan", "libdivide", "division", "integer")
license = ["Zlib", "BSL-1.0"]
homepage = "http://libdivide.com/"
url = "https://github.com/conan-io/conan-center-index"
settings = "arch", "compiler"
no_copy_source = True
options = {
"simd_intrinsics": [False, "sse2", "avx2", "avx512"]
}
default_options = {
"simd_intrinsics": False
}
@property
def _source_subfolder(self):
return "source_subfolder"
def config_options(self):
if self.settings.arch not in ["x86", "x86_64"]:
del self.options.simd_intrinsics
def configure(self):
if self.settings.compiler.cppstd:
tools.check_min_cppstd(self, 11)
def package_id(self):
self.info.header_only()
def source(self):
tools.get(**self.conan_data["sources"][self.version])
os.rename(self.name + "-" + self.version, self._source_subfolder)
def package(self):
self.copy("LICENSE.txt", dst="licenses", src=self._source_subfolder)
self.copy("libdivide.h", dst="include", src=self._source_subfolder)
def package_info(self):
simd = self.options.get_safe("simd_intrinsics", False)
if bool(simd):
self.cpp_info.defines = [
{"sse2": "LIBDIVIDE_SSE2",
"avx2": "LIBDIVIDE_AVX2",
"avx512": "LIBDIVIDE_AVX512"}[str(simd)]
]
| 741 |
343 | /* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
/*
* Compile-time and run-time interface between gpr and libexpr
*/
#include "config.h"
#include <stdlib.h>
#include <stdint.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "compile.h"
#include <assert.h>
#include "cgraph.h"
#include <error.h>
#include <actions.h>
#include "sfstr.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
#define ISEDGE(e) (AGTYPE(e)&2)
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
#include <gdefs.h>
#include "ctype.h"
#include "trie.c"
#define BITS_PER_BYTE 8
#ifdef HAVE_INTPTR_T
#define INT2PTR(t,v) ((t)(intptr_t)(v))
#define PTR2INT(v) ((Sflong_t)(intptr_t)(v))
#else
#define INT2PTR(t,v) ((t)(v))
#define PTR2INT(v) ((Sflong_t)(v))
#endif
static int iofread(void *chan, char *buf, int bufsize)
{
return read(sffileno((Sfio_t *) chan), buf, bufsize);
}
static int ioputstr(void *chan, const char *str)
{
return sfputr((Sfio_t *) chan, str, -1);
}
static int ioflush(void *chan)
{
return sfsync((Sfio_t *) chan);
}
static Agiodisc_t gprIoDisc = { iofread, ioputstr, ioflush };
#ifdef WIN32
static Agdisc_t gprDisc = { 0, 0, &gprIoDisc };
#else
static Agdisc_t gprDisc = { &AgMemDisc, &AgIdDisc, &gprIoDisc };
#endif
/* nameOf:
* Return name of object.
* Assumes obj != NULL
*/
static char *nameOf(Expr_t * ex, Agobj_t * obj, Sfio_t* tmps)
{
char *s;
char *key;
Agedge_t *e;
switch (AGTYPE(obj)) {
case AGNODE:
case AGRAPH:
s = agnameof(obj);
break;
default: /* edge */
e = (Agedge_t *) obj;
key = agnameof(AGMKOUT(e));
sfputr(tmps, agnameof(AGTAIL(e)), -1);
if (agisdirected(agraphof(e)))
sfputr(tmps, "->", -1);
else
sfputr(tmps, "--", -1);
sfputr(tmps, agnameof(AGHEAD(e)), -1);
if (key && *key) {
sfputc(tmps, '[');
sfputr(tmps, key, -1);
sfputc(tmps, ']');
}
s = exstring(ex, sfstruse(tmps));
break;
}
return s;
}
/* bbOf:
* If string as form "x,y,u,v" where is all are numeric,
* return "x,y" or "u,v", depending on getll, else return ""
*/
static char *bbOf(Expr_t * pgm, char *pt, int getll)
{
double x, y, u, v;
char *s;
char *p;
int len;
if (sscanf(pt, "%lf,%lf,%lf,%lf", &x, &y, &u, &v) == 4) {
p = strchr(pt, ',');
p = strchr(p + 1, ',');
if (getll) {
len = p - pt;
s = exstralloc(pgm, 0, len + 1);
strncpy(s, pt, len);
s[len] = '\0';
} else
s = exstring(pgm, p + 1);
} else
s = "";
return s;
}
/* xyOf:
* If string as form "x,y" where is x and y are numeric,
* return "x" or "y", depending on getx, else return ""
*/
static char *xyOf(Expr_t * pgm, char *pt, int getx)
{
double x, y;
char *v;
char *p;
int len;
if (sscanf(pt, "%lf,%lf", &x, &y) == 2) {
p = strchr(pt, ',');
if (getx) {
len = p - pt;
v = exstralloc(pgm, 0, len + 1);
strncpy(v, pt, len);
v[len] = '\0';
} else
v = exstring(pgm, p + 1);
} else
v = "";
return v;
}
/* posOf:
* Get pos data from node; store x or y into v if successful and return 0;
* else return -1
*/
static int posOf(Agnode_t* np, int idx, double* v)
{
static Agraph_t* root;
static Agsym_t* pos;
Agraph_t* nroot = agroot(np);
char* ps;
double p[2];
if (root != nroot) {
root = nroot;
pos = agattr(root, AGNODE, "pos", 0);
}
if (!pos) return -1;
ps = agxget(np, pos);
if (sscanf(ps, "%lf,%lf", &p[0], &p[1]) == 2) {
*v = p[idx];
return 0;
}
else return -1;
}
#if DEBUG > 1
static char *symName(Expr_t * ex, int op)
{
if (op >= MINNAME && op <= MAXNAME)
return gprnames[op];
else {
Sfio_t *sf = sfstropen();
char *s;
sfprintf(sf, "<unknown (%d)>", op);
s = exstring(ex, sfstruse(sf));
sfclose(sf);
return s;
}
}
#endif
/* xargs:
* Convert string argument to graph to type of graph desired.
* u => undirected
* d => directed
* s => strict
* n => non-strict
* Case-insensitive
* By default, the graph is directed, non-strict.
*/
static Agdesc_t xargs(char *args)
{
Agdesc_t desc = Agdirected;
char c;
while ((c = *args++)) {
switch (c) {
case 'u':
case 'U':
desc.directed = 0;
break;
case 'd':
case 'D':
desc.directed = 1;
break;
case 's':
case 'S':
desc.strict = 1;
break;
case 'n':
case 'N':
desc.directed = 0;
break;
default:
error(ERROR_WARNING, "unknown graph descriptor '%c' : ignored",
c);
break;
}
}
return desc;
}
/* deparse:
* Recreate string representation of expression involving
* a reference and a symbol.
* The parameter sf must be a string stream.
*/
static char *deparse(Expr_t * ex, Exnode_t * n, Sfio_t * sf)
{
exdump(ex, n, sf);
return (sfstruse(sf));
}
/* deref:
* Evaluate reference to derive desired graph object.
* A reference is either DI* or II*
* The parameter objp is the current object.
* Assume ref is type-correct.
*/
static Agobj_t *deref(Expr_t * pgm, Exnode_t * x, Exref_t * ref,
Agobj_t * objp, Gpr_t * state)
{
void *ptr;
if (ref == 0)
return objp;
else if (ref->symbol->lex == DYNAMIC) {
ptr =
INT2PTR(void *,
x->data.variable.dyna->data.variable.dyna->data.
constant.value.integer);
if (!ptr) {
exerror("null reference %s in expression %s.%s",
ref->symbol->name, ref->symbol->name, deparse(pgm, x,
state->tmp));
return ptr;
} else
return deref(pgm, x, ref->next, (Agobj_t *) ptr, state);
} else
switch (ref->symbol->index) { /* sym->lex == ID */
case V_outgraph:
return deref(pgm, x, ref->next, (Agobj_t *) state->outgraph,
state);
break;
case V_this:
return deref(pgm, x, ref->next, state->curobj, state);
break;
case V_thisg:
return deref(pgm, x, ref->next, (Agobj_t *) state->curgraph,
state);
break;
case V_nextg:
return deref(pgm, x, ref->next, (Agobj_t *) state->nextgraph,
state);
break;
case V_targt:
return deref(pgm, x, ref->next, (Agobj_t *) state->target,
state);
break;
case V_travedge:
return deref(pgm, x, ref->next, (Agobj_t *) state->tvedge,
state);
break;
case V_travroot:
return deref(pgm, x, ref->next, (Agobj_t *) state->tvroot,
state);
break;
case V_travnext:
return deref(pgm, x, ref->next, (Agobj_t *) state->tvnext,
state);
break;
case M_head:
if (!objp && !(objp = state->curobj)) {
exerror("Current object $ not defined");
return 0;
}
if (ISEDGE(objp))
return deref(pgm, x, ref->next,
(Agobj_t *) AGHEAD((Agedge_t *) objp), state);
else
exerror("head of non-edge");
break;
case M_tail:
if (!objp && !(objp = state->curobj)) {
exerror("Current object $ not defined");
return 0;
}
if (ISEDGE(objp))
return deref(pgm, x, ref->next,
(Agobj_t *) AGTAIL((Agedge_t *) objp), state);
else
exerror("tail of non-edge %x", objp);
break;
default:
exerror("%s : illegal reference",
ref->symbol->name);
break;
}
return 0;
}
/* assignable:
* Check that attribute is not a read-only, pseudo-attribute.
* Return 1 if okay; fatal otherwise.
*/
static int
assignable (Agobj_t *objp, unsigned char* name)
{
unsigned int ch;
int rv;
unsigned char* p = name;
TFA_Init();
while ((TFA_State >= 0) && (ch = *p)) {
TFA_Advance(ch & ~127 ? 127 : ch);
p++;
}
rv = TFA_Definition();
if (rv < 0) return 1;
switch (AGTYPE(objp)) {
case AGRAPH :
if (rv & Y(G))
exerror("Cannot assign to pseudo-graph attribute %s", name);
break;
case AGNODE :
if (rv & Y(V))
exerror("Cannot assign to pseudo-node attribute %s", name);
break;
default : /* edge */
if (rv & Y(E))
exerror("Cannot assign to pseudo-edge attribute %s", name);
break;
}
return 1;
}
/* setattr:
* Set object's attribute name to val.
* Initialize attribute if necessary.
*/
static int
setattr (Agobj_t *objp, char* name, char* val)
{
Agsym_t *gsym = agattrsym(objp, name);
if (!gsym) {
gsym = agattr(agroot(agraphof(objp)), AGTYPE(objp), name, "");
}
return agxset(objp, gsym, val);
}
/* kindToStr:
*/
static char*
kindToStr (int kind)
{
char* s;
switch (kind) {
case AGRAPH :
s = "graph";
break;
case AGNODE :
s = "node";
break;
default :
s = "edge";
break;
}
return s;
}
/* kindOf:
* Return string rep of object's kind
*/
static char*
kindOf (Agobj_t* objp)
{
return (kindToStr (agobjkind (objp)));
}
/* lookup:
* Apply symbol to get field value of objp
* Assume objp != NULL
*/
static int lookup(Expr_t * pgm, Agobj_t * objp, Exid_t * sym, Extype_t * v,
Gpr_t *state)
{
if (sym->lex == ID) {
switch (sym->index) {
case M_head:
if (ISEDGE(objp))
v->integer = PTR2INT(AGHEAD((Agedge_t *) objp));
else {
error(ERROR_WARNING, "head of non-edge");
return -1;
}
break;
case M_tail:
if (ISEDGE(objp))
v->integer = PTR2INT(AGTAIL((Agedge_t *) objp));
else {
error(ERROR_WARNING, "tail of non-edge");
return -1;
}
break;
case M_name:
v->string = nameOf(pgm, objp, state->tmp);
break;
case M_indegree:
if (AGTYPE(objp) == AGNODE)
v->integer = agdegree(agroot(objp), (Agnode_t *) objp, 1, 0);
else {
exerror("indegree of non-node");
return -1;
}
break;
case M_outdegree:
if (AGTYPE(objp) == AGNODE)
v->integer = agdegree(agroot(objp), (Agnode_t *) objp, 0, 1);
else {
exerror("outdegree of non-node");
return -1;
}
break;
case M_degree:
if (AGTYPE(objp) == AGNODE)
v->integer = agdegree(agroot(objp), (Agnode_t *) objp, 1, 1);
else {
exerror("degree of non-node");
return -1;
}
break;
case M_X:
if (AGTYPE(objp) == AGNODE) {
if (posOf ((Agnode_t *) objp, 0, &(v->floating)))
exerror("no x coordinate for node \"%s\"", agnameof(objp));
} else {
exerror("x coordinate of non-node");
return -1;
}
break;
case M_Y:
if (AGTYPE(objp) == AGNODE) {
if (posOf ((Agnode_t *) objp, 1, &(v->floating)))
exerror("no y coordinate for node \"%s\"", agnameof(objp));
} else {
exerror("x coordinate of non-node");
return -1;
}
break;
case M_parent:
if (AGTYPE(objp) == AGRAPH)
v->integer = PTR2INT(agparent((Agraph_t *) objp));
else {
exerror("parent of non-graph");
return -1;
}
break;
case M_root:
v->integer = PTR2INT(agroot(agraphof(objp)));
break;
case M_n_edges:
if (AGTYPE(objp) == AGRAPH)
v->integer = agnedges((Agraph_t *) objp);
else {
exerror("n_edges of non-graph");
return -1;
}
break;
case M_n_nodes:
if (AGTYPE(objp) == AGRAPH)
v->integer = agnnodes((Agraph_t *) objp);
else {
exerror("n_nodes of non-graph");
return -1;
}
break;
case M_directed:
if (AGTYPE(objp) == AGRAPH)
v->integer = agisdirected((Agraph_t *) objp);
else {
exerror("directed of non-graph");
return -1;
}
break;
case M_strict:
if (AGTYPE(objp) == AGRAPH)
v->integer = agisstrict((Agraph_t *) objp);
else {
exerror("strict of non-graph");
return -1;
}
break;
default:
error(ERROR_WARNING, "%s : illegal reference", sym->name);
return -1;
break;
}
} else {
Agsym_t *gsym = agattrsym(objp, sym->name);
if (!gsym) {
gsym = agattr(agroot(agraphof(objp)), AGTYPE(objp), sym->name, "");
error(ERROR_WARNING, "Using value of uninitialized %s attribute \"%s\" of \"%s\"", kindOf (objp), sym->name, nameOf(pgm, objp, state->tmp));
}
v->string = agxget(objp, gsym);
}
return 0;
}
/* getArg:
* Return value associated with $n.
*/
static char *getArg(int n, Gpr_t * state)
{
if (n >= state->argc) {
exerror("program references ARGV[%d] - undefined", n);
return 0;
}
return (state->argv[n]);
}
/* setDfltAttr:
*/
static int
setDfltAttr (Agraph_t *gp, char* k, char* name, char* value)
{
int kind;
switch (*k) {
case 'G' :
kind = AGRAPH;
break;
case 'E' :
kind = AGEDGE;
break;
case 'N' :
kind = AGNODE;
break;
default :
error(ERROR_WARNING, "Unknown kind \"%s\" passed to setDflt()", k);
return 1;
break;
}
agattr(gp, kind, name, value);
return 0;
}
/* toKind:
* Map string to object kind
*/
static int
toKind (char* k, char* fn)
{
int kind;
switch (*k) {
case 'G' :
kind = AGRAPH;
break;
case 'E' :
kind = AGEDGE;
break;
case 'N' :
kind = AGNODE;
break;
default :
exerror("Unknown kind \"%s\" passed to %s()", k, fn);
kind = 0;
break;
}
return kind;
}
/* nxtAttr:
*/
static char*
nxtAttr (Agraph_t *gp, char* k, char* name)
{
char* fn = (name ? "nxtAttr" : "fstAttr");
int kind = toKind (k, fn);
Agsym_t* sym;
if (name) {
sym = agattr (gp, kind, name, 0);
if (!sym) {
exerror("Third argument \"%s\" in nxtAttr() must be the name of an existing attribute", name);
return "";
}
}
else sym = NULL;
sym = agnxtattr (gp, kind, sym);
if (sym) return sym->name;
else return "";
}
/* getDfltAttr:
*/
static char*
getDfltAttr (Agraph_t *gp, char* k, char* name)
{
int kind = toKind (k, "getDflt");
Agsym_t* sym = agattr (gp, kind, name, 0);
if (!sym) {
sym = agattr(gp, kind, name, "");
error(ERROR_WARNING, "Uninitialized %s attribute \"%s\" in %s",
kindToStr (kind), name, "getDflt");
}
return sym->defval;
}
/* getval:
* Return value associated with gpr identifier.
*/
static Extype_t
getval(Expr_t * pgm, Exnode_t * node, Exid_t * sym, Exref_t * ref,
void *env, int elt, Exdisc_t * disc)
{
Extype_t v;
Gpr_t *state;
Extype_t *args;
Agobj_t *objp;
Agobj_t *objp1;
char *key;
Agraph_t *gp;
Agnode_t *np;
Agnode_t *hp;
Agedge_t *ep;
char* name;
gvprbinding* bp;
assert(sym->lex != CONSTANT);
if (elt == EX_CALL) {
args = (Extype_t *) env;
state = (Gpr_t *) (disc->user);
switch (sym->index) {
case F_graph:
gp = openG(args[0].string, xargs(args[1].string));
v.integer = PTR2INT(gp);
break;
case F_subg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
gp = openSubg(gp, args[1].string);
v.integer = PTR2INT(gp);
} else {
error(ERROR_WARNING, "NULL graph passed to subg()");
v.integer = 0;
}
break;
case F_issubg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
v.integer = PTR2INT(agsubg(gp, args[1].string, 0));
} else {
error(ERROR_WARNING, "NULL graph passed to isSubg()");
v.integer = 0;
}
break;
case F_fstsubg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
gp = agfstsubg(gp);
v.integer = PTR2INT(gp);
} else {
error(ERROR_WARNING, "NULL graph passed to fstsubg()");
v.integer = 0;
}
break;
case F_nxtsubg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
gp = agnxtsubg(gp);
v.integer = PTR2INT(gp);
} else {
error(ERROR_WARNING, "NULL graph passed to nxtsubg()");
v.integer = 0;
}
break;
case F_node:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
np = openNode(gp, args[1].string);
v.integer = PTR2INT(np);
} else {
error(ERROR_WARNING, "NULL graph passed to node()");
v.integer = 0;
}
break;
case F_addnode:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to addNode()");
v.integer = 0;
} else if (!np) {
error(ERROR_WARNING, "NULL node passed to addNode()");
v.integer = 0;
} else
v.integer = PTR2INT(addNode(gp, np, 1));
break;
case F_fstnode:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
np = agfstnode(gp);
v.integer = PTR2INT(np);
} else {
error(ERROR_WARNING, "NULL graph passed to fstnode()");
v.integer = 0;
}
break;
case F_nxtnode:
np = INT2PTR(Agnode_t *, args[0].integer);
if (np) {
np = agnxtnode(agroot(np), np);
v.integer = PTR2INT(np);
} else {
error(ERROR_WARNING, "NULL node passed to nxtnode()");
v.integer = 0;
}
break;
case F_nxtnodesg:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
np = agnxtnode(gp, np);
v.integer = PTR2INT(np);
} else {
error(ERROR_WARNING, "NULL node passed to nxtnode_sg()");
v.integer = 0;
}
break;
case F_isnode:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
v.integer = PTR2INT(agnode(gp, args[1].string, 0));
} else {
error(ERROR_WARNING, "NULL graph passed to isNode()");
v.integer = 0;
}
break;
case F_issubnode:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
v.integer = PTR2INT(addNode(gp, np, 0));
} else {
error(ERROR_WARNING, "NULL node passed to isSubnode()");
v.integer = 0;
}
break;
case F_indegree:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
v.integer = agdegree(gp, np, 1, 0);
} else {
error(ERROR_WARNING, "NULL node passed to indegreeOf()");
v.integer = 0;
}
break;
case F_outdegree:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
v.integer = agdegree(gp, np, 0, 1);
} else {
error(ERROR_WARNING, "NULL node passed to outdegreeOf()");
v.integer = 0;
}
break;
case F_degree:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
v.integer = agdegree(gp, np, 1, 1);
} else {
error(ERROR_WARNING, "NULL node passed to degreeOf()");
v.integer = 0;
}
break;
case F_isin:
gp = INT2PTR(Agraph_t *, args[0].integer);
objp = INT2PTR(Agobj_t *, args[1].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to isIn()");
v.integer = 0;
} else if (!objp) {
error(ERROR_WARNING, "NULL object passed to isIn()");
v.integer = 0;
} else
v.integer = agcontains (gp, objp);
break;
case F_compof:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to compOf()");
v.integer = 0;
} else if (!np) {
error(ERROR_WARNING, "NULL node passed to compOf()");
v.integer = 0;
} else
v.integer = PTR2INT(compOf(gp, np));
break;
case F_kindof:
objp = INT2PTR(Agobj_t *, args[0].integer);
if (!objp) {
exerror("NULL object passed to kindOf()");
v.string = 0;
} else switch (AGTYPE(objp)) {
case AGRAPH :
v.string = "G";
break;
case AGNODE :
v.string = "N";
break;
case AGINEDGE :
case AGOUTEDGE :
v.string = "E";
break;
}
break;
case F_edge:
key = args[2].string;
if (*key == '\0')
key = 0;
np = INT2PTR(Agnode_t *, args[0].integer);
hp = INT2PTR(Agnode_t *, args[1].integer);
if (!np) {
error(ERROR_WARNING, "NULL tail node passed to edge()");
v.integer = 0;
} else if (!hp) {
error(ERROR_WARNING, "NULL head node passed to edge()");
v.integer = 0;
} else {
ep = openEdge(0, np, hp, key);
v.integer = PTR2INT(ep);
}
break;
case F_edgesg:
key = args[3].string;
if (*key == '\0')
key = 0;
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
hp = INT2PTR(Agnode_t *, args[2].integer);
if (!np) {
error(ERROR_WARNING, "NULL tail node passed to edge_sg()");
v.integer = 0;
} else if (!hp) {
error(ERROR_WARNING, "NULL head node passed to edge_sg()");
v.integer = 0;
} else {
ep = openEdge(gp, np, hp, key);
v.integer = PTR2INT(ep);
}
break;
case F_addedge:
gp = INT2PTR(Agraph_t *, args[0].integer);
ep = INT2PTR(Agedge_t *, args[1].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to addEdge()");
v.integer = 0;
} else if (!ep) {
error(ERROR_WARNING, "NULL edge passed to addEdge()");
v.integer = 0;
} else
v.integer = PTR2INT(addEdge(gp, ep, 1));
break;
case F_opp:
ep = INT2PTR(Agedge_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!ep) {
error(ERROR_WARNING, "NULL edge passed to opp()");
v.integer = 0;
} else if (!np) {
error(ERROR_WARNING, "NULL node passed to opp()");
v.integer = 0;
} else {
if (aghead(ep) == np)
np = agtail(ep);
else
np = aghead(ep);
v.integer = PTR2INT(np);
}
break;
case F_isedge:
key = args[2].string;
if (*key == '\0')
key = 0;
np = INT2PTR(Agnode_t *, args[0].integer);
hp = INT2PTR(Agnode_t *, args[1].integer);
if (!np) {
error(ERROR_WARNING, "NULL tail node passed to isEdge()");
v.integer = 0;
} else if (!hp) {
error(ERROR_WARNING, "NULL head node passed to isEdge()");
v.integer = 0;
} else
v.integer = PTR2INT(isEdge(agroot(np), np, hp, key));
break;
case F_isedgesg:
key = args[3].string;
if (*key == '\0')
key = 0;
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
hp = INT2PTR(Agnode_t *, args[2].integer);
if (!gp)
gp = agroot(np);
if (!np) {
error(ERROR_WARNING, "NULL tail node passed to isEdge_sg()");
v.integer = 0;
} else if (!hp) {
error(ERROR_WARNING, "NULL head node passed to isEdge_sg()");
v.integer = 0;
} else
v.integer = PTR2INT(isEdge(gp, np, hp, key));
break;
case F_issubedge:
gp = INT2PTR(Agraph_t *, args[0].integer);
ep = INT2PTR(Agedge_t *, args[1].integer);
if (!gp)
gp = agroot(ep);
if (ep) {
v.integer = PTR2INT(addEdge(gp, ep, 0));
} else {
error(ERROR_WARNING, "NULL edge passed to isSubedge()");
v.integer = 0;
}
break;
case F_fstout:
np = INT2PTR(Agnode_t *, args[0].integer);
if (np) {
ep = agfstout(agroot(np), np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstout()");
v.integer = 0;
}
break;
case F_fstoutsg:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
ep = agfstout(gp, np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstout_sg()");
v.integer = 0;
}
break;
case F_nxtout:
ep = INT2PTR(Agedge_t *, args[0].integer);
if (ep) {
ep = agnxtout(agroot(ep), ep);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL edge passed to nxtout()");
v.integer = 0;
}
break;
case F_nxtoutsg:
gp = INT2PTR(Agraph_t *, args[0].integer);
ep = INT2PTR(Agedge_t *, args[1].integer);
if (!gp)
gp = agroot(ep);
if (ep) {
ep = agnxtout(gp, ep);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL edge passed to nxtout_sg()");
v.integer = 0;
}
break;
case F_fstin:
np = INT2PTR(Agnode_t *, args[0].integer);
if (np) {
ep = agfstin(agroot(np), np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstin()");
v.integer = 0;
}
break;
case F_fstinsg:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
ep = agfstin(gp, np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstin_sg()");
v.integer = 0;
}
break;
case F_nxtin:
ep = INT2PTR(Agedge_t *, args[0].integer);
if (ep) {
ep = agnxtin(agroot(ep), ep);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL edge passed to nxtin()");
v.integer = 0;
}
break;
case F_nxtinsg:
gp = INT2PTR(Agraph_t *, args[0].integer);
ep = INT2PTR(Agedge_t *, args[1].integer);
if (!gp)
gp = agroot(ep);
if (ep) {
ep = agnxtin(gp, ep);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL edge passed to nxtin_sg()");
v.integer = 0;
}
break;
case F_fstedge:
np = INT2PTR(Agnode_t *, args[0].integer);
if (np) {
ep = agfstedge(agroot(np), np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstedge()");
v.integer = 0;
}
break;
case F_fstedgesg:
gp = INT2PTR(Agraph_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!gp)
gp = agroot(np);
if (np) {
ep = agfstedge(gp, np);
v.integer = PTR2INT(ep);
} else {
error(ERROR_WARNING, "NULL node passed to fstedge_sg()");
v.integer = 0;
}
break;
case F_nxtedge:
ep = INT2PTR(Agedge_t *, args[0].integer);
np = INT2PTR(Agnode_t *, args[1].integer);
if (!ep) {
error(ERROR_WARNING, "NULL edge passed to nxtedge()");
v.integer = 0;
} else if (!np) {
error(ERROR_WARNING, "NULL node passed to nxtedge()");
v.integer = 0;
} else {
ep = agnxtedge(agroot(np), ep, np);
v.integer = PTR2INT(ep);
}
break;
case F_nxtedgesg:
gp = INT2PTR(Agraph_t *, args[0].integer);
ep = INT2PTR(Agedge_t *, args[1].integer);
np = INT2PTR(Agnode_t *, args[2].integer);
if (!gp)
gp = agroot(np);
if (!ep) {
error(ERROR_WARNING, "NULL edge passed to nxtedge_sg()");
v.integer = 0;
} else if (!np) {
error(ERROR_WARNING, "NULL node passed to nxtedge_sg()");
v.integer = 0;
} else {
ep = agnxtedge(gp, ep, np);
v.integer = PTR2INT(ep);
}
break;
case F_copy:
gp = INT2PTR(Agraph_t *, args[0].integer);
objp = INT2PTR(Agobj_t *, args[1].integer);
if (!objp) {
error(ERROR_WARNING, "NULL object passed to clone()");
v.integer = 0;
} else
v.integer = PTR2INT(copy(gp, objp));
break;
case F_clone:
gp = INT2PTR(Agraph_t *, args[0].integer);
objp = INT2PTR(Agobj_t *, args[1].integer);
if (!objp) {
error(ERROR_WARNING, "NULL object passed to clone()");
v.integer = 0;
} else
v.integer = PTR2INT(clone(gp, objp));
break;
case F_cloneG:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
gp = cloneG(gp, args[1].string);
v.integer = PTR2INT(gp);
} else {
error(ERROR_WARNING, "NULL graph passed to cloneG()");
v.integer = 0;
}
break;
case F_copya:
objp = INT2PTR(Agobj_t *, args[0].integer);
objp1 = INT2PTR(Agobj_t *, args[1].integer);
if (!(objp && objp1)) {
error(ERROR_WARNING, "NULL object passed to copyA()");
v.integer = 0;
} else
v.integer = copyAttr(objp, objp1);
break;
case F_induce:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to induce()");
v.integer = 1;
} else {
nodeInduce(gp);
v.integer = 0;
}
break;
case F_write:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to write()");
v.integer = 1;
} else
v.integer = sfioWrite (gp, state->outFile, state->dfltIO);
break;
case F_writeg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to writeG()");
v.integer = 1;
} else
v.integer = writeFile(gp, args[1].string, state->dfltIO);
break;
case F_readg:
gp = readFile(args[0].string);
v.integer = PTR2INT(gp);
break;
case F_fwriteg:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to fwriteG()");
v.integer = 1;
} else
v.integer = fwriteFile(pgm, gp, args[1].integer, state->dfltIO);
break;
case F_freadg:
gp = freadFile(pgm, args[0].integer);
v.integer = PTR2INT(gp);
break;
case F_openf:
v.integer = openFile(pgm, args[0].string, args[1].string);
break;
case F_closef:
v.integer = closeFile(pgm, args[0].integer);
break;
case F_readl:
v.string = readLine(pgm, args[0].integer);
break;
case F_isdirect:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to isDirect()");
v.integer = 0;
} else {
v.integer = agisdirected(gp);
}
break;
case F_isstrict:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to isStrict()");
v.integer = 0;
} else {
v.integer = agisstrict(gp);
}
break;
case F_delete:
gp = INT2PTR(Agraph_t *, args[0].integer);
objp = INT2PTR(Agobj_t *, args[1].integer);
if (!objp) {
error(ERROR_WARNING, "NULL object passed to delete()");
v.integer = 1;
} else if (objp == (Agobj_t *) (state->curgraph)) {
error(ERROR_WARNING, "cannot delete current graph $G");
v.integer = 1;
} else if (objp == (Agobj_t *) (state->target)) {
error(ERROR_WARNING, "cannot delete target graph $T");
v.integer = 1;
} else if (objp == state->curobj) {
if (!(v.integer = deleteObj(gp, objp)))
state->curobj = NULL;
} else
v.integer = deleteObj(gp, objp);
break;
case F_lock:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to lock()");
v.integer = -1;
} else
v.integer = lockGraph(gp, args[1].integer);
break;
case F_nnodes:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to nNodes()");
v.integer = 0;
} else {
v.integer = agnnodes(gp);
}
break;
case F_nedges:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (!gp) {
error(ERROR_WARNING, "NULL graph passed to nEdges()");
v.integer = 0;
} else {
v.integer = agnedges(gp);
}
break;
case F_atoi:
v.integer = atoi(args[0].string);
break;
case F_atof:
v.floating = atof(args[0].string);
break;
case F_sqrt:
v.floating = sqrt(args[0].floating);
break;
case F_cos:
v.floating = cos(args[0].floating);
break;
case F_sin:
v.floating = sin(args[0].floating);
break;
case F_atan2:
v.floating = atan2(args[0].floating, args[1].floating);
break;
case F_exp:
v.floating = exp(args[0].floating);
break;
case F_pow:
v.floating = pow(args[0].floating, args[1].floating);
break;
case F_log:
v.floating = log(args[0].floating);
break;
case F_min:
v.floating = MIN(args[0].floating, args[1].floating);
break;
case F_max:
v.floating = MAX(args[0].floating, args[1].floating);
break;
case F_sys:
v.integer = system(args[0].string);
break;
case F_hasattr:
case F_get:
objp = INT2PTR(Agobj_t *, args[0].integer);
name = args[1].string;
if (!objp) {
exerror("NULL object passed to aget()/hasAttr()");
v.integer = 0;
} else if (!name) {
exerror("NULL name passed to aget()/hasAttr()");
v.integer = 0;
}
else {
Agsym_t *gsym = agattrsym(objp, name);
if (sym->index == F_hasattr)
v.integer = (gsym != NULL);
else {
if (!gsym) {
gsym = agattr(agroot(agraphof(objp)), AGTYPE(objp), name, "");
error(ERROR_WARNING, "Using value of %s uninitialized attribute \"%s\" of \"%s\" in aget()", kindOf (objp), name, nameOf(pgm, objp, state->tmp));
}
v.string = agxget(objp, gsym);
}
}
break;
case F_set:
objp = INT2PTR(Agobj_t *, args[0].integer);
if (!objp) {
error(ERROR_WARNING, "NULL object passed to aset()");
v.integer = 1;
} else {
char* name = args[1].string;
char* value = args[2].string;
if (!name) {
error(ERROR_WARNING, "NULL name passed to aset()");
v.integer = 1;
}
else if (!value) {
error(ERROR_WARNING, "NULL value passed to aset()");
v.integer = 1;
}
else {
v.integer = setattr(objp, name, value);
}
}
break;
case F_dset:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
char* kind = args[1].string;
char* name = args[2].string;
char* value = args[3].string;
if (!name) {
error(ERROR_WARNING, "NULL name passed to setDflt()");
v.integer = 1;
}
else if (!value) {
error(ERROR_WARNING, "NULL value passed to setDflt()");
v.integer = 1;
}
else if (!kind) {
error(ERROR_WARNING, "NULL kind passed to setDflt()");
v.integer = 1;
}
else {
v.integer = setDfltAttr(gp, kind, name, value);
}
} else {
error(ERROR_WARNING, "NULL graph passed to node()");
v.integer = 0;
}
break;
case F_fstattr:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
char* kind = args[1].string;
if (!kind) {
error(ERROR_ERROR,"NULL kind passed to fstAttr()");
v.string = 0;
}
else {
v.string = nxtAttr (gp, kind, NULL);
}
} else {
exerror("NULL graph passed to fstAttr()");
v.string = 0;
}
break;
case F_nxtattr:
case F_isattr:
case F_dget:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
char* kind = args[1].string;
char* name = args[2].string;
if (!name) {
exerror("NULL name passed to %s", sym->name);
v.string = 0;
}
else if (!kind) {
exerror("NULL kind passed to %s", sym->name);
v.string = 0;
}
else if (sym->index == F_isattr) {
v.integer = (agattr(gp, toKind (kind, sym->name), name, 0) != NULL);
}
else if (sym->index == F_nxtattr) {
v.string = nxtAttr (gp, kind, name);
}
else {
v.string = getDfltAttr(gp, kind, name);
}
} else {
exerror("NULL graph passed to %s", sym->name);
v.string = 0;
}
break;
case F_canon:
v.string = canon(pgm, args[0].string);
break;
case F_ishtml:
v.integer = aghtmlstr(args[0].string);
break;
case F_html:
gp = INT2PTR(Agraph_t *, args[0].integer);
if (gp) {
v.string = toHtml(gp, args[1].string);
} else {
error(ERROR_WARNING, "NULL graph passed to html()");
v.string = 0;
}
break;
case F_tolower:
v.string = toLower(pgm, args[0].string, state->tmp);
break;
case F_colorx:
v.string = colorx(pgm, args[0].string, args[1].string, state->tmp);
break;
case F_strcmp:
if (args[0].string) {
if (args[1].string)
v.integer = strcmp(args[0].string,args[1].string);
else
v.integer = -1;
} else if (args[1].string)
v.integer = 1;
else
v.integer = 0;
break;
case F_toupper:
v.string = toUpper(pgm, args[0].string, state->tmp);
break;
case F_xof:
v.string = xyOf(pgm, args[0].string, 1);
break;
case F_yof:
v.string = xyOf(pgm, args[0].string, 0);
break;
case F_llof:
v.string = bbOf(pgm, args[0].string, 1);
break;
case F_urof:
v.string = bbOf(pgm, args[0].string, 0);
break;
case F_length:
v.integer = strlen(args[0].string);
break;
case F_index:
v.integer = indexOf(args[0].string, args[1].string);
break;
case F_rindex:
v.integer = rindexOf(args[0].string, args[1].string);
break;
case F_match:
v.integer = match(args[0].string, args[1].string);
break;
case F_call:
if ((bp = findBinding (state, args[0].string)))
v.integer = (bp->fn)(args[1].string);
else
v.integer = -1;
break;
default:
exerror("unknown function call: %s", sym->name);
}
return v;
} else if (elt == EX_ARRAY) {
args = (Extype_t *) env;
state = (Gpr_t *) (disc->user);
switch (sym->index) {
case A_ARGV:
v.string = getArg(args[0].integer, state);
break;
default:
exerror("unknown array name: %s", sym->name);
v.string = 0;
}
return v;
}
state = (Gpr_t *) env;
if (ref) {
objp = deref(pgm, node, ref, 0, state);
if (!objp)
exerror("null reference in expression %s",
deparse(pgm, node, state->tmp));
} else if ((sym->lex == ID) && (sym->index <= LAST_V)) {
switch (sym->index) {
case V_this:
v.integer = PTR2INT(state->curobj);
break;
case V_thisg:
v.integer = PTR2INT(state->curgraph);
break;
case V_nextg:
v.integer = PTR2INT(state->nextgraph);
break;
case V_targt:
v.integer = PTR2INT(state->target);
break;
case V_outgraph:
v.integer = PTR2INT(state->outgraph);
break;
case V_tgtname:
v.string = state->tgtname;
break;
case V_infname:
v.string = state->infname;
break;
case V_ARGC:
v.integer = state->argc;
break;
case V_travtype:
v.integer = state->tvt;
break;
case V_travroot:
v.integer = PTR2INT(state->tvroot);
break;
case V_travnext:
v.integer = PTR2INT(state->tvnext);
break;
case V_travedge:
v.integer = PTR2INT(state->tvedge);
break;
}
return v;
} else {
objp = state->curobj;
if (!objp) {
exerror("current object $ not defined as reference for %s",
deparse(pgm, node, state->tmp));
}
}
if (objp) {
if (lookup(pgm, objp, sym, &v, state)) {
exerror("in expression %s", deparse(pgm, node, state->tmp));
v.integer = 0;
}
}
else
v.integer = 0;
return v;
}
#define MINTYPE (LAST_M+1) /* First type occurs after last M_ */
static char *typeName(Expr_t * pg, int op)
{
return typenames[op - MINTYPE];
}
/* setval:
* Set sym to value v.
* Return -1 if not allowed.
* Assume already type correct.
*/
static int
setval(Expr_t * pgm, Exnode_t * x, Exid_t * sym, Exref_t * ref,
void *env, int elt, Extype_t v, Exdisc_t * disc)
{
Gpr_t *state;
Agobj_t *objp;
Agnode_t *np;
int iv;
int rv = 0;
state = (Gpr_t *) env;
if (ref) {
objp = deref(pgm, x, ref, 0, state);
if (!objp) {
exerror("in expression %s.%s",
ref->symbol->name, deparse(pgm, x, state->tmp));
return -1;
}
} else if ((MINNAME <= sym->index) && (sym->index <= MAXNAME)) {
switch (sym->index) {
case V_outgraph:
state->outgraph = INT2PTR(Agraph_t *, v.integer);
break;
case V_travtype:
iv = v.integer;
if (validTVT(v.integer))
state->tvt = (trav_type) iv;
else
error(1, "unexpected value %d assigned to %s : ignored",
iv, typeName(pgm, T_tvtyp));
break;
case V_travroot:
np = INT2PTR(Agnode_t *, v.integer);
if (!np || (agroot(np) == state->curgraph))
state->tvroot = np;
else {
error(1, "cannot set $tvroot, node %s not in $G : ignored",
agnameof(np));
}
break;
case V_travnext:
np = INT2PTR(Agnode_t *, v.integer);
if (!np || (agroot(np) == state->curgraph)) {
state->tvnext = np;
state->flags |= GV_NEXT_SET;
} else {
error(1, "cannot set $tvnext, node %s not in $G : ignored",
agnameof(np));
}
break;
case V_tgtname:
if (!streq(state->tgtname, v.string)) {
vmfree(pgm->vm, state->tgtname);
state->tgtname = vmstrdup(pgm->vm, v.string);
state->name_used = 0;
}
break;
default:
rv = -1;
break;
}
return rv;
} else {
objp = state->curobj;
if (!objp) {
exerror("current object $ undefined in expression %s",
deparse(pgm, x, state->tmp));
return -1;
}
}
assignable (objp, (unsigned char*)(sym->name));
return setattr(objp, sym->name, v.string);
}
static int codePhase;
#define haveGraph ((1 <= codePhase) && (codePhase <= 4))
#define haveTarget ((2 <= codePhase) && (codePhase <= 4))
#define inWalk ((2 <= codePhase) && (codePhase <= 3))
/* typeChk:
* Type check input type against implied type of symbol sym.
* If okay, return result type; else return 0.
* For functions, input type set must intersect with function domain.
* This means type errors may occur, but these will be caught at runtime.
* For non-functions, input type must be 0.
*/
static tctype typeChk(tctype intype, Exid_t * sym)
{
tctype dom = 0, rng = 0;
switch (sym->lex) {
case DYNAMIC:
dom = 0;
switch (sym->type) {
case T_obj:
rng = YALL;;
break;
case T_node:
rng = Y(V);
break;
case T_graph:
rng = Y(G);
break;
case T_edge:
rng = Y(E);
break;
case INTEGER:
rng = Y(I);
break;
case FLOATING:
rng = Y(F);
break;
case STRING:
rng = Y(S);
break;
default:
exerror("unknown dynamic type %d of symbol %s", sym->type,
sym->name);
break;
}
break;
case ID:
if (sym->index <= MAXNAME) {
switch (sym->index) {
case V_travroot:
case V_this:
case V_thisg:
case V_nextg:
if (!haveGraph)
exerror
("keyword %s cannot be used in BEGIN/END statements",
sym->name);
break;
case V_targt:
if (!haveTarget)
exerror
("keyword %s cannot be used in BEGIN/BEG_G/END statements",
sym->name);
break;
}
dom = tchk[sym->index][0];
rng = tchk[sym->index][1];
} else {
dom = YALL;
rng = Y(S);
}
break;
case NAME:
if (!intype && !haveGraph)
exerror
("undeclared, unmodified names like \"%s\" cannot be\nused in BEGIN and END statements",
sym->name);
dom = YALL;
rng = Y(S);
break;
default:
exerror("unexpected symbol in typeChk: name %s, lex %d",
sym->name, sym->lex);
break;
}
if (dom) {
if (!intype)
intype = YALL; /* type of $ */
if (!(dom & intype))
rng = 0;
} else if (intype)
rng = 0;
return rng;
}
/* typeChkExp:
* Type check variable expression.
*/
static tctype typeChkExp(Exref_t * ref, Exid_t * sym)
{
tctype ty;
if (ref) {
ty = typeChk(0, ref->symbol);
for (ref = ref->next; ty && ref; ref = ref->next)
ty = typeChk(ty, ref->symbol);
if (!ty)
return 0;
} else
ty = 0;
return typeChk(ty, sym);
}
/* refval:
* Called during compilation for uses of references: abc.x
* Also for abc.f(..), type abc.v, "abc".x and CONSTANTS.
* The grammar has been altered to disallow the first 3.
* Type check expressions; return value unused.
*/
static Extype_t
refval(Expr_t * pgm, Exnode_t * node, Exid_t * sym, Exref_t * ref,
char *str, int elt, Exdisc_t * disc)
{
Extype_t v;
if (sym->lex == CONSTANT) {
switch (sym->index) {
case C_flat:
v.integer = TV_flat;
break;
case C_ne:
v.integer = TV_ne;
break;
case C_en:
v.integer = TV_en;
break;
case C_bfs:
v.integer = TV_bfs;
break;
case C_dfs:
v.integer = TV_dfs;
break;
case C_fwd:
v.integer = TV_fwd;
break;
case C_rev:
v.integer = TV_rev;
break;
case C_postdfs:
v.integer = TV_postdfs;
break;
case C_postfwd:
v.integer = TV_postfwd;
break;
case C_postrev:
v.integer = TV_postrev;
break;
case C_prepostdfs:
v.integer = TV_prepostdfs;
break;
case C_prepostfwd:
v.integer = TV_prepostfwd;
break;
case C_prepostrev:
v.integer = TV_prepostrev;
break;
case C_null:
v.integer = 0;
break;
default:
v = exzero(node->type);
break;
}
} else {
if (!typeChkExp(ref, sym)) {
Gpr_t *state = (Gpr_t *) (disc->user);
exerror("type error using %s",
deparse(pgm, node, state->tmp));
}
v = exzero(node->type);
}
return v;
}
/* binary:
* Evaluate (l ex->op r) producing a value of type ex->type,
* stored in l.
* May be unary, with r = NULL
* Return -1 if operation cannot be done, 0 otherwise.
* If arg is > 0, operation unnecessary; just report possibility.
*/
int
binary(Expr_t * pg, Exnode_t * l, Exnode_t * ex, Exnode_t * r, int arg,
Exdisc_t * disc)
{
Agobj_t *lobjp;
Agobj_t *robjp;
int ret = -1;
if (BUILTIN(l->type))
return -1;
if (r && BUILTIN(r->type))
return -1;
if (!INTEGRAL(ex->type))
return -1;
if (l->type == T_tvtyp) {
int li, ri;
if (!r)
return -1; /* Assume libexpr handled unary */
if (r->type != T_tvtyp)
return -1;
li = l->data.constant.value.integer;
ri = r->data.constant.value.integer;
switch (ex->op) {
case EQ:
if (arg)
return 0;
l->data.constant.value.integer = (li == ri);
ret = 0;
break;
case NE:
if (arg)
return 0;
l->data.constant.value.integer = (li != ri);
ret = 0;
break;
case '<':
if (arg)
return 0;
l->data.constant.value.integer = (li < ri);
ret = 0;
break;
case LE:
if (arg)
return 0;
l->data.constant.value.integer = (li <= ri);
ret = 0;
break;
case GE:
if (arg)
return 0;
l->data.constant.value.integer = (li >= ri);
ret = 0;
break;
case '>':
if (arg)
return 0;
l->data.constant.value.integer = (li > ri);
ret = 0;
break;
}
}
/* l is a graph object; make sure r is also */
if (r && (r->type == T_tvtyp))
return -1;
lobjp = INT2PTR(Agobj_t *, l->data.constant.value.integer);
if (r)
robjp = INT2PTR(Agobj_t *, r->data.constant.value.integer);
else
robjp = 0;
switch (ex->op) {
case EQ:
if (arg)
return 0;
l->data.constant.value.integer = !compare(lobjp, robjp);
ret = 0;
break;
case NE:
if (arg)
return 0;
l->data.constant.value.integer = compare(lobjp, robjp);
ret = 0;
break;
case '<':
if (arg)
return 0;
l->data.constant.value.integer = (compare(lobjp, robjp) < 0);
ret = 0;
break;
case LE:
if (arg)
return 0;
l->data.constant.value.integer = (compare(lobjp, robjp) <= 0);
ret = 0;
break;
case GE:
if (arg)
return 0;
l->data.constant.value.integer = (compare(lobjp, robjp) >= 0);
ret = 0;
break;
case '>':
if (arg)
return 0;
l->data.constant.value.integer = (compare(lobjp, robjp) > 0);
ret = 0;
break;
}
return ret;
}
/* strToTvtype:
*/
static int
strToTvtype (char* s)
{
int rt = 0;
char* sfx;
if (!strncmp(s, "TV_", 3)) {
sfx = s + 3;
if (!strcmp(sfx, "flat")) {
rt = TV_flat;
} else if (!strcmp(sfx, "ne")) {
rt = TV_ne;
} else if (!strcmp(sfx, "en")) {
rt = TV_en;
} else if (!strcmp(sfx, "bfs")) {
rt = TV_bfs;
} else if (!strcmp(sfx, "dfs")) {
rt = TV_dfs;
} else if (!strcmp(sfx, "fwd")) {
rt = TV_fwd;
} else if (!strcmp(sfx, "rev")) {
rt = TV_rev;
} else if (!strcmp(sfx, "postdfs")) {
rt = TV_postdfs;
} else if (!strcmp(sfx, "postfwd")) {
rt = TV_postfwd;
} else if (!strcmp(sfx, "postrev")) {
rt = TV_postrev;
} else if (!strcmp(sfx, "prepostdfs")) {
rt = TV_prepostdfs;
} else if (!strcmp(sfx, "prepostfwd")) {
rt = TV_prepostfwd;
} else if (!strcmp(sfx, "prepostrev")) {
rt = TV_prepostrev;
} else
exerror("illegal string \"%s\" for type tvtype_t", s);
} else
exerror("illegal string \"%s\" for type tvtype_t", s);
return rt;
}
/* tvtypeToStr:
*/
static char*
tvtypeToStr (int v)
{
char* s = 0;
switch (v) {
case TV_flat:
s = "TV_flat";
break;
case TV_ne:
s = "TV_ne";
break;
case TV_en:
s = "TV_en";
break;
case TV_bfs:
s = "TV_bfs";
break;
case TV_dfs:
s = "TV_dfs";
break;
case TV_fwd:
s = "TV_fwd";
break;
case TV_rev:
s = "TV_rev";
break;
case TV_postdfs:
s = "TV_postdfs";
break;
case TV_postfwd:
s = "TV_postfwd";
break;
case TV_postrev:
s = "TV_postrev";
break;
case TV_prepostdfs:
s = "TV_prepostdfs";
break;
case TV_prepostfwd:
s = "TV_prepostfwd";
break;
case TV_prepostrev:
s = "TV_prepostrev";
break;
default:
exerror("Unexpected value %d for type tvtype_t",
v);
break;
}
return s;
}
/* stringOf:
* Convert value x to type string.
* Assume x does not have a built-in type
* Return -1 if conversion cannot be done, 0 otherwise.
* If arg is > 0, conversion unnecessary; just report possibility.
*/
static int stringOf(Expr_t * prog, register Exnode_t * x, int arg, Exdisc_t* disc)
{
Agobj_t *objp;
int rv = 0;
if (arg)
return 0;
if (x->type == T_tvtyp) {
if (!(x->data.constant.value.string =
tvtypeToStr (x->data.constant.value.integer)))
rv = -1;
} else {
objp = INT2PTR(Agobj_t *, x->data.constant.value.integer);
if (!objp) {
exerror("cannot generate name for NULL %s",
typeName(prog, x->type));
rv = -1;
}
else {
Gpr_t* state = (Gpr_t *) (disc->user);
x->data.constant.value.string = nameOf(prog, objp, state->tmp);
}
}
x->type = STRING;
return rv;
}
/* convert:
* Convert value x of type x->type to type type.
* Return -1 if conversion cannot be done, 0 otherwise.
* If arg is > 0, conversion unnecessary; just report possibility.
* In particular, assume x != 0 if arg == 0.
* Use #ifdef OLD to remove graph object conversion to strings,
* as this seemed to dangerous.
*/
static int
convert(Expr_t * prog, register Exnode_t * x, int type,
register Exid_t * xref, int arg, Exdisc_t * disc)
{
Agobj_t *objp;
int ret = -1;
/* If both types are built-in, let libexpr handle */
if (BUILTIN(type) && BUILTIN(x->type))
return -1;
if ((type == T_obj) && (x->type <= T_obj))
ret = 0; /* trivial cast from specific graph object to T_obj */
else if ((type <= T_obj) && (x->type == INTEGER)) {
if (x->data.constant.value.integer == 0)
ret = 0; /* allow NULL pointer */
} else if (type == INTEGER) {
ret = 0;
} else if (x->type == T_obj) {
/* check dynamic type */
if (arg) {
if ((type != FLOATING) && (type <= T_obj))
ret = 0;
} else {
objp = INT2PTR(Agobj_t *, x->data.constant.value.integer);
switch (type) {
case T_graph:
if (!objp || AGTYPE(objp) == AGRAPH)
ret = 0;
break;
case T_node:
if (!objp || AGTYPE(objp) == AGNODE)
ret = 0;
break;
case T_edge:
if (!objp || ISEDGE(objp))
ret = 0;
break;
#ifdef OLD
case STRING:
x->data.constant.value.string = nameOf(prog, objp);
ret = 0;
break;
#endif
}
}
} else if (type == STRING) {
if (x->type == T_tvtyp) {
ret = 0;
if (!arg) {
x->data.constant.value.string =
tvtypeToStr (x->data.constant.value.integer);
}
}
#ifdef OLD
else {
objp = INT2PTR(Agobj_t *, x->data.constant.value.integer);
if (objp) {
x->data.constant.value.string = nameOf(prog, objp);
ret = 0;
} else
cvtError(xref, "Uninitialized object");
}
#endif
} else if ((type == T_tvtyp) && (x->type == INTEGER)) {
if (arg)
ret = 0;
else if (validTVT(x->data.constant.value.integer))
ret = 0;
else
exerror("Integer value %d not legal for type tvtype_t",
x->data.constant.value.integer);
}
/* in case libexpr hands us the trivial case */
else if (x->type == type) {
ret = 0;
} else if (x->type == STRING) {
char *s;
if (type == T_tvtyp) {
if (arg)
ret = 0;
else {
ret = 0;
s = x->data.constant.value.string;
x->data.constant.value.integer = strToTvtype(s);
}
}
}
if (!arg && (ret == 0))
x->type = type;
return ret;
}
/* keyval;
* Calculate unique key for object.
* We use this to unify local copies of nodes and edges.
*/
static Extype_t keyval(Expr_t * pgm, Extype_t v, int type, Exdisc_t * disc)
{
if (type <= T_obj) {
v.integer = AGID(INT2PTR(Agobj_t *, v.integer));
}
return v;
}
/* matchval:
* Pattern match strings.
*/
static int
matchval(Expr_t * pgm, Exnode_t * xstr, const char *str, Exnode_t * xpat,
const char *pat, void *env, Exdisc_t * disc)
{
return strgrpmatch(str, pat, NiL, 0,
STR_MAXIMAL | STR_LEFT | STR_RIGHT);
}
/* a2t:
* Convert type indices to symbolic name.
*/
static int
a2t[] = { 0, FLOATING, INTEGER, STRING,
T_node, T_edge, T_graph, T_obj
};
/* initDisc:
* Create and initialize expr discipline.
*/
static Exdisc_t *initDisc(Gpr_t * state)
{
Exdisc_t *dp;
dp = newof(0, Exdisc_t, 1, 0);
if (!dp) {
error(ERROR_ERROR,
"could not create libexp discipline: out of memory");
return 0;
}
dp->version = EX_VERSION;
dp->flags = EX_CHARSTRING | EX_UNDECLARED;
dp->symbols = symbols;
dp->convertf = convert;
dp->stringof = stringOf;
dp->binaryf = binary;
dp->typename = typeName;
if (state->errf)
dp->errorf = state->errf;
else
dp->errorf = (Exerror_f) errorf;
dp->keyf = keyval;
dp->getf = getval;
dp->reff = refval;
dp->setf = setval;
dp->matchf = matchval;
dp->exitf = state->exitf;
dp->types = a2t;
dp->user = state;
state->dp = dp; /* dp is freed when state is freed */
return dp;
}
/* compile:
* Compile given string, then extract and return
* typed expression.
*/
static Exnode_t *compile(Expr_t * prog, char *src, char *input, int line,
char *lbl, char *sfx, int kind)
{
Exnode_t *e = 0;
Sfio_t *sf;
Sfio_t *prefix;
int rv;
/* create input stream */
if (sfx) {
sf = sfopen(0, sfx, "rs");
if (input) {
prefix = sfopen(0, input, "rs");
sfstack(sf, prefix);
}
} else
sf = sfopen(0, input, "rs");
/* prefixing label if necessary */
if (lbl) {
prefix = sfopen(0, 0, "sr+");
sfprintf(prefix, "%s:\n", lbl);
sfseek(prefix, 0, 0);
sfstack(sf, prefix);
line--;
}
if (!src)
src = "<command line>";
rv = excomp(prog, src, line, 0, sf);
sfclose(sf);
if (rv >= 0 && (getErrorErrors() == 0))
e = exexpr(prog, lbl, NiL, kind);
return e;
}
/* checkGuard:
* Check if guard is an assignment and warn.
*/
static void checkGuard(Exnode_t * gp, char *src, int line)
{
gp = exnoncast(gp);
if (gp && exisAssign(gp)) {
if (src) {
setErrorFileLine (src, line);
}
error(ERROR_WARNING, "assignment used as bool in guard");
}
}
/* mkStmts:
*/
static case_stmt *mkStmts(Expr_t * prog, char *src, case_info * sp,
int cnt, char *lbl, Sfio_t *tmps)
{
case_stmt *cs;
int i;
cs = newof(0, case_stmt, cnt, 0);
for (i = 0; i < cnt; i++) {
if (sp->guard) {
sfprintf(tmps, "%s_g%d", lbl, i);
cs[i].guard = compile(prog, src, sp->guard, sp->gstart,
sfstruse(tmps), 0, INTEGER);
if (getErrorErrors()) break;
checkGuard(cs[i].guard, src, sp->gstart);
}
if (sp->action) {
sfprintf(tmps, "%s_a%d", lbl, i);
cs[i].action = compile(prog, src, sp->action, sp->astart,
sfstruse(tmps), 0, INTEGER);
if (getErrorErrors()) break;
/* If no error but no compiled action, the input action must
* have been essentially an empty block, which should be
* considered different from a missing block. So, compile a
* trivial block.
*/
if (!cs[i].action) {
sfprintf(tmps, "%s__a%d", lbl, i);
cs[i].action = compile(prog, src, "1", sp->astart,
sfstruse(tmps), 0, INTEGER);
}
}
sp = sp->next;
}
return cs;
}
/* mkBlocks:
*/
static int mkBlock(comp_block* bp, Expr_t * prog, char *src, parse_block *inp, Sfio_t* tmps, int i)
{
int rv = 0;
char label[BUFSIZ];
codePhase = 1;
if (inp->begg_stmt) {
sfprintf(tmps, "_begin_g_%d", i);
symbols[0].type = T_graph;
tchk[V_this][1] = Y(G);
bp->begg_stmt = compile(prog, src, inp->begg_stmt,
inp->l_beging, sfstruse(tmps), 0, VOIDTYPE);
if (getErrorErrors())
goto finishBlk;
rv |= BEGG;
}
codePhase = 2;
if (inp->node_stmts) {
symbols[0].type = T_node;
tchk[V_this][1] = Y(V);
bp->n_nstmts = inp->n_nstmts;
sprintf (label, "_nd%d", i);
bp->node_stmts = mkStmts(prog, src, inp->node_stmts,
inp->n_nstmts, label, tmps);
if (getErrorErrors())
goto finishBlk;
bp->walks |= WALKSG;
}
codePhase = 3;
if (inp->edge_stmts) {
symbols[0].type = T_edge;
tchk[V_this][1] = Y(E);
bp->n_estmts = inp->n_estmts;
sprintf (label, "_eg%d", i);
bp->edge_stmts = mkStmts(prog, src, inp->edge_stmts,
inp->n_estmts, label, tmps);
if (getErrorErrors())
goto finishBlk;
bp->walks |= WALKSG;
}
finishBlk:
if (getErrorErrors()) {
free (bp->node_stmts);
free (bp->edge_stmts);
bp->node_stmts = 0;
bp->edge_stmts = 0;
}
return (rv | bp->walks);
}
/* doFlags:
* Convert command line flags to actions in END_G.
*/
static char *doFlags(int flags, Sfio_t * s)
{
sfprintf(s, "\n");
if (flags & SRCOUT)
sfprintf(s, "$O = $G;\n");
if (flags & INDUCE)
sfprintf(s, "induce($O);\n");
return sfstruse(s);
}
/* compileProg:
* Convert gpr sections in libexpr program.
*/
comp_prog *compileProg(parse_prog * inp, Gpr_t * state, int flags)
{
comp_prog *p;
Sfio_t *tmps = state->tmp;
char *endg_sfx = 0;
int i, useflags = 0;
/* Initialize default io */
state->dfltIO = &gprIoDisc;
/* Make sure we have enough bits for types */
assert(BITS_PER_BYTE * sizeof(tctype) >= (1 << TBITS));
p = newof(0, comp_prog, 1, 0);
if (!p) {
error(ERROR_ERROR,
"could not create compiled program: out of memory");
goto finish;
}
if (flags) {
endg_sfx = strdup (doFlags(flags, tmps));
if (*endg_sfx == '\0')
endg_sfx = 0;
}
if (!(initDisc(state)))
goto finish;
exinit();
if (!(p->prog = exopen(state->dp)))
goto finish;
codePhase = 0;
if (inp->begin_stmt) {
p->begin_stmt = compile(p->prog, inp->source, inp->begin_stmt,
inp->l_begin, 0, 0, VOIDTYPE);
if (getErrorErrors())
goto finish;
}
if (inp->blocks) {
comp_block* bp;
parse_block* ibp = inp->blocks;
p->blocks = bp = newof(0, comp_block, inp->n_blocks, 0);
for (i = 0; i < inp->n_blocks; bp++, i++) {
useflags |= mkBlock (bp, p->prog, inp->source, ibp, tmps, i);
if (getErrorErrors())
goto finish;
else {
ibp = ibp->next;
p->n_blocks++;
}
}
}
p->flags = useflags;
codePhase = 4;
if (inp->endg_stmt || endg_sfx) {
symbols[0].type = T_graph;
tchk[V_this][1] = Y(G);
p->endg_stmt = compile(p->prog, inp->source, inp->endg_stmt,
inp->l_endg, "_end_g", endg_sfx, VOIDTYPE);
if (getErrorErrors())
goto finish;
}
codePhase = 5;
if (inp->end_stmt) {
symbols[0].type = T_obj;
p->end_stmt = compile(p->prog, inp->source, inp->end_stmt,
inp->l_end, "_end_", 0, VOIDTYPE);
if (getErrorErrors())
goto finish;
}
setErrorLine (0); /* execution errors have no line numbers */
if (p->end_stmt)
p->flags |= ENDG;
finish:
if (getErrorErrors()) {
freeCompileProg (p);
p = 0;
}
free (endg_sfx);
return p;
}
void
freeCompileProg (comp_prog *p)
{
comp_block* bp;
int i;
if (!p) return;
exclose (p->prog, 1);
for (i = 0; i < p->n_blocks; i++) {
bp = p->blocks + i;
free (bp->node_stmts);
free (bp->edge_stmts);
}
free (p->blocks);
free (p);
}
/* walksGraph;
* Returns true if block actually has node or edge statements.
*/
int walksGraph(comp_block * p)
{
return (p->walks);
}
/* usesGraph;
* Returns true if program uses the graph, i.e., has
* N/E/BEG_G/END_G statments
*/
int usesGraph(comp_prog * p)
{
return (p->flags);
}
void ptchk(void)
{
int i;
for (i = 0; i <= LAST_M; i++)
printf("%d: %d %d\n", i, tchk[i][0], tchk[i][1]);
}
/* readG:
* Read graph from file and initialize
* dynamic data.
*/
Agraph_t *readG(Sfio_t * fp)
{
Agraph_t *g;
#ifdef WIN32
gprDisc.mem = &AgMemDisc;
gprDisc.id = &AgIdDisc;
#endif
g = agread(fp, &gprDisc);
if (g) {
aginit(g, AGRAPH, UDATA, sizeof(gdata), 0);
aginit(g, AGNODE, UDATA, sizeof(ndata), 0);
aginit(g, AGEDGE, UDATA, sizeof(edata), 0);
}
return g;
}
/* openG:
* Open graph and initialize dynamic data.
*/
Agraph_t *openG(char *name, Agdesc_t desc)
{
Agraph_t *g;
#ifdef WIN32
gprDisc.mem = &AgMemDisc;
gprDisc.id = &AgIdDisc;
#endif
g = agopen(name, desc, &gprDisc);
if (g)
agbindrec(g, UDATA, sizeof(gdata), 0);
return g;
}
/* openSubg:
* Open subgraph and initialize dynamic data.
*/
Agraph_t *openSubg(Agraph_t * g, char *name)
{
Agraph_t *sg;
sg = agsubg(g, name, 1);
if (sg && !aggetrec(sg, UDATA, 0))
agbindrec(sg, UDATA, sizeof(gdata), 0);
return sg;
}
/* openNode:
* Create node and initialize dynamic data.
*/
Agnode_t *openNode(Agraph_t * g, char *name)
{
Agnode_t *np;
np = agnode(g, name, 1);
if (np && !aggetrec(np, UDATA, 0))
agbindrec(np, UDATA, sizeof(ndata), 0);
return np;
}
/* openEdge:
* Create edge and initialize dynamic data.
*/
Agedge_t *openEdge(Agraph_t* g, Agnode_t * t, Agnode_t * h, char *key)
{
Agedge_t *ep;
Agraph_t *root;
root = sameG(t, h, "openEdge", "tail and head nodes");
if (!root)
return 0;
if (g) {
if (!sameG(g, root, "openEdge", "subgraph and nodes"))
return 0;
} else
g = root;
ep = agedge(g, t, h, key, 1);
if (ep && !aggetrec(ep, UDATA, 0))
agbindrec(ep, UDATA, sizeof(edata), 0);
return ep;
}
| 29,115 |
14,668 | <filename>tools/cr/cr/commands/gn.py<gh_stars>1000+
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module for the gn command."""
import os
import cr
class GnCommand(cr.Command):
"""The implementation of the gn command.
The gn command is meant for running the gn tool without having to manually
specify an out directory.
"""
def __init__(self):
super(GnCommand, self).__init__()
self.help = 'Run gn with the currently selected out directory'
self.description = ("""
Runs the gn command with the currently selected out directory as the
second argument.
""")
def AddArguments(self, subparsers):
parser = super(GnCommand, self).AddArguments(subparsers)
self.ConsumeArgs(parser, 'gn')
return parser
def Run(self):
out_path = os.path.join(cr.context['CR_SRC'],
cr.context['CR_OUT_FULL'])
args = cr.context.remains
if args:
cr.Host.Execute('gn', args[0], out_path, *args[1:])
else:
cr.Host.Execute('gn')
| 420 |
1,073 | <gh_stars>1000+
// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.unix.Chroot -analyzer-store region -verify %s
extern int chroot(const char* path);
extern int chdir(const char* path);
void foo(void) {
}
void f1(void) {
chroot("/usr/local"); // root changed.
foo(); // expected-warning {{No call of chdir("/") immediately after chroot}}
}
void f2(void) {
chroot("/usr/local"); // root changed.
chdir("/"); // enter the jail.
foo(); // no-warning
}
void f3(void) {
chroot("/usr/local"); // root changed.
chdir("../"); // change working directory, still out of jail.
foo(); // expected-warning {{No call of chdir("/") immediately after chroot}}
}
| 237 |
6,989 | <filename>lib/python2.7/site-packages/scipy/_lib/_testutils.py
"""
Generic test utilities and decorators.
"""
from __future__ import division, print_function, absolute_import
import os
import sys
from numpy.testing import dec
from nose import SkipTest
from scipy._lib.decorator import decorator
__all__ = ['knownfailure_overridable', 'suppressed_stdout', 'xslow']
def knownfailure_overridable(msg=None):
if not msg:
msg = "Undiagnosed issues (corner cases, wrong comparison values, or otherwise)"
msg = msg + " [Set environment variable SCIPY_XFAIL=1 to run this test nevertheless.]"
def deco(func):
try:
if bool(os.environ['SCIPY_XFAIL']):
return func
except (ValueError, KeyError):
pass
return dec.knownfailureif(True, msg)(func)
return deco
def suppressed_stdout(f):
import nose
def pwrapper(*arg, **kwargs):
oldstdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
try:
return f(*arg, **kwargs)
finally:
sys.stdout.close()
sys.stdout = oldstdout
return nose.tools.make_decorator(f)(pwrapper)
@decorator
def xslow(func, *a, **kw):
try:
v = int(os.environ.get('SCIPY_XSLOW', '0'))
if not v:
raise ValueError()
except ValueError:
raise SkipTest("very slow test; set environment variable "
"SCIPY_XSLOW=1 to run it")
return func(*a, **kw)
| 652 |
1,473 | <filename>Core/src/org/sleuthkit/autopsy/ingest/IngestOptionsPanel.java<gh_stars>1000+
/*
* Autopsy Forensic Browser
*
* Copyright 2011-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.ingest;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.corecomponents.OptionsPanel;
import org.sleuthkit.autopsy.modules.interestingitems.FilesSetDefsPanel;
import org.sleuthkit.autopsy.modules.interestingitems.FilesSetDefsPanel.PANEL_TYPE;
/**
* Global options panel for keyword searching.
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
public class IngestOptionsPanel extends IngestModuleGlobalSettingsPanel implements OptionsPanel {
@NbBundle.Messages({"IngestOptionsPanel.settingsTab.text=Settings",
"IngestOptionsPanel.settingsTab.toolTipText=Settings regarding resources available to ingest.",
"IngestOptionsPanel.fileFiltersTab.text=File Filters",
"IngestOptionsPanel.fileFiltersTab.toolTipText=Settings for creating and editing ingest file filters.",
"IngestOptionsPanel.profilesTab.text=Profiles",
"IngestOptionsPanel.profilesTab.toolTipText=Settings for creating and editing profiles."})
private FilesSetDefsPanel filterPanel;
private final static int INDEX_OF_FILTER_PANEL = 0;
private IngestSettingsPanel settingsPanel;
private final static int INDEX_OF_SETTINGS_PANEL = 2;
private ProfileSettingsPanel profilePanel;
private final static int INDEX_OF_PROFILE_PANEL = 1;
private int indexOfPreviousTab;
/**
* This panel implements a property change listener that listens to ingest
* job events so it can disable the buttons on the panel if ingest is
* running. This is done to prevent changes to user-defined types while the
* type definitions are in use.
*/
IngestJobEventPropertyChangeListener ingestJobEventsListener;
public IngestOptionsPanel() {
initComponents();
customizeComponents();
indexOfPreviousTab = tabbedPane.getSelectedIndex();
}
private void customizeComponents() {
filterPanel = new FilesSetDefsPanel(PANEL_TYPE.FILE_INGEST_FILTERS);
settingsPanel = new IngestSettingsPanel();
profilePanel = new ProfileSettingsPanel();
tabbedPane.insertTab(NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.fileFiltersTab.text"), null,
filterPanel, NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.fileFiltersTab.toolTipText"), INDEX_OF_FILTER_PANEL);
tabbedPane.insertTab(NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.profilesTab.text"), null,
profilePanel, NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.profilesTab.toolTipText"), INDEX_OF_PROFILE_PANEL);
tabbedPane.insertTab(NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.settingsTab.text"), null,
settingsPanel, NbBundle.getMessage(IngestOptionsPanel.class, "IngestOptionsPanel.settingsTab.toolTipText"), INDEX_OF_SETTINGS_PANEL);
//Listener for when tabbed panes are switched, because we can have two file filter definitions panels open at the same time
//we may wind up in a situation where the user has created and saved one in the profiles panel
//so we need to refresh the filterPanel in those cases before proceeding.
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
//If we are switching to a filter panel we should load
//load the filter panel to ensure it is up to date
//incase a filter was addded through the Profile->new->create new filter manner
if (tabbedPane.getSelectedIndex() == INDEX_OF_FILTER_PANEL && tabbedPane.getSelectedIndex() != indexOfPreviousTab) {
filterPanel.load();
}
//save the contents of whichever Tab we just switched from
saveTabByIndex(indexOfPreviousTab);
//save the index of the current tab for the next time we switch
indexOfPreviousTab = tabbedPane.getSelectedIndex();
}
}
});
addIngestJobEventsListener();
enableTabs();
}
/**
* Add a property change listener that listens to ingest job events to
* disable the buttons on the panel if ingest is running. This is done to
* prevent changes to user-defined types while the type definitions are in
* use.
*/
private void addIngestJobEventsListener() {
ingestJobEventsListener = new IngestJobEventPropertyChangeListener();
IngestManager.getInstance().addIngestJobEventListener(ingestJobEventsListener);
}
/**
* A property change listener that listens to ingest job events.
*/
private class IngestJobEventPropertyChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
enableTabs();
}
});
}
}
/**
* Disables tabs and options inside of tabs during Ingest, and re-enables
* them after Ingest is complete or cancelled.
*/
private void enableTabs() {
boolean ingestIsRunning = IngestManager.getInstance().isIngestRunning();
tabbedPane.setEnabled(!ingestIsRunning);
settingsPanel.enableButtons(!ingestIsRunning);
profilePanel.enableButtons(!ingestIsRunning);
filterPanel.enableButtons();
}
@Override
public void addPropertyChangeListener(PropertyChangeListener l) {
super.addPropertyChangeListener(l);
/*
* There is at least one look and feel library that follows the bad
* practice of calling overrideable methods in a constructor, e.g.:
*
* at
* javax.swing.plaf.synth.SynthPanelUI.installListeners(SynthPanelUI.java:83)
* at
* javax.swing.plaf.synth.SynthPanelUI.installUI(SynthPanelUI.java:63)
* at javax.swing.JComponent.setUI(JComponent.java:666) at
* javax.swing.JPanel.setUI(JPanel.java:153) at
* javax.swing.JPanel.updateUI(JPanel.java:126) at
* javax.swing.JPanel.<init>(JPanel.java:86) at
* javax.swing.JPanel.<init>(JPanel.java:109) at
* javax.swing.JPanel.<init>(JPanel.java:117)
*
* When this happens, the following child components of this JPanel
* subclass have not been constructed yet, since this panel's
* constructor has not been called yet.
*/
if (null != filterPanel) {
filterPanel.addPropertyChangeListener(l);
}
if (null != settingsPanel) {
settingsPanel.addPropertyChangeListener(l);
}
if (null != profilePanel) {
profilePanel.addPropertyChangeListener(l);
}
}
@Override
public void removePropertyChangeListener(PropertyChangeListener l) {
filterPanel.removePropertyChangeListener(l);
settingsPanel.removePropertyChangeListener(l);
profilePanel.removePropertyChangeListener(l);
}
@Override
public void saveSettings() {
saveTabByIndex(tabbedPane.getSelectedIndex());
}
/**
* Save the panel which is in the tab corresponding to the specified index.
*
* @param index - the index of the tab you wish to save the contents of
*/
private void saveTabByIndex(int index) {
//Because we can create filters in two seperate windows here we need
//to be careful not to save an out of date list over the current list
switch (index) {
case (INDEX_OF_FILTER_PANEL):
filterPanel.saveSettings();
break;
case (INDEX_OF_PROFILE_PANEL):
profilePanel.saveSettings();
break;
case (INDEX_OF_SETTINGS_PANEL):
settingsPanel.saveSettings();
break;
default:
//don't save anything if it wasn't a tab index that should exist
}
}
@Override
public void store() {
saveSettings();
}
@Override
public void load() {
filterPanel.load();
settingsPanel.load();
profilePanel.load();
}
boolean valid() {
return true;
}
/**
* Method called when the cancel button is clicked.
*/
void cancel() {
//doesn't need to do anything
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration//GEN-END:variables
}
| 4,248 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/web_applications/projector_system_web_app_info.h"
#include "ash/constants/ash_features.h"
#include "ash/grit/ash_projector_app_trusted_resources.h"
#include "ash/webui/projector_app/public/cpp/projector_app_constants.h"
#include "chrome/browser/ash/web_applications/system_web_app_install_utils.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/grit/generated_resources.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
ProjectorSystemWebAppDelegate::ProjectorSystemWebAppDelegate(Profile* profile)
: web_app::SystemWebAppDelegate(web_app::SystemAppType::PROJECTOR,
"Projector",
GURL(ash::kChromeUITrustedProjectorAppUrl),
profile) {}
ProjectorSystemWebAppDelegate::~ProjectorSystemWebAppDelegate() = default;
std::unique_ptr<WebApplicationInfo>
ProjectorSystemWebAppDelegate::GetWebAppInfo() const {
auto info = std::make_unique<WebApplicationInfo>();
info->start_url = GURL(ash::kChromeUITrustedProjectorAppUrl);
info->scope = GURL(ash::kChromeUITrustedProjectorAppUrl);
info->title = l10n_util::GetStringUTF16(IDS_PROJECTOR_APP_NAME);
// TODO(b/195127670): Add 48, 128, and 192 size icons through
// CreateIconInfoForSystemWebApp().
// TODO(b/195127670): Figure out the theme color.
info->theme_color = SK_ColorBLACK;
info->display_mode = blink::mojom::DisplayMode::kStandalone;
info->user_display_mode = blink::mojom::DisplayMode::kStandalone;
// TODO(b/195127670): Add info.url_handlers for https://projector.apps.chrome
// domain. Requires web-app-origin-association file at the new domain to prove
// cross-ownership. See
// https://web.dev/pwa-url-handler/#the-web-app-origin-association-file.
return info;
}
bool ProjectorSystemWebAppDelegate::ShouldCaptureNavigations() const {
return true;
}
bool ProjectorSystemWebAppDelegate::IsAppEnabled() const {
if (!profile_->GetProfilePolicyConnector()->IsManaged() ||
profile_->IsChild()) {
return ash::features::IsProjectorAllUserEnabled();
}
// TODO(b/209675088): Check Projector admin policy.
return ash::features::IsProjectorEnabled() ||
ash::features::IsProjectorManagedUserEnabled();
}
| 918 |
673 | /*
* Copyright (C) 2018 xuexiangjys(<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xuexiang.xaop.util;
import android.view.View;
import com.xuexiang.xaop.annotation.SingleClick;
/**
* <pre>
* desc : 快速点击工具类
* author : xuexiang
* time : 2018/4/22 下午6:47
* </pre>
*/
public final class ClickUtils {
/**
* 最近一次点击的时间
*/
private static long sLastClickTime;
/**
* 最近一次点击的控件ID
*/
private static int sLastClickViewId;
/**
* Don't let anyone instantiate this class.
*/
private ClickUtils() {
throw new UnsupportedOperationException("Do not need instantiate!");
}
/**
* 是否是快速点击
*
* @param v 点击的控件
* @return true:是,false:不是
*/
public static boolean isFastDoubleClick(View v) {
return isFastDoubleClick(v, SingleClick.DEFAULT_INTERVAL_MILLIS);
}
/**
* 是否是快速点击
*
* @param v 点击的控件
* @param intervalMillis 时间间期(毫秒)
* @return true:是,false:不是
*/
public static boolean isFastDoubleClick(View v, long intervalMillis) {
long time = System.currentTimeMillis();
int viewId = v.getId();
long timeD = time - sLastClickTime;
if (0 < timeD && timeD < intervalMillis && viewId == sLastClickViewId) {
return true;
} else {
sLastClickTime = time;
sLastClickViewId = viewId;
return false;
}
}
}
| 905 |
592 | {
"layers": {
"VIIRS_SNPP_DayNightBand_At_Sensor_Radiance": {
"id": "VIIRS_SNPP_DayNightBand_At_Sensor_Radiance",
"title": "Black Marble Nighttime At Sensor Radiance (Day/Night Band)",
"subtitle": "Suomi NPP / VIIRS",
"description": "viirs/VIIRS_SNPP_DayNightBand_At_Sensor_Radiance",
"tags": "dnb night s-npp snpp lights city urban nighttime black marble vnp46a1",
"layergroup": "Earth at Night",
"group": "overlays",
"tracks": [
"OrbitTracks_Suomi_NPP_Descending"
],
"daynight": [
"night"
]
}
}
} | 270 |
1,829 | <filename>spring-boot-2.0-samples/production-ready-sample/src/main/java/thinking/in/spring/boot/samples/production/ready/actuator/management/CustomizedManagementContextConfiguration.java
package thinking.in.spring.boot.samples.production.ready.actuator.management;
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
/**
* 自定义 {@link @ManagementContextConfiguration ManagementContextConfiguration} 配置类
*
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @see ManagementContextConfiguration
* @since 1.0.0
*/
@ManagementContextConfiguration
public class CustomizedManagementContextConfiguration {
@EventListener(ContextRefreshedEvent.class)
public void onContextRefreshed(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
ApplicationContext parentContext = context.getParent();
System.out.printf("当前管理端应用上下文 ID:%s,其双亲应用上下文 ID:%s\n",
context.getId(),
parentContext == null ? null : parentContext.getId()
);
}
}
| 436 |
703 |
#pragma once
#include <RendererFoundation/Resources/UnorderedAccesView.h>
struct ID3D11UnorderedAccessView;
class ezGALUnorderedAccessViewVulkan : public ezGALUnorderedAccessView
{
public:
EZ_ALWAYS_INLINE ID3D11UnorderedAccessView* GetDXResourceView() const;
protected:
friend class ezGALDeviceVulkan;
friend class ezMemoryUtils;
ezGALUnorderedAccessViewVulkan(ezGALResourceBase* pResource, const ezGALUnorderedAccessViewCreationDescription& Description);
~ezGALUnorderedAccessViewVulkan();
virtual ezResult InitPlatform(ezGALDevice* pDevice) override;
virtual ezResult DeInitPlatform(ezGALDevice* pDevice) override;
ID3D11UnorderedAccessView* m_pDXUnorderedAccessView;
};
#include <RendererVulkan/Resources/Implementation/UnorderedAccessViewVulkan_inl.h>
| 259 |
777 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include "base/macros.h"
#include "chrome/browser/media_galleries/chromeos/mtp_device_object_enumerator.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
struct MtpFileEntryData {
const char* const name;
int64_t size;
bool is_directory;
time_t modification_time;
};
const MtpFileEntryData kTestCases[] = {
{ "Foo", 123, false, 321 },
{ "Bar", 234, true, 432 },
{ "Baaz", 345, false, 543 },
};
void TestEnumeratorIsEmpty(MTPDeviceObjectEnumerator* enumerator) {
EXPECT_EQ(0, enumerator->Size());
EXPECT_FALSE(enumerator->IsDirectory());
EXPECT_TRUE(enumerator->LastModifiedTime().is_null());
}
void TestNextEntryIsEmpty(MTPDeviceObjectEnumerator* enumerator) {
EXPECT_TRUE(enumerator->Next().empty());
}
typedef testing::Test MTPDeviceObjectEnumeratorTest;
TEST_F(MTPDeviceObjectEnumeratorTest, Empty) {
std::vector<MtpFileEntry> entries;
MTPDeviceObjectEnumerator enumerator(entries);
TestEnumeratorIsEmpty(&enumerator);
TestNextEntryIsEmpty(&enumerator);
TestNextEntryIsEmpty(&enumerator);
TestEnumeratorIsEmpty(&enumerator);
}
TEST_F(MTPDeviceObjectEnumeratorTest, Traversal) {
std::vector<MtpFileEntry> entries;
for (size_t i = 0; i < arraysize(kTestCases); ++i) {
MtpFileEntry entry;
entry.set_file_name(kTestCases[i].name);
entry.set_file_size(kTestCases[i].size);
entry.set_file_type(kTestCases[i].is_directory ?
MtpFileEntry::FILE_TYPE_FOLDER :
MtpFileEntry::FILE_TYPE_OTHER);
entry.set_modification_time(kTestCases[i].modification_time);
entries.push_back(entry);
}
MTPDeviceObjectEnumerator enumerator(entries);
TestEnumeratorIsEmpty(&enumerator);
TestEnumeratorIsEmpty(&enumerator);
for (size_t i = 0; i < arraysize(kTestCases); ++i) {
EXPECT_EQ(kTestCases[i].name, enumerator.Next().value());
EXPECT_EQ(kTestCases[i].size, enumerator.Size());
EXPECT_EQ(kTestCases[i].is_directory, enumerator.IsDirectory());
EXPECT_EQ(kTestCases[i].modification_time,
enumerator.LastModifiedTime().ToTimeT());
}
TestNextEntryIsEmpty(&enumerator);
TestNextEntryIsEmpty(&enumerator);
TestEnumeratorIsEmpty(&enumerator);
TestNextEntryIsEmpty(&enumerator);
TestEnumeratorIsEmpty(&enumerator);
}
} // namespace
| 943 |
764 | <gh_stars>100-1000
{"symbol": "GZR","address": "0xE638dc39b6aDBEE8526b5C22380b4b45dAf46d8e","overview":{"en": ""},"email": "<EMAIL>","website": "https://tokensale.gizer.io/","state": "NORMAL","links": {"blog": "https://medium.com/@Gizer_Gaming/","twitter": "https://twitter.com/Gizer_Gaming","telegram": "https://t.me/gizergaming","github": "https://github.com/GizerInc"}} | 150 |
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/password_feature_manager_impl.h"
#include "base/test/scoped_feature_list.h"
#include "components/password_manager/core/browser/password_form.h"
#include "components/password_manager/core/browser/password_manager_client.h"
#include "components/password_manager/core/browser/password_manager_util.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/driver/test_sync_service.h"
#include "testing/gtest/include/gtest/gtest.h"
class PasswordFeatureManagerImplTest : public ::testing::Test {
public:
PasswordFeatureManagerImplTest()
: password_feature_manager_(&pref_service_, &sync_service_) {
pref_service_.registry()->RegisterDictionaryPref(
password_manager::prefs::kAccountStoragePerAccountSettings);
account_.email = "<EMAIL>";
account_.gaia = "account";
account_.account_id = CoreAccountId::FromGaiaId(account_.gaia);
}
~PasswordFeatureManagerImplTest() override = default;
protected:
TestingPrefServiceSimple pref_service_;
syncer::TestSyncService sync_service_;
password_manager::PasswordFeatureManagerImpl password_feature_manager_;
CoreAccountInfo account_;
};
TEST_F(PasswordFeatureManagerImplTest, GenerationEnabledIfUserIsOptedIn) {
base::test::ScopedFeatureList features;
features.InitAndEnableFeature(
password_manager::features::kEnablePasswordsAccountStorage);
sync_service_.SetAuthenticatedAccountInfo(account_);
sync_service_.SetIsAuthenticatedAccountPrimary(false);
sync_service_.SetDisableReasons({});
sync_service_.SetTransportState(syncer::SyncService::TransportState::ACTIVE);
password_feature_manager_.OptInToAccountStorage();
ASSERT_EQ(
password_manager_util::GetPasswordSyncState(&sync_service_),
password_manager::SyncState::kAccountPasswordsActiveNormalEncryption);
EXPECT_TRUE(password_feature_manager_.IsGenerationEnabled());
}
TEST_F(PasswordFeatureManagerImplTest,
GenerationEnabledIfUserEligibleForAccountStorageOptIn) {
base::test::ScopedFeatureList features;
features.InitAndEnableFeature(
password_manager::features::kEnablePasswordsAccountStorage);
sync_service_.SetAuthenticatedAccountInfo(account_);
sync_service_.SetIsAuthenticatedAccountPrimary(false);
sync_service_.SetDisableReasons({});
sync_service_.SetTransportState(syncer::SyncService::TransportState::ACTIVE);
sync_service_.SetActiveDataTypes({});
ASSERT_EQ(password_manager_util::GetPasswordSyncState(&sync_service_),
password_manager::SyncState::kNotSyncing);
// The user must be eligible for account storage opt in now.
ASSERT_TRUE(password_feature_manager_.ShouldShowAccountStorageOptIn());
EXPECT_TRUE(password_feature_manager_.IsGenerationEnabled());
}
TEST_F(PasswordFeatureManagerImplTest,
GenerationDisabledIfUserNotEligibleForAccountStorageOptIn) {
// Setup one example of user not eligible for opt in: signed in but with
// feature flag disabled.
base::test::ScopedFeatureList features;
features.InitAndDisableFeature(
password_manager::features::kEnablePasswordsAccountStorage);
sync_service_.SetAuthenticatedAccountInfo(account_);
sync_service_.SetIsAuthenticatedAccountPrimary(false);
sync_service_.SetDisableReasons({});
sync_service_.SetTransportState(syncer::SyncService::TransportState::ACTIVE);
sync_service_.SetActiveDataTypes({});
ASSERT_EQ(password_manager_util::GetPasswordSyncState(&sync_service_),
password_manager::SyncState::kNotSyncing);
// The user must not be eligible for account storage opt in now.
ASSERT_FALSE(password_feature_manager_.ShouldShowAccountStorageOptIn());
EXPECT_FALSE(password_feature_manager_.IsGenerationEnabled());
}
| 1,286 |
347 | package org.ovirt.engine.core.common.vdscommands.gluster;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeOptionEntity;
import org.ovirt.engine.core.compat.Guid;
/**
* VDS parameters class with volume name, volume option and force as parameters,
* apart from volume name inherited from {@link GlusterVolumeVDSParameters}.
* Used by the "Reset gluster volume option" command.
*/
public class ResetGlusterVolumeOptionsVDSParameters extends GlusterVolumeVDSParameters {
private GlusterVolumeOptionEntity volumeOption;
private boolean forceAction;
public ResetGlusterVolumeOptionsVDSParameters(Guid serverId, String volumeName, GlusterVolumeOptionEntity volumeOption, boolean forceAction) {
super(serverId, volumeName);
this.volumeOption = volumeOption;
this.forceAction = forceAction;
}
public ResetGlusterVolumeOptionsVDSParameters() {
}
public GlusterVolumeOptionEntity getVolumeOption() {
return volumeOption;
}
public boolean isforceAction() {
return forceAction;
}
}
| 339 |
689 | <reponame>Takaaki-Inaba/ucx
/**
* Copyright (C) Mellanox Technologies Ltd. 2019. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCS_X86_64_GLOBAL_OPTS_H_
#define UCS_X86_64_GLOBAL_OPTS_H_
#include <stddef.h>
#include <ucs/sys/compiler_def.h>
BEGIN_C_DECLS
#define UCS_ARCH_GLOBAL_OPTS_INITALIZER { \
.builtin_memcpy_min = UCS_MEMUNITS_AUTO, \
.builtin_memcpy_max = UCS_MEMUNITS_AUTO \
}
/* built-in memcpy config */
typedef struct ucs_arch_global_opts {
size_t builtin_memcpy_min;
size_t builtin_memcpy_max;
} ucs_arch_global_opts_t;
END_C_DECLS
#endif
| 290 |
3,897 | /*
* Copyright 2018-2020 Cypress Semiconductor Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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 <cstring>
#include <algorithm>
#include <vector>
#include "SclSTAInterface.h"
#include "nsapi.h"
#include "lwipopts.h"
#include "lwip/etharp.h"
#include "lwip/ethip6.h"
#include "rtos.h"
#include "scl_emac.h"
#include "scl_ipc.h"
#include "mbed_wait_api.h"
#include "SclAccessPoint.h"
#include "scl_buffer_api.h"
/** @file
* Provides SCL interface functions to be used with WiFiInterface or NetworkInterface Objects
*/
#define MIN_SSID_LENGTH (0)
#define MIN_PASSWORD_LENGTH (0)
struct scl_tx_net_credentials {
nsapi_security_t network_security_type;
int ssid_len;
int pass_len;
const char *network_ssid;
const char *network_passphrase;
} scl_tx_network_credentials;
struct scl_scan_userdata {
rtos::Semaphore *sema;
scan_result_type sres_type;
WiFiAccessPoint *aps;
std::vector<scl_scan_result_t> *result_buff;
unsigned count;
unsigned offset;
bool scan_in_progress;
};
static scl_scan_userdata interal_scan_data;
static scl_scan_result_t internal_scan_result;
network_params_t network_parameter;
/* Internal scan callback that handles the scan results */
void scl_scan_handler(scl_scan_result_t *result_ptr,void *user_data, scl_scan_status_t status);
#define CMP_MAC( a, b ) (((((unsigned char*)a)[0])==(((unsigned char*)b)[0]))&& \
((((unsigned char*)a)[1])==(((unsigned char*)b)[1]))&& \
((((unsigned char*)a)[2])==(((unsigned char*)b)[2]))&& \
((((unsigned char*)a)[3])==(((unsigned char*)b)[3]))&& \
((((unsigned char*)a)[4])==(((unsigned char*)b)[4]))&& \
((((unsigned char*)a)[5])==(((unsigned char*)b)[5])))
int scl_toerror(scl_result_t res)
{
switch (res) {
case SCL_SUCCESS:
return NSAPI_ERROR_OK;
case SCL_UNSUPPORTED:
return NSAPI_ERROR_UNSUPPORTED;
case SCL_BADARG:
return NSAPI_ERROR_PARAMETER;
case SCL_INVALID_JOIN_STATUS:
return NSAPI_ERROR_NO_CONNECTION;
case SCL_BUFFER_UNAVAILABLE_PERMANENT:
case SCL_BUFFER_UNAVAILABLE_TEMPORARY:
case SCL_RX_BUFFER_ALLOC_FAIL:
case SCL_BUFFER_ALLOC_FAIL:
case SCL_MALLOC_FAILURE:
return NSAPI_ERROR_NO_MEMORY;
case SCL_ACCESS_POINT_NOT_FOUND:
case SCL_NETWORK_NOT_FOUND:
return NSAPI_ERROR_NO_SSID;
case SCL_NOT_AUTHENTICATED:
case SCL_INVALID_KEY:
case SCL_NOT_KEYED:
return NSAPI_ERROR_AUTH_FAILURE;
case SCL_PENDING:
case SCL_JOIN_IN_PROGRESS:
return NSAPI_ERROR_IN_PROGRESS;
case SCL_CONNECTION_LOST:
return NSAPI_ERROR_CONNECTION_LOST;
case SCL_TIMEOUT:
case SCL_EAPOL_KEY_PACKET_M1_TIMEOUT:
case SCL_EAPOL_KEY_PACKET_M3_TIMEOUT:
case SCL_EAPOL_KEY_PACKET_G1_TIMEOUT:
return NSAPI_ERROR_CONNECTION_TIMEOUT;
default:
return -res;
}
}
nsapi_security_t scl_tosecurity(scl_security_t sec)
{
switch (sec) {
case SCL_SECURITY_OPEN:
return NSAPI_SECURITY_NONE;
case SCL_SECURITY_WEP_PSK:
case SCL_SECURITY_WEP_SHARED:
return NSAPI_SECURITY_WEP;
case SCL_SECURITY_WPA_TKIP_PSK:
case SCL_SECURITY_WPA_AES_PSK:
case SCL_SECURITY_WPA_TKIP_ENT:
case SCL_SECURITY_WPA_AES_ENT:
case SCL_SECURITY_WPA_MIXED_ENT:
return NSAPI_SECURITY_WPA;
case SCL_SECURITY_WPA2_MIXED_PSK:
case SCL_SECURITY_WPA2_WPA_PSK:
case SCL_SECURITY_WPA2_WPA_TKIP_PSK:
return NSAPI_SECURITY_WPA_WPA2;
case SCL_SECURITY_WPA2_MIXED_ENT:
return NSAPI_SECURITY_WPA2_ENT;
case SCL_SECURITY_WPA2_AES_PSK:
case SCL_SECURITY_WPA2_AES_ENT:
case SCL_SECURITY_WPA2_FBT_PSK:
case SCL_SECURITY_WPA2_FBT_ENT:
case SCL_SECURITY_WPA2_TKIP_ENT:
return NSAPI_SECURITY_WPA2;
default:
return NSAPI_SECURITY_UNKNOWN;
}
}
scl_security_t scl_fromsecurity(nsapi_security_t sec)
{
switch (sec) {
case NSAPI_SECURITY_NONE:
return SCL_SECURITY_OPEN;
case NSAPI_SECURITY_WEP:
return SCL_SECURITY_WEP_PSK;
case NSAPI_SECURITY_WPA:
return SCL_SECURITY_WPA_MIXED_PSK;
case NSAPI_SECURITY_WPA2:
return SCL_SECURITY_WPA2_AES_PSK;
case NSAPI_SECURITY_WPA_WPA2:
return SCL_SECURITY_WPA2_MIXED_PSK;
default:
return SCL_SECURITY_UNKNOWN;
}
}
SclSTAInterface::SclSTAInterface(SCL_EMAC &emac, OnboardNetworkStack &stack, scl_interface_shared_info_t &shared)
: EMACInterface(emac, stack),
_ssid("\0"),
_pass("\0"),
_security(NSAPI_SECURITY_NONE),
_scl_emac(emac),
_iface_shared(shared)
{
}
nsapi_error_t SclSTAInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel)
{
int err = set_channel(channel);
if (err) {
return err;
}
err = set_credentials(ssid, pass, security);
if (err) {
return err;
}
return connect();
}
nsapi_error_t SclSTAInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security)
{
if ((ssid == NULL) ||
(strlen(ssid) == 0) ||
(pass == NULL && (security != NSAPI_SECURITY_NONE)) ||
(strlen(pass) == 0 && (security != NSAPI_SECURITY_NONE)) ||
(strlen(pass) > 63 && (security == NSAPI_SECURITY_WPA2 || security == NSAPI_SECURITY_WPA || security == NSAPI_SECURITY_WPA_WPA2))
) {
return NSAPI_ERROR_PARAMETER;
}
memset(_ssid, 0, sizeof(_ssid));
strncpy(_ssid, ssid, sizeof(_ssid));
memset(_pass, 0, sizeof(_pass));
strncpy(_pass, pass, sizeof(_pass));
_security = security;
return NSAPI_ERROR_OK;
}
nsapi_error_t SclSTAInterface::connect()
{
uint32_t delay_timeout = 0;
scl_result_t ret_val;
nsapi_error_t interface_status;
uint32_t connection_status = 0;
scl_tx_network_credentials.network_ssid = _ssid;
if ((strlen(_ssid) < MAX_SSID_LENGTH) && (strlen(_ssid) > MIN_SSID_LENGTH) ) {
scl_tx_network_credentials.ssid_len = strlen(_ssid);
} else {
return NSAPI_ERROR_PARAMETER;
}
scl_tx_network_credentials.network_passphrase = _pass;
if (((strlen(_pass) < MAX_PASSWORD_LENGTH) && (strlen(_pass) > MIN_PASSWORD_LENGTH)) || (_security == NSAPI_SECURITY_NONE)) {
scl_tx_network_credentials.pass_len = strlen(_pass);
} else {
return NSAPI_ERROR_PARAMETER;
}
scl_tx_network_credentials.network_security_type = _security;
ret_val = scl_send_data(SCL_TX_CONNECT, (char *)&scl_tx_network_credentials, TIMER_DEFAULT_VALUE);
if (ret_val == SCL_SUCCESS) {
SCL_LOG(("wifi provisioning in progress\r\n"));
}
network_parameter.connection_status = NSAPI_STATUS_DISCONNECTED;
//Get the network parameter from NP
while ((network_parameter.connection_status != NSAPI_STATUS_GLOBAL_UP) && delay_timeout < NW_CONNECT_TIMEOUT) {
ret_val = scl_get_nw_parameters(&network_parameter);
wait_us(NW_DELAY_TIME_US);
delay_timeout++;
}
if (delay_timeout >= NW_CONNECT_TIMEOUT || ret_val != SCL_SUCCESS) {
return NSAPI_ERROR_NO_CONNECTION;
}
if (!_scl_emac.powered_up) {
_scl_emac.power_up();
}
if (!_interface) {
nsapi_error_t err = _stack.add_ethernet_interface(_emac, true, &_interface);
if (err != NSAPI_ERROR_OK) {
_interface = NULL;
return err;
}
_interface->attach(_connection_status_cb);
}
if (!scl_wifi_is_ready_to_transceive()) {
scl_emac_wifi_link_state_changed(true);
}
interface_status = _interface->bringup(false,
network_parameter.ip_address,
network_parameter.netmask,
network_parameter.gateway,
DEFAULT_STACK);
if (interface_status == NSAPI_ERROR_OK) {
scl_send_data(SCL_TX_CONNECTION_STATUS, (char *)&connection_status, TIMER_DEFAULT_VALUE);
}
return interface_status;
}
void SclSTAInterface::wifi_on()
{
if (!_scl_emac.powered_up) {
_scl_emac.power_up();
}
}
nsapi_error_t SclSTAInterface::disconnect()
{
scl_result_t ret_val;
nsapi_error_t disconnect_status;
uint32_t delay_timeout = 0;
ret_val = scl_send_data(SCL_TX_DISCONNECT, (char *)&disconnect_status, TIMER_DEFAULT_VALUE);
if (ret_val == SCL_ERROR) {
return NSAPI_ERROR_TIMEOUT;
}
if (!_interface) {
return NSAPI_ERROR_NO_CONNECTION;
}
// block till disconnected from network
while ((network_parameter.connection_status != NSAPI_STATUS_DISCONNECTED) && delay_timeout < NW_DISCONNECT_TIMEOUT) {
ret_val = scl_get_nw_parameters(&network_parameter);
wait_us(NW_DELAY_TIME_US);
delay_timeout++;
}
if (delay_timeout >= NW_DISCONNECT_TIMEOUT) {
return NSAPI_ERROR_TIMEOUT;
}
// bring down
int err = _interface->bringdown();
if (err) {
return err;
}
scl_emac_wifi_link_state_changed(false);
return NSAPI_ERROR_OK;
}
void scl_scan_handler(scl_scan_result_t *result_ptr,
void *user_data, scl_scan_status_t status)
{
scl_scan_userdata *data = (scl_scan_userdata *)&interal_scan_data;
scl_scan_result_t *record = result_ptr;
unsigned int i;
nsapi_wifi_ap ap;
uint8_t length;
/* Even after stopping scan, some results will still come as results are already present in the queue */
if (data->scan_in_progress == false) {
return;
}
// finished scan, either succesfully or through an abort
if (status != SCL_SCAN_INCOMPLETE) {
data->scan_in_progress = false;
data->sema->release();
return;
}
// can't really keep anymore scan results
if (data->count > 0 && data->offset >= data->count) {
/* We can not abort the scan as this function is getting executed in SCL context,
Note that to call any SCL API, caller function should not in SCL context */
return;
}
for (i = 0; i < data->result_buff->size(); i++) {
if (memcmp(((*data->result_buff)[i].BSSID.octet),(record->BSSID.octet),sizeof(scl_mac_t)) == 0) {
return;
}
}
if (data->count > 0 && (data->aps != NULL)) {
// get ap stats
length = record->SSID.length;
if (length < (sizeof(ap.ssid) - 1)) {
length = sizeof(ap.ssid) - 1;
}
memcpy(ap.ssid, record->SSID.value, length);
ap.ssid[length] = '\0';
memcpy(ap.bssid, record->BSSID.octet, sizeof(ap.bssid));
ap.security = scl_tosecurity(record->security);
ap.rssi = record->signal_strength;
ap.channel = record->channel;
if (data->sres_type == SRES_TYPE_WIFI_ACCESS_POINT) {
data->aps[data->offset] = WiFiAccessPoint(ap);
} else if (data->sres_type == SRES_TYPE_SCL_ACCESS_POINT) {
SclAccessPoint *aps_sres = static_cast<SclAccessPoint *>(data->aps);
aps_sres[data->offset] = std::move(SclAccessPoint(ap, record->bss_type,
record->ie_ptr, record->ie_len));
}
}
// store to result_buff for future duplication removal
data->result_buff->push_back(*record);
data->offset = data->result_buff->size();
}
int SclSTAInterface::internal_scan(WiFiAccessPoint *aps, unsigned count, scan_result_type sres_type)
{
ScopedMutexLock lock(_iface_shared.mutex);
scl_result_t scl_res;
int res;
// initialize wifi, this is noop if already init
if (!_scl_emac.powered_up) {
if(!_scl_emac.power_up()) {
return NSAPI_ERROR_DEVICE_ERROR;
}
}
interal_scan_data.sema = new Semaphore();
interal_scan_data.sres_type = sres_type;
interal_scan_data.aps = aps;
interal_scan_data.count = count;
interal_scan_data.offset = 0;
interal_scan_data.scan_in_progress = true;
interal_scan_data.result_buff = new std::vector<scl_scan_result_t>();
scl_res = (scl_result_t)scl_wifi_scan(SCL_SCAN_TYPE_ACTIVE, SCL_BSS_TYPE_ANY,
NULL, NULL, NULL, NULL, scl_scan_handler, &internal_scan_result, &interal_scan_data);
if (scl_res != SCL_SUCCESS) {
res = scl_toerror(scl_res);
} else {
/* This semaphore will be released in scan callback once the scan is completed */
interal_scan_data.sema->acquire();
res = interal_scan_data.offset;
}
delete interal_scan_data.sema;
delete interal_scan_data.result_buff;
return res;
}
int SclSTAInterface::scan(WiFiAccessPoint *aps, unsigned count)
{
return internal_scan(aps, count, SRES_TYPE_WIFI_ACCESS_POINT);
}
int8_t SclSTAInterface::get_rssi()
{
int32_t rssi;
scl_result_t res;
if (!_scl_emac.powered_up) {
_scl_emac.power_up();
}
res = (scl_result_t) scl_wifi_get_rssi(&rssi);
if (res == SCL_ERROR) {
return SCL_ERROR;
}
return (int8_t)rssi;
}
int SclSTAInterface::is_interface_connected(void)
{
if (scl_wifi_is_ready_to_transceive() == SCL_SUCCESS) {
return SCL_SUCCESS;
} else {
return SCL_CONNECTION_LOST;
}
}
int SclSTAInterface::get_bssid(uint8_t *bssid)
{
scl_mac_t ap_mac;
scl_result_t res = SCL_SUCCESS;
if (bssid == NULL) {
return SCL_BADARG;
}
memset(&ap_mac, 0, sizeof(ap_mac));
if (scl_wifi_is_ready_to_transceive() == SCL_SUCCESS) {
res = (scl_result_t) scl_wifi_get_bssid(&ap_mac);
if (res == SCL_SUCCESS) {
memcpy(bssid, ap_mac.octet, sizeof(ap_mac.octet));
}
} else {
return SCL_CONNECTION_LOST;
}
return res;
}
int SclSTAInterface::wifi_set_up(void)
{
int res = SCL_SUCCESS;
res = scl_wifi_set_up();
return res;
}
| 7,136 |
572 |
#ifndef __APPLICATION_SPECIAL_PATH_H__
#define __APPLICATION_SPECIAL_PATH_H__
#include <shlobj.h>
#include "FilePathUtil.h"
class ApplicationSpecialPath {
public:
static std::wstring GetSpecialFolderPath(int csidl) {
wchar_t path[MAX_PATH+1];
if(!SHGetSpecialFolderPath(NULL, path, csidl, false))
return std::wstring();
return std::wstring(path);
}
static inline std::wstring GetPersonalPath() {
std::wstring path = GetSpecialFolderPath(CSIDL_PERSONAL);
if( path.empty() ) path = GetSpecialFolderPath(CSIDL_APPDATA);
if(path != L"") {
return path;
}
return L"";
}
static inline std::wstring GetAppDataPath() {
std::wstring path = GetSpecialFolderPath(CSIDL_APPDATA);
if(path != L"" ) {
return path;
}
return L"";
}
static inline std::wstring GetSavedGamesPath() {
std::wstring result;
PWSTR ppszPath = NULL;
HRESULT hr = ::SHGetKnownFolderPath(FOLDERID_SavedGames, 0, NULL, &ppszPath);
if( hr == S_OK ) {
result = std::wstring(ppszPath);
::CoTaskMemFree( ppszPath );
}
return result;
}
static inline std::wstring ReplaceStringAll( std::wstring src, const std::wstring& target, const std::wstring& dest ) {
std::wstring::size_type nPos = 0;
while( (nPos = src.find(target, nPos)) != std::wstring::npos ) {
src.replace( nPos, target.length(), dest );
}
return src;
}
static inline std::wstring GetConfigFileName( const std::wstring& exename ) {
return ChangeFileExt(exename, L".cf");
}
static std::wstring GetDataPathDirectory( std::wstring datapath, const std::wstring& exename ) {
if(datapath == L"" ) datapath = std::wstring(L"$(exepath)\\savedata");
std::wstring exepath = ExcludeTrailingBackslash(ExtractFileDir(exename));
std::wstring personalpath = ExcludeTrailingBackslash(GetPersonalPath());
std::wstring appdatapath = ExcludeTrailingBackslash(GetAppDataPath());
std::wstring savedgamespath = ExcludeTrailingBackslash(GetSavedGamesPath());
if(personalpath == L"") personalpath = exepath;
if(appdatapath == L"") appdatapath = exepath;
if(savedgamespath == L"") savedgamespath = exepath;
OSVERSIONINFO osinfo;
osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&osinfo);
bool vista_or_later = osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT && osinfo.dwMajorVersion >= 6;
std::wstring vistapath = vista_or_later ? appdatapath : exepath;
datapath = ReplaceStringAll(datapath, L"$(exepath)", exepath);
datapath = ReplaceStringAll(datapath, L"$(personalpath)", personalpath);
datapath = ReplaceStringAll(datapath, L"$(appdatapath)", appdatapath);
datapath = ReplaceStringAll(datapath, L"$(vistapath)", vistapath);
datapath = ReplaceStringAll(datapath, L"$(savedgamespath)", savedgamespath);
return IncludeTrailingBackslash(ExpandUNCFileName(datapath));
}
static std::wstring GetUserConfigFileName( const std::wstring& datapath, const std::wstring& exename ) {
// exepath, personalpath, appdatapath
return GetDataPathDirectory(datapath, exename) + ExtractFileName(ChangeFileExt(exename, L".cfu"));
}
};
#endif // __APPLICATION_SPECIAL_PATH_H__
| 1,175 |
310 | package org.seasar.doma.it.domain;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.seasar.doma.it.IntegrationTestEnvironment;
import org.seasar.doma.it.dao.FulltimeEmployeeDao;
import org.seasar.doma.it.dao.FulltimeEmployeeDaoImpl;
import org.seasar.doma.it.entity.FulltimeEmployee;
import org.seasar.doma.jdbc.Config;
@ExtendWith(IntegrationTestEnvironment.class)
public class AllowNullTest {
@Test
void selectDomain(Config config) throws Exception {
FulltimeEmployeeDao dao = new FulltimeEmployeeDaoImpl(config);
FulltimeEmployee e = new FulltimeEmployee();
e.setEmployeeId(99);
e.setEmployeeNo(9999);
dao.insert(e);
Money salary = dao.selectSalaryById(99);
assertNotNull(salary);
assertNull(salary.getValue());
}
@Test
void selectOptinalDomain(Config config) throws Exception {
FulltimeEmployeeDao dao = new FulltimeEmployeeDaoImpl(config);
FulltimeEmployee e = new FulltimeEmployee();
e.setEmployeeId(99);
e.setEmployeeNo(9999);
dao.insert(e);
Optional<Money> salary = dao.selectOptionalSalaryById(99);
assertNotNull(salary);
assertFalse(salary.isPresent());
}
}
| 518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.