repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
---|---|---|
scottkwarren/config-db | NAMD_2.12_Source/charm-6.7.1/src/xlat-i/xi-Type.h | #ifndef _TYPE_H
#define _TYPE_H
#include "xi-util.h"
namespace xi {
class TParamList;
class ParamList;
/*********************** Type System **********************/
class Type : public Printable {
public:
virtual void print(XStr&) = 0;
virtual int isVoid(void) const {return 0;}
virtual int isBuiltin(void) const { return 0; }
virtual int isMessage(void) const {return 0;}
virtual int isTemplated(void) const { return 0; }
virtual int isPointer(void) const {return 0;}
virtual int isNamed(void) const { return 0; }
virtual int isCkArgMsgPtr(void) const {return 0;}
virtual int isCkArgMsg(void) const {return 0;}
virtual int isCkMigMsgPtr(void) const {return 0;}
virtual int isCkMigMsg(void) const {return 0;}
virtual int isReference(void) const {return 0;}
virtual int isInt(void) const { return 0; }
virtual bool isConst(void) const {return false;}
virtual Type *deref(void) {return this;}
virtual const char *getBaseName(void) const = 0;
virtual const char *getScope(void) const = 0;
virtual int getNumStars(void) const {return 0;}
virtual void genProxyName(XStr &str,forWhom forElement);
virtual void genIndexName(XStr &str);
virtual void genMsgProxyName(XStr& str);
XStr proxyName(forWhom w)
{XStr ret; genProxyName(ret,w); return ret;}
XStr indexName(void)
{XStr ret; genIndexName(ret); return ret;}
XStr msgProxyName(void)
{XStr ret; genMsgProxyName(ret); return ret;}
virtual void printVar(XStr &str, char *var) {print(str); str<<" "; str<<var;}
int operator==(const Type &tp) const {
return (strcmp(getBaseName(), tp.getBaseName())==0);
}
virtual ~Type() { }
};
class BuiltinType : public Type {
private:
char *name;
public:
BuiltinType(const char *n) : name((char *)n) {}
int isBuiltin(void) const {return 1;}
void print(XStr& str) { str << name; }
int isVoid(void) const { return !strcmp(name, "void"); }
int isInt(void) const { return !strcmp(name, "int"); }
const char *getBaseName(void) const { return name; }
const char *getScope(void) const { return NULL; }
};
class NamedType : public Type {
private:
const char* name;
const char* scope;
TParamList *tparams;
public:
NamedType(const char* n, TParamList* t=0, const char* scope_=NULL)
: name(n), scope(scope_), tparams(t) {}
int isTemplated(void) const { return (tparams!=0); }
int isCkArgMsg(void) const {return 0==strcmp(name,"CkArgMsg");}
int isCkMigMsg(void) const {return 0==strcmp(name,"CkMigrateMessage");}
void print(XStr& str);
int isNamed(void) const {return 1;}
virtual const char *getBaseName(void) const { return name; }
virtual const char *getScope(void) const { return scope; }
virtual void genProxyName(XStr& str,forWhom forElement);
virtual void genIndexName(XStr& str);
virtual void genMsgProxyName(XStr& str);
};
class PtrType : public Type {
private:
Type *type;
int numstars; // level of indirection
public:
PtrType(Type *t) : type(t), numstars(1) {}
int isPointer(void) const {return 1;}
int isCkArgMsgPtr(void) const {return numstars==1 && type->isCkArgMsg();}
int isCkMigMsgPtr(void) const {return numstars==1 && type->isCkMigMsg();}
int isMessage(void) const {return numstars==1 && !type->isBuiltin();}
void indirect(void) { numstars++; }
int getNumStars(void) const {return numstars; }
void print(XStr& str);
Type* deref(void) { return type; }
const char *getBaseName(void) const { return type->getBaseName(); }
const char *getScope(void) const { return NULL; }
virtual void genMsgProxyName(XStr& str) {
if (numstars != 1) {
die("too many stars-- entry parameter must have form 'MTYPE *msg'");
} else {
type->genMsgProxyName(str);
}
}
};
class ReferenceType : public Type {
private:
Type *referant;
public:
ReferenceType(Type *t) : referant(t) {}
int isReference(void) const {return 1;}
void print(XStr& str) {str<<referant<<" &";}
virtual Type *deref(void) {return referant;}
const char *getBaseName(void) const { return referant->getBaseName(); }
const char *getScope(void) const { return NULL; }
};
class ConstType : public Type {
private:
Type *constType;
public:
ConstType(Type *t) : constType(t) {}
void print(XStr& str) {str << "const " << constType;}
virtual bool isConst(void) const {return true;}
virtual Type *deref(void) {return constType;}
const char *getBaseName(void) const { return constType->getBaseName(); }
const char *getScope(void) const { return NULL; }
};
class FuncType : public Type {
private:
Type *rtype;
const char *name;
ParamList *params;
public:
FuncType(Type* r, const char* n, ParamList* p)
:rtype(r),name(n),params(p) {}
void print(XStr& str);
const char *getBaseName(void) const { return name; }
const char *getScope(void) const { return NULL; }
};
//This is used as a list of base classes
class TypeList : public Printable {
public:
Type *type;
TypeList *next;
TypeList(Type *t, TypeList *n=0) : type(t), next(n) {}
~TypeList() { delete type; delete next; }
int length(void) const;
Type *getFirst(void) {return type;}
void print(XStr& str);
void genProxyNames(XStr& str, const char *prefix, const char *middle,
const char *suffix, const char *sep, forWhom forElement);
};
} // namespace xi
#endif // ifndef _TYPE_H
|
goyourfly/NovaCustom | native/avos/Source/stream_sink_audio_fake.c | /*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "global.h"
#include "types.h"
#include "debug.h"
#include "stream.h"
#include "file.h"
#include "pipe.h"
#include <stdint.h>
#ifdef CONFIG_STREAM
static int debug_fas = 0;
DECLARE_DEBUG_TOGGLE( "dbgfas", debug_fas );
#define DBGS if(Debug[DBG_STREAM])
#define DBG if(debug_fas)
static int delay = 0;
static int rate;
static int block_size = 8192;
static int block_num = 8;
static PIPE *out_pipe = NULL;
static pthread_mutex_t pipe_mutex;
static pthread_t out_thread_handle;
static pthread_mutex_t out_mutex;
static int out_run;
static int ref_time;
static uint64_t ref_bytes;
static int last_time;
static int _flush( STREAM *s );
static void output( STREAM *s )
{
UCHAR data[block_size];
int used = pipe_get_used( out_pipe );
if( used == 0 ) {
// we have an underrun!
if( ref_bytes != 0 ) {
serprintf("ssaf: UNDERRUN!\n");
}
ref_time = atime();
ref_bytes = 0;
msec_sleep(20);
return;
}
// where should we be now:
int now_time = atime() - ref_time;
uint64_t now_bytes = (uint64_t )now_time * rate * 2 * 2 / 1000;
uint64_t diff = now_bytes - ref_bytes;
int out = MIN( block_size, diff );
out = MIN( out, used );
//DBG2 serprintf("ssaf: time %8d diff %6lld used %6d out %6d\n", now_time, diff, used, out );
DBG serprintf("ssaf: %2d used %6d out %6d\n", now_time - last_time, used, out );
pipe_read( out_pipe, data, out );
ref_bytes += out;
last_time = now_time;
msec_sleep(20);
}
// ************************************************************
//
// out_thread
//
// ************************************************************
static void *out_thread( void *data )
{
STREAM *s = (STREAM*)data;
DBGS serprintf("out_thread::Starting\r\n");
while( out_run ) {
if( !pthread_mutex_trylock( &out_mutex ) ) {
output( s );
pthread_mutex_unlock( &out_mutex );
}
msec_sleep( 1 );
}
DBGS serprintf("out_thread::Exiting\r\n");
return NULL;
}
static int _open( STREAM *s )
{
return 0;
}
static int _close( STREAM *s )
{
return 0;
}
static int _start( STREAM *s )
{
rate = s->audio->samplesPerSec;
delay = (UINT64)1000 * (UINT64)(block_size * block_num) / (rate * 2 * 2);
DBGS serprintf("stream_sink_audio_open_fake: rate %d delay %d\r\n", rate, delay );
if( !(out_pipe = pipe_new( block_size * block_num ) ) ) {
return 1;
}
pthread_mutex_init ( &out_mutex, NULL );
pthread_mutex_init ( &pipe_mutex, NULL );
_flush( s );
// lock and start the out_thread
pthread_mutex_lock( &out_mutex );
out_run = 1;
apthread_create( &out_thread_handle, 0, out_thread, (void*)s, "audio fake out" );
ref_time = atime();
ref_bytes = 0;
pthread_mutex_unlock( &out_mutex );
s->audio_sink_open = 1;
return 0;
}
static int _stop( STREAM *s )
{
DBGS serprintf("stream_sink_audio_close_fake\r\n");
if( !s->audio_sink_open ) {
serprintf("ssaf not open!\r\n");
return 1;
}
pthread_mutex_lock( &out_mutex );
DBGS serprintf("waiting for out thread to join\r\n");
if( out_run ) {
out_run = 0;
apthread_join( out_thread_handle, NULL );
DBGS serprintf("out_thread joined\r\n");
}
pthread_mutex_unlock( &out_mutex );
pthread_mutex_destroy( &out_mutex );
pthread_mutex_destroy( &pipe_mutex );
if( out_pipe ) {
pipe_delete( &out_pipe );
}
s->audio_sink_open = 0;
return 0;
}
static int _flush( STREAM *s )
{
DBGS serprintf("stream_sink_audio_flush_fake\r\n");
pthread_mutex_lock( &pipe_mutex );
pipe_flush(out_pipe);
pthread_mutex_unlock( &pipe_mutex );
return 0;
}
static int _end( STREAM *s )
{
return 0;
}
static int _syncable( STREAM *s )
{
return 1;
}
static int _write( STREAM *s, AUDIO_FRAME *frame )
{
UCHAR *data = frame->data;
int size = frame->size;
while( size ) {
int copy = MIN( size, block_size );
//DBGS serprintf("ssaf: free %5d copy: %5d\r\n", pipe_get_free( out_pipe ), copy );
pipe_write_wait( out_pipe, data, copy );
data += copy;
size -= copy;
}
return frame->size;
}
static int _preload( STREAM *s )
{
return 0;
}
static int _delay( STREAM *s )
{
return delay;
}
static int _can_write( STREAM *s, int len )
{
return pipe_get_free( out_pipe ) >= block_num;
}
static int _set_passthrough( STREAM *s, int pass )
{
return 0;
}
static int _get_passthrough( STREAM *s )
{
return 0;
}
static int _mute( STREAM *s, int mute )
{
return 0;
}
STREAM_SINK_AUDIO stream_sink_audio_FAKE =
{
"audio fake",
_open,
_close,
_start,
_stop,
_write,
_preload,
_flush,
_end,
_syncable,
_delay,
_can_write,
_set_passthrough,
_get_passthrough,
_mute,
};
#endif
|
lyriccoder/aibolit | test/integration/all.py | # The MIT License (MIT)
#
# Copyright (c) 2020 Aibolit
#
# 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 NON-INFRINGEMENT. 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.
import os
import sys
from typing import List
import numpy as np
import tqdm
from aibolit.config import Config
# TODO: fix all errors in the patterns/metrics and make these lists empty
EXCLUDE_PATTERNS: List[str] = []
EXCLUDE_METRICS: List[str] = []
current_path: str = os.path.dirname(os.path.realpath(__file__))
print('Processed files in testing:')
for filename in tqdm.tqdm(os.listdir(current_path + '/samples')):
for pattern in Config.get_patterns_config()['patterns']:
if pattern['code'] in EXCLUDE_PATTERNS:
continue
try:
path_to_file = os.path.join(current_path, 'samples', filename)
patter_result = pattern['make']().value(path_to_file)
assert isinstance(patter_result, list) and \
all(isinstance(item, int) for item in patter_result), \
f'Pattern return {patter_result} with type {type(patter_result)}, but list of int was expected.'
except Exception as e:
print(f'Error in application of the pattern "{pattern["name"]}" '
f'with code {pattern["code"]} for file "{filename}"')
print(f'Reason: {e}')
sys.exit(1)
for metric in Config.get_patterns_config()['metrics']:
if metric['code'] in EXCLUDE_METRICS:
continue
try:
path_to_file = os.path.join(current_path, 'samples', filename)
metric_result = metric['make']().value(path_to_file)
assert isinstance(metric_result, (int, float, np.float64)), \
f'Metric return {metric_result} of type {type(metric_result)}, ' \
'but int, float or numpy float was expected'
except Exception as e:
print(f'Error in application of the metric "{metric["name"]}" '
f'with code {metric["code"]} for file "{filename}"')
print(f'Reason: {e}')
sys.exit(1)
sys.exit(0)
|
Archive-42/a-whole-bunch-o-gatsby-templates | The-NodeJS-Master-Class/Section 4/Making AJAX Requests/public/app.js | <gh_stars>0
/*
* Frontend Logic for application
*
*/
// Container for frontend application
var app = {};
// Config
app.config = {
'sessionToken' : false
};
// AJAX Client (for RESTful API)
app.client = {}
// Interface for making API calls
app.client.request = function(headers,path,method,queryStringObject,payload,callback){
// Set defaults
headers = typeof(headers) == 'object' && headers !== null ? headers : {};
path = typeof(path) == 'string' ? path : '/';
method = typeof(method) == 'string' && ['POST','GET','PUT','DELETE'].indexOf(method.toUpperCase()) > -1 ? method.toUpperCase() : 'GET';
queryStringObject = typeof(queryStringObject) == 'object' && queryStringObject !== null ? queryStringObject : {};
payload = typeof(payload) == 'object' && payload !== null ? payload : {};
callback = typeof(callback) == 'function' ? callback : false;
// For each query string parameter sent, add it to the path
var requestUrl = path+'?';
var counter = 0;
for(var queryKey in queryStringObject){
if(queryStringObject.hasOwnProperty(queryKey)){
counter++;
// If at least one query string parameter has already been added, preprend new ones with an ampersand
if(counter > 1){
requestUrl+='&';
}
// Add the key and value
requestUrl+=queryKey+'='+queryStringObject[queryKey];
}
}
// Form the http request as a JSON type
var xhr = new XMLHttpRequest();
xhr.open(method, requestUrl, true);
xhr.setRequestHeader("Content-type", "application/json");
// For each header sent, add it to the request
for(var headerKey in headers){
if(headers.hasOwnProperty(headerKey)){
xhr.setRequestHeader(headerKey, headers[headerKey]);
}
}
// If there is a current session token set, add that as a header
if(app.config.sessionToken){
xhr.setRequestHeader("token", app.config.sessionToken.id);
}
// When the request comes back, handle the response
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE) {
var statusCode = xhr.status;
var responseReturned = xhr.responseText;
// Callback if requested
if(callback){
try{
var parsedResponse = JSON.parse(responseReturned);
callback(statusCode,parsedResponse);
} catch(e){
callback(statusCode,false);
}
}
}
}
// Send the payload as JSON
var payloadString = JSON.stringify(payload);
xhr.send(payloadString);
};
|
arthur-zhang/KiVM | src/kivm/jni/nativeLibrary.cpp | <gh_stars>100-1000
//
// Created by kiva on 2018/11/11.
//
#include <kivm/kivm.h>
#include <kivm/jni/nativeLibrariy.h>
namespace kivm {
using JNIOnLoadFunction = jint(*)(JavaVM *, void *);
using JNIOnUnloadFunction = void (*)(JavaVM *, void *);
JavaNativeLibrary::JavaNativeLibrary(const String &libraryName)
: _libraryName(libraryName), _linked(false) {
}
bool JavaNativeLibrary::prepare() {
const String &path = findLibrary(_libraryName);
int javaVersion = JNI_VERSION_UNKNOWN;
if (_sharedLibrary.open(strings::toStdString(path))) {
auto onLoadFunction = (JNIOnLoadFunction) _sharedLibrary.findSymbol("JNI_OnLoad");
if (onLoadFunction) {
javaVersion = onLoadFunction(KiVM::getJavaVMQuick(), nullptr);
}
}
_linked = KiVM::checkJavaVersion(javaVersion);
return _linked;
}
void JavaNativeLibrary::dispose() {
if (_linked) {
auto onUnloadFunction = (JNIOnUnloadFunction) _sharedLibrary.findSymbol("JNI_OnUnload");
if (onUnloadFunction) {
onUnloadFunction(KiVM::getJavaVMQuick(), nullptr);
}
_linked = false;
}
}
String JavaNativeLibrary::findLibrary(const String &libraryName) {
return kivm::String();
}
JavaNativeLibrary::~JavaNativeLibrary() {
dispose();
}
} |
ronething/leetcode-golang | topic/dp/62. Unique Paths.go | <gh_stars>0
package dp
func uniquePaths(m int, n int) int {
// res[0][0] = 1
// res[0][1] = 1
// res[1][0] = 1
// res[i][j] = res[i-1][j] + res[i][j-1] (i,j>=1)
// 表示 索引位置 i,j 元素的不同路径数
// 要么由上面走到 i,j 要么由左边走到 i,j 把两者的路径数加起来即可
// 需要注意判断是否越界
res := make([]int, m*n)
// 索引 m 表示行,n 表示列
// i * n + j
res[0] = 1
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i == 0 && j == 0 {
continue
}
index := i*n + j
if i-1 >= 0 {
res[index] += res[(i-1)*n+j]
}
if j-1 >= 0 {
res[index] += res[i*n+j-1]
}
}
}
return res[m*n-1]
}
|
JasonLeeSJTU/Algorithms_Python | jianzhi_offer_3.py | #!/usr/bin/env python
# encoding: utf-8
'''
@author: <NAME>
@license: (C) Copyright @ <NAME>
@contact: <EMAIL>
@file: jianzhi_offer_3.py
@time: 2019/4/18 11:03
@desc:
'''
class Solution:
# array 二维列表
def Find(self, target, array):
if not target or not array:
return False
rows = len(array)
cols = len(array[0])
row = rows - 1
col = 0
while col < cols and row >= 0:
if target == array[row][col]:
return True
elif target > array[row][col]:
col += 1
else:
row -= 1
return False
if __name__ == '__main__':
array = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
res = Solution()
a = res.Find(16, array)
print(a)
|
johnnygreco/hugs-pipe | scripts/runner.py | <reponame>johnnygreco/hugs-pipe
"""
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database with the master process.
"""
timer = time()
success, sources, meta_data, synth_ids = args
run_name, tract, patch, patch_meta = meta_data
db_ingest = hugs.database.HugsIngest(session, run_name)
if success:
db_ingest.add_all(tract, patch, patch_meta, sources)
if synth_ids is not None:
db_ingest.add_injected_synths(synth_ids)
else:
db_ingest.add_tract(tract)
db_ingest.add_patch(patch, patch_meta)
delta_time = time() - timer
hugs.log.logger.info('time to ingest = {:.2f} seconds'.format(delta_time))
def worker(p):
"""
Workers initialize pipe configuration and run pipeline.
"""
rank = MPI.COMM_WORLD.Get_rank()
if p['seed'] is None:
tract, p1, p2 = p['tract'], int(p['patch'][0]), int(p['patch'][-1])
seed = [int(time()), tract, p1, p2, rank]
else:
seed = p['seed']
config = hugs.PipeConfig(run_name=p['run_name'],
config_fn=p['config_fn'],
random_state=seed,
log_fn=p['log_fn'],
rerun_path=p['rerun_path'])
config.set_patch_id(p['tract'], p['patch'])
config.logger.info('random seed set to {}'.format(seed))
if p['use_old_pipeline']:
results = find_lsbgs.run(config)
else:
results = next_gen_search.run(config, False)
pm = results.hugs_exp.patch_meta
if (results.synths is not None) and results.success:
if len(results.synths) > 0:
synth_ids = results.synths.to_pandas().loc[:, ['synth_id']]
for plane in config.synth_check_masks:
masked = hugs.synths.find_masked_synths(results.synths,
results.exp_clean,
planes=plane)
synth_ids['mask_' + plane.lower()] = masked
else:
synth_ids = None
else:
synth_ids = None
patch_meta = PatchMeta(
x0 = pm.x0,
y0 = pm.y0,
small_frac = pm.small_frac,
cleaned_frac = pm.cleaned_frac,
bright_obj_frac = pm.bright_obj_frac,
good_data_frac = pm.good_data_frac
)
meta_data = [
config.run_name,
config.tract,
config.patch,
patch_meta,
]
if results.success:
df = results.sources.to_pandas()
df['flags'] = df['flags'].astype(int)
else:
df = None
config.reset_mask_planes()
config.logger.info('writing results to database')
return results.success, df, meta_data, synth_ids
if __name__=='__main__':
from argparse import ArgumentParser
from astropy.table import Table
rank = MPI.COMM_WORLD.Get_rank()
# parse command-line arguments
parser = ArgumentParser('Run hugs pipeline')
parser.add_argument('-t', '--tract', type=int, help='HSC tract')
parser.add_argument('-p', '--patch', type=str, help='HSC patch')
parser.add_argument('-c', '--config_fn', help='hugs config file',
default=hugs.utils.default_config_fn)
parser.add_argument('--patches_fn', help='patches file')
parser.add_argument('--use-old-pipeline', action="store_true")
parser.add_argument('-r', '--run_name', type=str, default='hugs-pipe-run')
parser.add_argument('--seed', help='rng seed', default=None)
parser.add_argument('--rerun_path', help='full rerun path', default=None)
parser.add_argument('--overwrite', type=bool,
help='overwrite database', default=True)
group = parser.add_mutually_exclusive_group()
group.add_argument('--ncores', default=1, type=int,
help='Number of processes (uses multiprocessing).')
group.add_argument('--mpi', default=False, action="store_true",
help="Run with MPI.")
args = parser.parse_args()
config_params = hugs.utils.read_config(args.config_fn)
outdir = config_params['hugs_io']
#######################################################################
# run on a single patch
#######################################################################
if args.tract is not None:
assert args.patch is not None
tract, patch = args.tract, args.patch
patches = Table([[tract], [patch]], names=['tract', 'patch'])
run_dir_name = '{}-{}-{}'.format(args.run_name, tract, patch)
outdir = os.path.join(outdir, run_dir_name)
hugs.utils.mkdir_if_needed(outdir)
log_fn = os.path.join(outdir, 'hugs-pipe.log')
patches['outdir'] = outdir
patches['log_fn'] = log_fn
#######################################################################
# OR run on all patches in file
#######################################################################
elif args.patches_fn is not None:
patches = Table.read(args.patches_fn)
if rank==0:
time_label = hugs.utils.get_time_label()
outdir = os.path.join(
outdir, '{}-{}'.format(args.run_name, time_label))
hugs.utils.mkdir_if_needed(outdir)
log_dir = os.path.join(outdir, 'log')
hugs.utils.mkdir_if_needed(log_dir)
log_fn = []
for tract, patch in patches['tract', 'patch']:
fn = os.path.join(log_dir, '{}-{}.log'.format(tract, patch))
log_fn.append(fn)
patches['outdir'] = outdir
patches['log_fn'] = log_fn
else:
print('\n**** must give tract and patch --or-- a patch file ****\n')
parser.print_help()
exit()
patches['rerun_path'] = args.rerun_path
patches['seed'] = args.seed
patches['config_fn'] = args.config_fn
patches['run_name'] = args.run_name
patches['use_old_pipeline'] = args.use_old_pipeline
if rank==0:
# open database session with master process
db_fn = os.path.join(outdir, args.run_name+'.db')
engine = hugs.database.connect(db_fn, args.overwrite)
session = hugs.database.Session()
shutil.copyfile(args.config_fn, os.path.join(outdir, 'config.yml'))
pool = schwimmbad.choose_pool(mpi=args.mpi, processes=args.ncores)
list(pool.map(worker, patches, callback=ingest_data))
pool.close()
|
avijitmondal/Together | together-auth-center/src/main/java/com/avijitmondal/together/auth/service/UserTokenSessionService.java | package com.avijitmondal.together.auth.service;
import com.avijitmondal.together.auth.model.UserTokenSession;
import com.avijitmondal.together.auth.repository.UserTokenSessionRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Optional;
@Service
public class UserTokenSessionService implements IUserTokenSessionService {
private final Log logger = LogFactory.getLog(this.getClass());
@Autowired
private UserTokenSessionRepository userTokenSessionRepository;
@Override
public ValidMappingResponse isValidUserTokenSessionMapping(UserTokenSession userTokenSession) throws UsernameNotFoundException {
String username = userTokenSession.getUsername();
Optional<UserTokenSession> userTokenSessionFromDB = userTokenSessionRepository.findOneByUsername(username);
if (userTokenSessionFromDB.isEmpty()) {
logger.error("User " + username + " mapping with token is not found in the database.");
throw new UsernameNotFoundException("User " + username + " mapping with token is not found in the database.");
}
LocalDateTime currentSystemTime = LocalDateTime.now();
ZonedDateTime currentZonedDateTime = currentSystemTime.atZone(ZoneId.systemDefault());
long currentTimeInMillis = currentZonedDateTime.toInstant().toEpochMilli();
ZonedDateTime dataBaseZonedDateTime = userTokenSessionFromDB.get().getCreatedTime().atZone(ZoneId.systemDefault());
// tokenTimeInMillis = created_time in millis + expiry time (seconds) * 1000.
long tokenTimeInMillis = dataBaseZonedDateTime.toInstant().toEpochMilli() + (userTokenSessionFromDB.get().getExpiryTime() * 1000);
if ( currentTimeInMillis >= tokenTimeInMillis) {
logger.info("User " + username + " token has expired. Please generate new token. Deleting the expired token mapping.");
userTokenSessionRepository.delete(userTokenSessionFromDB.get());
throw new UsernameNotFoundException("User " + username + " token has expired. Please generate new token.");
}else if(!userTokenSession.equals(userTokenSessionFromDB.get())) {
if (!userTokenSessionFromDB.get().getToken().equals(userTokenSession.getToken())){
logger.info("User "+userTokenSession.getUsername()+ " has invalid user and token mapping. Please generate new token.");
} else {
logger.info("User "+userTokenSession.getUsername()+ " has invalid user and session-id mapping. Please generate new token.");
}
logger.info("So, Deleting the invalid mapping.");
userTokenSessionRepository.delete(userTokenSessionFromDB.get());
throw new UsernameNotFoundException("User " + username + " has invalid user, session-id and token mapping. Please generate new token.");
}else {
logger.info("User " + username + " has valid token.");
return new ValidMappingResponse(true, userTokenSessionFromDB.get());
}
}
@Override
public UserTokenSession saveUserTokenSessionMapping(UserTokenSession userTokenSession) {
Optional<UserTokenSession> userTokenSessionFromDB = userTokenSessionRepository.findOneByUsername(userTokenSession.getUsername());
if (userTokenSessionFromDB.isPresent()) {
if (userTokenSessionFromDB.get().equals(userTokenSession)) {
logger.info("User "+userTokenSession.getUsername()+ " making login call again with same token and session-id.");
} else if (!userTokenSessionFromDB.get().getToken().equals(userTokenSession.getToken())){
logger.info("User "+userTokenSession.getUsername()+ " making login call with new token");
} else {
logger.info("User "+userTokenSession.getUsername()+ " making login call with different session-id");
}
logger.info("So, Deleting older mapping from tbl_user_token_session."+userTokenSessionFromDB);
userTokenSessionRepository.delete(userTokenSessionFromDB.get());
}
return userTokenSessionRepository.save(userTokenSession);
}
}
|
McDoyen/yavasource | javasource/changecalendar/proxies/UU95_RecalulateObject.java | <reponame>McDoyen/yavasource<gh_stars>0
// This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package changecalendar.proxies;
public class UU95_RecalulateObject
{
private final com.mendix.systemwideinterfaces.core.IMendixObject uU95_RecalulateObjectMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "ChangeCalendar.UU95_RecalulateObject";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
UU95_RecalulateObject_Day("ChangeCalendar.UU95_RecalulateObject_Day");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@Override
public java.lang.String toString()
{
return metaName;
}
}
public UU95_RecalulateObject(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "ChangeCalendar.UU95_RecalulateObject"));
}
protected UU95_RecalulateObject(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject uU95_RecalulateObjectMendixObject)
{
if (uU95_RecalulateObjectMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("ChangeCalendar.UU95_RecalulateObject", uU95_RecalulateObjectMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a ChangeCalendar.UU95_RecalulateObject");
this.uU95_RecalulateObjectMendixObject = uU95_RecalulateObjectMendixObject;
this.context = context;
}
/**
* @deprecated Use 'UU95_RecalulateObject.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static changecalendar.proxies.UU95_RecalulateObject initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return changecalendar.proxies.UU95_RecalulateObject.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static changecalendar.proxies.UU95_RecalulateObject initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new changecalendar.proxies.UU95_RecalulateObject(context, mendixObject);
}
public static changecalendar.proxies.UU95_RecalulateObject load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return changecalendar.proxies.UU95_RecalulateObject.initialize(context, mendixObject);
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of UU95_RecalulateObject_Day
*/
public final java.util.List<mendix.proxies.Day> getUU95_RecalulateObject_Day() throws com.mendix.core.CoreException
{
return getUU95_RecalulateObject_Day(getContext());
}
/**
* @param context
* @return value of UU95_RecalulateObject_Day
*/
@SuppressWarnings("unchecked")
public final java.util.List<mendix.proxies.Day> getUU95_RecalulateObject_Day(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
java.util.List<mendix.proxies.Day> result = new java.util.ArrayList<mendix.proxies.Day>();
Object valueObject = getMendixObject().getValue(context, MemberNames.UU95_RecalulateObject_Day.toString());
if (valueObject == null)
return result;
for (com.mendix.systemwideinterfaces.core.IMendixObject mendixObject : com.mendix.core.Core.retrieveIdList(context, (java.util.List<com.mendix.systemwideinterfaces.core.IMendixIdentifier>) valueObject))
result.add(mendix.proxies.Day.initialize(context, mendixObject));
return result;
}
/**
* Set value of UU95_RecalulateObject_Day
* @param uu95_recalulateobject_day
*/
public final void setUU95_RecalulateObject_Day(java.util.List<mendix.proxies.Day> uu95_recalulateobject_day)
{
setUU95_RecalulateObject_Day(getContext(), uu95_recalulateobject_day);
}
/**
* Set value of UU95_RecalulateObject_Day
* @param context
* @param uu95_recalulateobject_day
*/
public final void setUU95_RecalulateObject_Day(com.mendix.systemwideinterfaces.core.IContext context, java.util.List<mendix.proxies.Day> uu95_recalulateobject_day)
{
java.util.List<com.mendix.systemwideinterfaces.core.IMendixIdentifier> identifiers = new java.util.ArrayList<com.mendix.systemwideinterfaces.core.IMendixIdentifier>();
for (mendix.proxies.Day proxyObject : uu95_recalulateobject_day)
identifiers.add(proxyObject.getMendixObject().getId());
getMendixObject().setValue(context, MemberNames.UU95_RecalulateObject_Day.toString(), identifiers);
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return uU95_RecalulateObjectMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final changecalendar.proxies.UU95_RecalulateObject that = (changecalendar.proxies.UU95_RecalulateObject) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "ChangeCalendar.UU95_RecalulateObject";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
|
ulrichdah/BittyBuzz | src/crazyflie/lib/inc/cfmodules/eventtrigger.h | /**
* || ____ _ __
* +------+ / __ )(_) /_______________ _____ ___
* | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
* +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
* || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
*
* Crazyflie control firmware
*
* Copyright (C) 2012-2021 BitCraze AB
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, in version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* eventtrigger.h - Event triggers to mark important system events with payloads
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
/* Data structures */
enum eventtriggerType_e {
eventtriggerType_uint8 = 1,
eventtriggerType_uint16 = 2,
eventtriggerType_uint32 = 3,
eventtriggerType_int8 = 4,
eventtriggerType_int16 = 5,
eventtriggerType_int32 = 6,
eventtriggerType_float = 7,
};
typedef float float_t;
typedef struct eventtriggerPayloadDesc_s
{
enum eventtriggerType_e type;
const char *name;
} eventtriggerPayloadDesc;
typedef struct eventtrigger_s
{
const char *name;
const struct eventtriggerPayloadDesc_s* payloadDesc;
uint8_t numPayloadVariables;
void *payload;
uint8_t payloadSize;
} eventtrigger;
/* Example Use Case
static struct
{
uint8_t var1;
uint32_t var2;
} __attribute__((packed)) __eventTriggerPayload__myEvent__;
static const eventtriggerPayloadDesc __eventTriggerPayloadDesc__myEvent__[] = {
{.type = eventtriggerType_uint8,
.name = "var1"},
{.type = eventtriggerType_uint32,
.name = "var2"},
};
static const eventtrigger myEventTrigger = {
.name = "myEvent",
.payloadDesc = __eventTriggerPayloadDesc__myEvent__,
.numPayloadVariables = sizeof(__eventTriggerPayloadDesc__myEvent__) / sizeof(eventtriggerPayloadDesc),
.payload = &__eventTriggerPayload__myEvent__,
.payloadSize = sizeof(__eventTriggerPayload__myEvent__),
};
*/
/* The same code above can be generated using the following macro:
EVENTTRIGGER(myEvent, uint8, var1, uint32, var2)
To debug/develop the macros, a good way is to create a new file "etdbg.c" with the following content
and then execute "gcc -E etdbg.c":
#include "src/modules/interface/eventtrigger.h"
EVENTTRIGGER(myEvent, uint8, var1, uint32, var2)
*/
#ifndef UNIT_TEST_MODE
/* Macro magic, see https://codecraft.co/2014/11/25/variadic-macros-tricks/ */
#define _GET_NTH_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, N, ...) N
#define _fe_0(_call, ...)
#define _fe_2(_call, k, v, ...) _call(k, v) _fe_0(_call, __VA_ARGS__)
#define _fe_4(_call, k, v, ...) _call(k, v) _fe_2(_call, __VA_ARGS__)
#define _fe_6(_call, k, v, ...) _call(k, v) _fe_4(_call, __VA_ARGS__)
#define _fe_8(_call, k, v, ...) _call(k, v) _fe_6(_call, __VA_ARGS__)
#define _fe_10(_call, k, v, ...) _call(k, v) _fe_8(_call, __VA_ARGS__)
#define CALL_MACRO_FOR_EACH_PAIR(x, ...) \
_GET_NTH_ARG("ignored", ##__VA_ARGS__, \
_fe_10, _invalid_, \
_fe_8, _invalid_, \
_fe_6, _invalid_, \
_fe_4, _invalid_, \
_fe_2, _invalid_, \
_fe_0) \
(x, ##__VA_ARGS__)
#define CALL_MACRO_IF_EMPTY(TRUE_MACRO, FALSE_MACRO, NAME, ...) \
_GET_NTH_ARG("ignored", ##__VA_ARGS__, \
TRUE_MACRO, _invalid_, \
TRUE_MACRO, _invalid_, \
TRUE_MACRO, _invalid_, \
TRUE_MACRO, _invalid_, \
TRUE_MACRO, _invalid_, \
FALSE_MACRO)(NAME, ##__VA_ARGS__)
#define _EVENTTRIGGER_ENTRY_PACKED(TYPE, NAME) \
TYPE##_t NAME;
#define _EVENTTRIGGER_ENTRY_DESCRIPTION(TYPE, NAME) \
{ \
.type = eventtriggerType_##TYPE, \
.name = #NAME, \
},
#define _EVENTTRIGGER_NON_EMPTY(NAME, ...) \
static struct \
{ \
CALL_MACRO_FOR_EACH_PAIR(_EVENTTRIGGER_ENTRY_PACKED, ##__VA_ARGS__) \
} __attribute__((packed)) eventTrigger_##NAME##_payload; \
static const eventtriggerPayloadDesc __eventTriggerPayloadDesc__##NAME##__[] = \
{ \
CALL_MACRO_FOR_EACH_PAIR(_EVENTTRIGGER_ENTRY_DESCRIPTION, ##__VA_ARGS__)}; \
static const eventtrigger eventTrigger_##NAME __attribute__((section(".eventtrigger." #NAME), used)) = { \
.name = #NAME, \
.payloadDesc = __eventTriggerPayloadDesc__##NAME##__, \
.numPayloadVariables = sizeof(__eventTriggerPayloadDesc__##NAME##__) / \
sizeof(eventtriggerPayloadDesc), \
.payload = &eventTrigger_##NAME##_payload, \
.payloadSize = sizeof(eventTrigger_##NAME##_payload), \
};
#define _EVENTTRIGGER_EMPTY(NAME) \
static const eventtrigger eventTrigger_##NAME __attribute__((section(".eventtrigger." #NAME), used)) = { \
.name = #NAME, \
.payloadDesc = NULL, \
.numPayloadVariables = 0, \
.payload = NULL, \
.payloadSize = 0, \
};
#define EVENTTRIGGER(NAME, ...) \
CALL_MACRO_IF_EMPTY(_EVENTTRIGGER_NON_EMPTY, _EVENTTRIGGER_EMPTY, NAME, ##__VA_ARGS__)
#else // UNIT_TEST_MODE
// Empty defines when running unit tests
#define EVENTTRIGGER(NAME, ...)
#endif // UNIT_TEST_MODE
/* Functions and associated data structures */
typedef void (*eventtriggerCallback)(const eventtrigger *);
enum eventtriggerHandler_e
{
eventtriggerHandler_USD = 0,
eventtriggerHandler_Count
};
/** Get the eventtrigger id from a pointer
*
* @param event Pointer to the event
* @return A unique id 0...numEvents-1 for the event
*/
uint16_t eventtriggerGetId(const eventtrigger *event);
/** Get the eventtrigger pointer from an event id
*
* @param id unique id of the event
* @return A pointer to the eventtrigger data structure, or NULL if no such eventtrigger exists
*/
const eventtrigger* eventtriggerGetById(uint16_t id);
/** Get the eventtrigger pointer from an event name
*
* @param name Name of the event
* @return A pointer to the eventtrigger data structure, or NULL if no such eventtrigger exists
*/
const eventtrigger* eventtriggerGetByName(const char *name);
/** Trigger the specified event
*
* @param event Pointer to the event with updated payload
*
* event->payload should be filled beforehand with metadata about the event
*/
void eventTrigger(const eventtrigger *event);
/** Register a callback that will be called for enabled events
*
* @param handler unique type of the handler that this callback is for
* @param cb function pointer to the callback
*
* The handler allows multiple event handlers to be triggered by the same event.
* The callback is only called for enabled events.
*/
void eventtriggerRegisterCallback(enum eventtriggerHandler_e handler, eventtriggerCallback cb);
|
vicyor/spike-system | src/main/java/com/vicyor/spike/service/impl/SpikeOrderServiceImpl.java | <reponame>vicyor/spike-system
package com.vicyor.spike.service.impl;
import com.vicyor.spike.entity.SpikeOrder;
import com.vicyor.spike.repository.SpikeOrderRepository;
import com.vicyor.spike.service.SpikeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 作者:姚克威
* 时间:2020/3/3 12:05
**/
@Service
public class SpikeOrderServiceImpl implements SpikeOrderService {
@Autowired
SpikeOrderRepository spikeOrderRepository;
@Override
public void saveSpikeOrder(SpikeOrder order) {
spikeOrderRepository.save(order);
}
@Override
public void finishExpiredOrder(String userId, Long goodsId) {
spikeOrderRepository.updateOrderStatus(userId,goodsId);
}
}
|
degarashi/sprinkler | src/dep_win/ghook/ghook/wevent.cpp | <reponame>degarashi/sprinkler<filename>src/dep_win/ghook/ghook/wevent.cpp
#include "wevent.hpp"
#include <stdexcept>
WEvent::WEvent(LPCTSTR name):
_event(CreateEvent(NULL, FALSE, FALSE, name))
{
if(!_event)
throw std::runtime_error("something wrong(WEvent())");
}
void WEvent::signal() {
if(!SetEvent(_event))
throw std::runtime_error("something wrong(WEvent::signal())");
}
void WEvent::reset() {
if(!ResetEvent(_event))
throw std::runtime_error("something wrong(WEvent::reset())");
}
void WEvent::pulse() {
if(!PulseEvent(_event))
throw std::runtime_error("something wrong(WEvent::pulse())");
}
void WEvent::wait() {
switch(WaitForSingleObject(_event, INFINITE)) {
case WAIT_ABANDONED:
case WAIT_OBJECT_0:
break;
case WAIT_TIMEOUT:
case WAIT_FAILED:
throw std::runtime_error("something wrong(WEvent::wait())");
default:
break;
}
}
HANDLE WEvent::ref() const noexcept {
return _event;
}
WEvent::~WEvent() {
CloseHandle(_event);
}
|
mfloresn90/CSharpSources | Web authentication broker sample/C# and C++/AuthFilters/SwitchableAuthFilter.cpp | #include "pch.h"
#include "OAuth.h"
#include "OAuth2.h"
#include "SwitchableAuthFilter.h"
#include <winerror.h>
#include <ppltasks.h>
#include <collection.h>
using namespace AuthFilters;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Web::Http;
using namespace Windows::Web::Http::Filters;
SwitchableAuthFilter::SwitchableAuthFilter(IHttpFilter^ innerFilter)
{
if (innerFilter == nullptr)
{
throw ref new Exception(E_INVALIDARG, "innerFilter cannot be null.");
}
this->m_InnerFilter = innerFilter;
}
SwitchableAuthFilter::~SwitchableAuthFilter()
{
/*
for (auto v = m_FilterVector.begin(); v != m_FilterVector.end(); v++)
{
(*v)->SetInnerFilter(nullptr);
delete (*v);
}
m_FilterVector.clear();
*/
for (auto m = this->m_FilterMap.begin(); m != this->m_FilterMap.end(); m++)
{
delete m->first;
IHttpFilter^ filter = m->second;
ISetInnerFilter^ setInner = dynamic_cast<ISetInnerFilter^>(filter);
if (setInner != nullptr)
{
setInner->SetInnerFilter(nullptr);
}
delete filter;
}
m_FilterMap.clear();
if (m_InnerFilter != nullptr)
{
delete m_InnerFilter;
m_InnerFilter = nullptr;
}
}
void SwitchableAuthFilter::ClearAll()
{
/*
for (auto i = m_FilterVector.begin(); i != m_FilterVector.end(); i++)
{
(*i)->Clear();
}
*/
for (auto i = m_FilterMap.begin(); i != m_FilterMap.end(); i++)
{
//(*i)->Clear();
auto f1 = dynamic_cast<OAuthFilter^>(i->second);
if (f1 != nullptr)
{
f1->Clear();
}
auto f2 = dynamic_cast<OAuth2Filter^>(i->second);
if (f2 != nullptr)
{
f2->Clear();
}
}
}
void SwitchableAuthFilter::AddOAuthFilter(AuthFilters::OAuthFilter^ newFilter)
{
m_FilterMap[newFilter->AuthConfiguration.ApiUriPrefix] = newFilter;
}
void SwitchableAuthFilter::AddOAuth2Filter(AuthFilters::OAuth2Filter^ newFilter)
{
//m_FilterVector.push_back(newFilter);
m_FilterMap[newFilter->AuthConfiguration.ApiUriPrefix] = newFilter;
}
void SwitchableAuthFilter::AddFilter(Platform::String^ stringToMatch, Windows::Web::Http::Filters::IHttpFilter^ newFilter)
{
m_FilterMap[stringToMatch] = newFilter;
}
IAsyncOperationWithProgress<HttpResponseMessage^, HttpProgress>^ SwitchableAuthFilter::SendRequestAsync(
HttpRequestMessage^ request)
{
if (m_InnerFilter == nullptr)
{
throw ref new Exception(E_INVALIDARG, "innerFilter cannot be set to null.");
}
// Walk the list and pick the right filter
auto requestUri = std::wstring(request->RequestUri->AbsoluteCanonicalUri->Data());
for (auto i = m_FilterMap.begin(); i != m_FilterMap.end(); i++)
{
//auto matchString = std::wstring((*i)->AuthConfiguration.ApiUriPrefix->Data());
auto matchString = std::wstring(i->first->Data());
if (requestUri.compare(0, matchString.size(), matchString) == 0)
{
IHttpFilter^ filter = i->second;
ISetInnerFilter^ setInner = dynamic_cast<ISetInnerFilter^>(filter);
if (setInner != nullptr)
{
setInner->SetInnerFilter(m_InnerFilter);
}
//(*i)->SetInnerFilter (m_InnerFilter);
return filter->SendRequestAsync(request);
}
}
return m_InnerFilter->SendRequestAsync(request);
}
|
bradchesney79/illacceptanything | linux/drivers/scsi/t128.h | /*
* Trantor T128/T128F/T228 defines
* Note : architecturally, the T100 and T128 are different and won't work
*
* Copyright 1993, <NAME>
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* <EMAIL>
* +1 (303) 440-4894
*
* For more information, please consult
*
* Trantor Systems, Ltd.
* T128/T128F/T228 SCSI Host Adapter
* Hardware Specifications
*
* Trantor Systems, Ltd.
* 5415 Randall Place
* Fremont, CA 94538
* 1+ (415) 770-1400, FAX 1+ (415) 770-9910
*/
#ifndef T128_H
#define T128_H
#define TDEBUG 0
#define TDEBUG_INIT 0x1
#define TDEBUG_TRANSFER 0x2
/*
* The trantor boards are memory mapped. They use an NCR5380 or
* equivalent (my sample board had part second sourced from ZILOG).
* NCR's recommended "Pseudo-DMA" architecture is used, where
* a PAL drives the DMA signals on the 5380 allowing fast, blind
* transfers with proper handshaking.
*/
/*
* Note : a boot switch is provided for the purpose of informing the
* firmware to boot or not boot from attached SCSI devices. So, I imagine
* there are fewer people who've yanked the ROM like they do on the Seagate
* to make bootup faster, and I'll probably use this for autodetection.
*/
#define T_ROM_OFFSET 0
/*
* Note : my sample board *WAS NOT* populated with the SRAM, so this
* can't be used for autodetection without a ROM present.
*/
#define T_RAM_OFFSET 0x1800
/*
* All of the registers are allocated 32 bytes of address space, except
* for the data register (read/write to/from the 5380 in pseudo-DMA mode)
*/
#define T_CONTROL_REG_OFFSET 0x1c00 /* rw */
#define T_CR_INT 0x10 /* Enable interrupts */
#define T_CR_CT 0x02 /* Reset watchdog timer */
#define T_STATUS_REG_OFFSET 0x1c20 /* ro */
#define T_ST_BOOT 0x80 /* Boot switch */
#define T_ST_S3 0x40 /* User settable switches, */
#define T_ST_S2 0x20 /* read 0 when switch is on, 1 off */
#define T_ST_S1 0x10
#define T_ST_PS2 0x08 /* Set for Microchannel 228 */
#define T_ST_RDY 0x04 /* 5380 DRQ */
#define T_ST_TIM 0x02 /* indicates 40us watchdog timer fired */
#define T_ST_ZERO 0x01 /* Always zero */
#define T_5380_OFFSET 0x1d00 /* 8 registers here, see NCR5380.h */
#define T_DATA_REG_OFFSET 0x1e00 /* rw 512 bytes long */
#ifndef ASM
#ifndef CMD_PER_LUN
#define CMD_PER_LUN 2
#endif
#ifndef CAN_QUEUE
#define CAN_QUEUE 32
#endif
#define NCR5380_implementation_fields \
void __iomem *base
#define NCR5380_local_declare() \
void __iomem *base
#define NCR5380_setup(instance) \
base = ((struct NCR5380_hostdata *)(instance->hostdata))->base
#define T128_address(reg) (base + T_5380_OFFSET + ((reg) * 0x20))
#if !(TDEBUG & TDEBUG_TRANSFER)
#define NCR5380_read(reg) readb(T128_address(reg))
#define NCR5380_write(reg, value) writeb((value),(T128_address(reg)))
#else
#define NCR5380_read(reg) \
(((unsigned char) printk("scsi%d : read register %d at address %08x\n"\
, instance->hostno, (reg), T128_address(reg))), readb(T128_address(reg)))
#define NCR5380_write(reg, value) { \
printk("scsi%d : write %02x to register %d at address %08x\n", \
instance->hostno, (value), (reg), T128_address(reg)); \
writeb((value), (T128_address(reg))); \
}
#endif
#define NCR5380_intr t128_intr
#define do_NCR5380_intr do_t128_intr
#define NCR5380_queue_command t128_queue_command
#define NCR5380_abort t128_abort
#define NCR5380_bus_reset t128_bus_reset
#define NCR5380_info t128_info
#define NCR5380_show_info t128_show_info
#define NCR5380_write_info t128_write_info
/* 15 14 12 10 7 5 3
1101 0100 1010 1000 */
#define T128_IRQS 0xc4a8
#endif /* ndef ASM */
#endif /* T128_H */
|
wxmerkt/ihmc-open-robotics-software | IHMCRoboticsToolkit/src/us/ihmc/robotics/screwTheory/GeometricJacobian.java | package us.ihmc.robotics.screwTheory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;
import us.ihmc.robotics.geometry.ReferenceFrameMismatchException;
import us.ihmc.robotics.nameBasedHashCode.NameBasedHashCodeHolder;
import us.ihmc.robotics.referenceFrames.ReferenceFrame;
/**
* This class provides a simple tool to compute the Jacobian matrix
* of a kinematic chain composed of {@link InverseDynamicsJoint}s.
* <p>
* To use this tool, one can create an object by using the constructor
* {@link #GeometricJacobian(RigidBody, RigidBody, ReferenceFrame)}.
* The Jacobian computed will include all the joints from {@code ancestor}
* to {@code descendant} and will be expressed in {@code jacobianFrame}.
* Then the method {@link #compute()} is to be called every time the
* joint configuration has changed and Jacobian matrix is to be updated.
* Finally several options are offered on how to use the Jacobian matrix:
* <ul>
* <li> {@link #getJacobianMatrix()} can be used to get the reference to
* the raw matrix can be used to then perform external operations with it
* using the third-party library EJML.
* <li> {@link #computeJointTorques(Wrench, DenseMatrix64F)} computes
* the joint torques necessary to achieve a given {@code Wrench} at the
* end-effector or descendant of this Jacobian. It uses the relation:
* <br> τ = J<sup>T</sup> * W </br>
* with τ being the joint torques, J the Jacobian matrix, and
* W the wrench to exert at the end-effector.
* </ul>
* </p>
*/
public class GeometricJacobian implements NameBasedHashCodeHolder
{
/** Array of the joints to be considered by this Jacobian. */
private final InverseDynamicsJoint[] joints;
/**
* Array of ALL the joints from the base to the end effector of this Jacobian.
* This is useful in {@link ConvectiveTermCalculator} when the list of joints
* of the Jacobian is not continuous.
*/
private final InverseDynamicsJoint[] jointPathFromBaseToEndEffector;
private final LinkedHashMap<InverseDynamicsJoint, List<Twist>> unitTwistMap;
private final List<Twist> unitTwistList;
private final DenseMatrix64F jacobian;
private ReferenceFrame jacobianFrame;
// Temporary variables
private final Twist tempTwist = new Twist();
private final DenseMatrix64F tempMatrix = new DenseMatrix64F(Twist.SIZE, 1);
private final boolean allowChangeFrame;
private final long nameBasedHashCode;
/**
* Creates a new Jacobian for the open loop chain described by the ordered keys of {@code unitTwists}.
*
* @param unitTwists an ordered list of relative joint twists.
* The order in which the twists are ordered will correspond to the order of the columns in the Jacobian
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @param allowChangeFrame whether the feature {@link #changeFrame(ReferenceFrame)} will be available or not.
* @throws RuntimeException if the joint ordering is incorrect.
*/
private GeometricJacobian(LinkedHashMap<InverseDynamicsJoint, List<Twist>> unitTwists, ReferenceFrame jacobianFrame, boolean allowChangeFrame)
{
this.joints = new InverseDynamicsJoint[unitTwists.size()];
unitTwists.keySet().toArray(joints);
this.unitTwistMap = unitTwists;
this.unitTwistList = extractUnitTwistList(unitTwists);
this.jacobianFrame = jacobianFrame;
this.jacobian = createJacobianMatrix(this.unitTwistMap);
this.jointPathFromBaseToEndEffector = ScrewTools.createJointPath(getBase(), getEndEffector());
this.allowChangeFrame = allowChangeFrame;
nameBasedHashCode = ScrewTools.computeGeometricJacobianNameBasedHashCode(joints, jacobianFrame, allowChangeFrame);
}
/**
* Constructor for internal usage of the screw theory library.
* <p>
* Creates a new Jacobian representing the motion subspace of the given joint.
* </p>
*
* @param joint the joint for which the motion subspace is to be created.
* @param unitTwists the list of unitary twists representing the degrees of freedom of {@code joint}.
* For instance, the unit twist of a {@link RevoluteJoint} around the y-axis is: T<sub>u</sub> = [0 1 0 0 0 0]<sup>T</sup>.
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @throws RuntimeException if the joint ordering is incorrect.
*/
public GeometricJacobian(InverseDynamicsJoint joint, List<Twist> unitTwists, ReferenceFrame jacobianFrame)
{
this(createUnitTwistMap(joint, unitTwists), jacobianFrame, true);
}
/**
* Creates a new Jacobian for the kinematic starting from {@code ancestor} and ending at {@code descendant}.
*
* @param ancestor the predecessor of the first joint considered by this Jacobian.
* @param descendant the successor of the last joint considered by this Jacobian.
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @throws RuntimeException if the joint ordering is incorrect.
*/
public GeometricJacobian(RigidBody ancestor, RigidBody descendant, ReferenceFrame jacobianFrame)
{
this(ScrewTools.createJointPath(ancestor, descendant), jacobianFrame, true);
}
/**
* Creates the Jacobian for the kinematic chain described by the given joints.
* These joints have to be ordered and going downstream (the first joint has to be the closest joint
* to the root of the system and the last the farthest).
*
* @param joints the joints that this Jacobian considers.
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @throws RuntimeException if the joint ordering is incorrect.
*/
public GeometricJacobian(InverseDynamicsJoint[] joints, ReferenceFrame jacobianFrame)
{
this(extractTwistsFromJoints(joints), jacobianFrame, true);
}
/**
* Creates the Jacobian for the kinematic chain described by the given joints.
* These joints have to be ordered and going downstream (the first joint has to be the closest joint
* to the root of the system and the last the farthest).
*
* @param joints the joints that this Jacobian considers.
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @param allowChangeFrame whether the feature {@link #changeFrame(ReferenceFrame)} will be available or not.
* @throws RuntimeException if the joint ordering is incorrect.
*/
public GeometricJacobian(InverseDynamicsJoint[] joints, ReferenceFrame jacobianFrame, boolean allowChangeFrame)
{
this(extractTwistsFromJoints(joints), jacobianFrame, allowChangeFrame);
}
/**
* Creates a new Jacobian representing one joint.
*
* @param joint the joint that this Jacobian considers.
* @param jacobianFrame the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* @throws RuntimeException if the joint ordering is incorrect.
*/
public GeometricJacobian(InverseDynamicsJoint joint, ReferenceFrame jacobianFrame)
{
this(joint, joint.getMotionSubspace().getAllUnitTwists(), jacobianFrame);
}
/**
* Computes the Jacobian.
*/
public void compute()
{
int column = 0;
for (int i = 0; i < unitTwistList.size(); i++)
{
Twist twist = unitTwistList.get(i);
tempTwist.set(twist);
tempTwist.changeFrame(jacobianFrame);
tempTwist.getMatrix(tempMatrix, 0);
CommonOps.extract(tempMatrix, 0, tempMatrix.getNumRows(), 0, tempMatrix.getNumCols(), jacobian, 0, column++);
}
}
/**
* Changes the frame in which the resulting twist of the end effector with respect to the base frame will be expressed.
* The boolean {@code allowChangeFrame} has to be initialize to {@code true} at construction time.
*
* @param jacobianFrame the new frame of this Jacobian.
* @throws RuntimeException if this feature is not enabled.
*/
public void changeFrame(ReferenceFrame jacobianFrame)
{
if (!allowChangeFrame)
throw new RuntimeException("Cannot change the frame of this Jacobian.");
this.jacobianFrame = jacobianFrame;
}
/**
* Computes and packs the twist that corresponds to the given joint velocity vector.
*
* @param jointVelocities the joint velocity column vector.
* The vector should have the same ordering as the unit twists of the ordered joint list of this Jacobian
* that were passed in during construction.
* @return the twist of the end effector with respect to the base, expressed in the jacobianFrame.
*/
public void getTwist(DenseMatrix64F jointVelocities, Twist twistToPack)
{
CommonOps.mult(jacobian, jointVelocities, tempMatrix);
twistToPack.set(getEndEffectorFrame(), getBaseFrame(), jacobianFrame, tempMatrix, 0);
}
/**
* Computes and returns the joint torque vector that corresponds to the given wrench.
*
* @param wrench the resulting wrench at the end effector.
* The wrench should be expressed in {@code jacobianFrame} and the wrench's {@code bodyFrame}
* should be the body fixed frame of the end-effector.
* @return joint torques that result in the given wrench as a column vector.
* @throws ReferenceFrameMismatchException if the given wrench
* {@code wrench.getExpressedInFrame() != this.getJacobianFrame()} or
* {@code wrench.getBodyFrame() != this.getEndEffectorFrame()}.
*/
public DenseMatrix64F computeJointTorques(Wrench wrench)
{
DenseMatrix64F jointTorques = new DenseMatrix64F(1, jacobian.getNumCols());
computeJointTorques(wrench, jointTorques);
return jointTorques;
}
/**
* Computes and packs the joint torque vector that corresponds to the given wrench.
*
* @param wrench the resulting wrench at the end effector.
* The wrench should be expressed in {@code jacobianFrame} and the wrench's {@code bodyFrame}
* should be the body fixed frame of the end-effector.
* @throws ReferenceFrameMismatchException if the given wrench {@code wrench.getExpressedInFrame() != this.getJacobianFrame()} or
* {@code wrench.getBodyFrame() != this.getEndEffectorFrame()}.
*/
public void computeJointTorques(Wrench wrench, DenseMatrix64F jointTorquesToPack)
{
// reference frame check
wrench.getExpressedInFrame().checkReferenceFrameMatch(this.jacobianFrame);
// FIXME add the following reference frame check
// wrench.getBodyFrame().checkReferenceFrameMatch(getEndEffectorFrame());
wrench.getMatrix(tempMatrix);
jointTorquesToPack.reshape(1, jacobian.getNumCols());
CommonOps.multTransA(tempMatrix, jacobian, jointTorquesToPack);
CommonOps.transpose(jointTorquesToPack);
}
/**
* Returns a reference to the underlying {@code DenseMatrix64F} object. Does not recompute the Jacobian.
*
* @return a reference to the underlying {@code DenseMatrix64F} object
*/
public DenseMatrix64F getJacobianMatrix()
{
return jacobian;
}
/**
* @return the determinant of the Jacobian matrix
*/
public double det()
{
return CommonOps.det(jacobian);
}
/**
* Returns one entry from the Jacobian matrix. Does not recompute the Jacobian.
*
* @param row the desired row of the Jacobian
* @param column the desired column of the Jacobian
* @return the entry at (row, column)
*/
public double getJacobianEntry(int row, int column)
{
return jacobian.get(row, column);
}
/**
* @return the number of columns in the Jacobian matrix
*/
public int getNumberOfColumns()
{
return jacobian.getNumCols();
}
/**
* @return the frame in which this Jacobian is expressed
*/
public ReferenceFrame getJacobianFrame()
{
return jacobianFrame;
}
/** @return an {@code Array} containing the joints considered by this Jacobian. */
public InverseDynamicsJoint[] getJointsInOrder()
{
return joints;
}
/** @return a {@code Array} of joints describing a continuous path from the base to the end effector of this Jacobian. */
public InverseDynamicsJoint[] getJointPathFromBaseToEndEffector()
{
return jointPathFromBaseToEndEffector;
}
/**
* Returns the base {@code RigidBody} of this Jacobian.
* The base is the predecessor of the first joint that this Jacobian considers.
*
* @return the base of this Jacobian.
*/
public RigidBody getBase()
{
return joints[0].getPredecessor();
}
/**
* Returns the end-effector {@code RigidBody} of this Jacobian.
* The end-effector is the successor of the last joint this Jacobian considers.
*
* @return the end-effector of this jacobian.
*/
public RigidBody getEndEffector()
{
return joints[joints.length - 1].getSuccessor();
}
/**
* Returns the body fixed frame of the base {@code RigidBody} of this Jacobian.
* The base is the predecessor of the first joint that this Jacobian considers.
*
* @return the body fixed frame of the base.
*/
public ReferenceFrame getBaseFrame()
{
return getBase().getBodyFixedFrame();
}
/**
* Returns the body fixed frame of the end-effector {@code RigidBody} of this Jacobian.
* The end-effector is the successor of the last joint this Jacobian considers.
*
* @return the body fixed frame of the end-effector.
*/
public ReferenceFrame getEndEffectorFrame()
{
return getEndEffector().getBodyFixedFrame();
}
// default access for efficiency
List<Twist> getAllUnitTwists()
{
return unitTwistList;
}
private static LinkedHashMap<InverseDynamicsJoint, List<Twist>> extractTwistsFromJoints(InverseDynamicsJoint[] joints)
{
checkJointOrder(joints);
LinkedHashMap<InverseDynamicsJoint, List<Twist>> ret = new LinkedHashMap<InverseDynamicsJoint, List<Twist>>();
for (int i = 0; i < joints.length; i++)
{
InverseDynamicsJoint joint = joints[i];
ret.put(joint, joint.getMotionSubspace().unitTwistMap.get(joint));
}
return ret;
}
private static void checkJointOrder(InverseDynamicsJoint[] joints)
{
for (int i = 1; i < joints.length; i++)
{
InverseDynamicsJoint joint = joints[i];
InverseDynamicsJoint previousJoint = joints[i - 1];
if (ScrewTools.isAncestor(previousJoint.getPredecessor(), joint.getPredecessor()))
throw new RuntimeException("joints must be in order from ancestor to descendant");
}
}
private List<Twist> extractUnitTwistList(LinkedHashMap<InverseDynamicsJoint, List<Twist>> unitTwistMap)
{
int size = 0;
for (List<Twist> twistList : unitTwistMap.values())
{
size += twistList.size();
}
List<Twist> ret = new ArrayList<Twist>(size);
for (List<Twist> twistList : unitTwistMap.values())
{
for (int i = 0; i < twistList.size(); i++)
{
ret.add(twistList.get(i));
}
}
return ret;
}
private static LinkedHashMap<InverseDynamicsJoint, List<Twist>> createUnitTwistMap(InverseDynamicsJoint joint, List<Twist> unitTwists)
{
LinkedHashMap<InverseDynamicsJoint, List<Twist>> ret = new LinkedHashMap<InverseDynamicsJoint, List<Twist>>(1);
ret.put(joint, unitTwists);
return ret;
}
private static DenseMatrix64F createJacobianMatrix(LinkedHashMap<InverseDynamicsJoint, List<Twist>> unitTwists)
{
return new DenseMatrix64F(SpatialMotionVector.SIZE, ScrewTools.computeDegreesOfFreedom(unitTwists.keySet()));
}
/**
* Creates a descriptive {@code String} for this Jacobian containing
* information such as the {@code jacobianFrame}, the list of the joint names,
* and the current value of the Jacobian matrix.
*
* @return a descriptive {@code String} for this Jacobian.
*/
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("Jacobian. jacobianFrame = " + jacobianFrame + ". Joints:\n");
for (InverseDynamicsJoint joint : unitTwistMap.keySet())
{
builder.append(joint.getClass().getSimpleName() + " " + joint.getName() + "\n");
}
builder.append("\n");
builder.append(jacobian.toString());
return builder.toString();
}
public String getShortInfo()
{
return "Jacobian, end effector = " + getEndEffector() + ", base = " + getBase() + ", expressed in " + getJacobianFrame();
}
@Override
public long nameBasedHashCode()
{
return nameBasedHashCode;
}
}
|
vimofthevine/underbudget4 | webapp/src/common/components/PureFab/PureFab.stories.js | import AddIcon from '@material-ui/icons/Add';
import { action } from '@storybook/addon-actions';
import React from 'react';
import PureFab from './PureFab';
export default {
title: 'common/PureFab',
component: PureFab,
};
const Template = (args) => <PureFab {...args} />;
export const PrimaryColor = Template.bind({});
PrimaryColor.args = {
action: {
'aria-label': 'add item',
icon: <AddIcon />,
onClick: action('click'),
text: 'Add item',
},
};
export const SecondaryColor = Template.bind({});
SecondaryColor.args = {
...PrimaryColor.args,
color: 'secondary',
};
|
mtezych/cpp | vulkan/source/RenderPass.cpp | <filename>vulkan/source/RenderPass.cpp
#include <vulkan/RenderPass.h>
#include <vulkan/Device.h>
#include <cassert>
namespace vk
{
RenderPass::RenderPass
(
const Device& device,
const std::vector<VkAttachmentDescription>& attachments,
const std::vector<VkSubpassDescription>& subpasses,
const std::vector<VkSubpassDependency>& dependencies
):
device { &device },
vkRenderPass { VK_NULL_HANDLE }
{
const auto createInfo = VkRenderPassCreateInfo
{
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
nullptr,
0,
uint32_t ( attachments.size() ), attachments.data(),
uint32_t ( subpasses.size() ), subpasses.data(),
uint32_t ( dependencies.size() ), dependencies.data(),
};
const auto result = device.vkCreateRenderPass
(
device.vkDevice,
&createInfo,
nullptr,
&vkRenderPass
);
assert(result == VK_SUCCESS);
}
RenderPass::~RenderPass ()
{
if (vkRenderPass != VK_NULL_HANDLE)
{
device->vkDestroyRenderPass(device->vkDevice, vkRenderPass, nullptr);
}
}
RenderPass::RenderPass (RenderPass&& renderPass)
:
device { renderPass.device },
vkRenderPass { renderPass.vkRenderPass }
{
renderPass.device = nullptr;
renderPass.vkRenderPass = VK_NULL_HANDLE;
}
RenderPass& RenderPass::operator = (RenderPass&& renderPass)
{
if (vkRenderPass != VK_NULL_HANDLE)
{
device->vkDestroyRenderPass(device->vkDevice, vkRenderPass, nullptr);
}
device = renderPass.device;
vkRenderPass = renderPass.vkRenderPass;
renderPass.device = nullptr;
renderPass.vkRenderPass = VK_NULL_HANDLE;
return *this;
}
}
|
vitorsouza/FrameWeb-Martins-2015 | core/plugins/codegenerator/br.ufes.inf.nemo.frameweb.codegenerator.e4/src/br/ufes/inf/nemo/frameweb/codegenerator/e4/models/ApplicationModelCodeGenerator.java | <filename>core/plugins/codegenerator/br.ufes.inf.nemo.frameweb.codegenerator.e4/src/br/ufes/inf/nemo/frameweb/codegenerator/e4/models/ApplicationModelCodeGenerator.java
package br.ufes.inf.nemo.frameweb.codegenerator.e4.models;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import br.ufes.inf.nemo.frameweb.codegenerator.e4.ProjectProperties;
import br.ufes.inf.nemo.frameweb.codegenerator.e4.classes.ClassCodeGenerator;
import br.ufes.inf.nemo.frameweb.model.frameweb.ApplicationModel;
import br.ufes.inf.nemo.frameweb.model.frameweb.ApplicationPackage;
import br.ufes.inf.nemo.frameweb.model.frameweb.AuthServiceClass;
import br.ufes.inf.nemo.frameweb.model.frameweb.AuthServiceInterface;
import br.ufes.inf.nemo.frameweb.model.frameweb.DITemplate;
import br.ufes.inf.nemo.frameweb.model.frameweb.ServiceClass;
import br.ufes.inf.nemo.frameweb.model.frameweb.ServiceInterface;
import br.ufes.inf.nemo.frameweb.model.frameweb.ServiceMethod;
import br.ufes.inf.nemo.frameweb.utils.IFileUtils;
import br.ufes.inf.nemo.frameweb.utils.IFolderUtils;
public class ApplicationModelCodeGenerator implements ModelCodeGenerator {
private List<ApplicationPackage> applicationPackages;
private DITemplate diTemplate;
private ProjectProperties projectConfiguration;
public ApplicationModelCodeGenerator(ApplicationModel applicationModel, DITemplate diTemplate, ProjectProperties projectConfiguration) {
applicationPackages = applicationModel.getOwnedElements()
.stream()
.filter(ApplicationPackage.class::isInstance)
.map(ApplicationPackage.class::cast)
.collect(Collectors.toList());
this.diTemplate = diTemplate;
this.projectConfiguration = projectConfiguration;
}
@Override
public void generate() {
String templatePath = diTemplate.getClassTemplate();
String template = projectConfiguration.getTemplate(templatePath);
String interfaceTemplatePath = diTemplate.getInterfaceTemplate();
String interfaceTemplate = projectConfiguration.getTemplate(interfaceTemplatePath);
String authTemplatePath = diTemplate.getAuthClassTemplate();
String authTemplate = projectConfiguration.getTemplate(authTemplatePath);
String authInterfaceTemplatePath = diTemplate.getAuthInterfaceTemplate();
String authInterfaceTemplate = projectConfiguration.getTemplate(authInterfaceTemplatePath);
IFolder src = projectConfiguration.getSourceFolder();
applicationPackages.forEach(applicationPackage -> {
String packagePath = IFolderUtils.packageNameToPath(applicationPackage.getName());
IFolderUtils.makeDirectory(src, packagePath);
IFolder package_ = src.getFolder(packagePath);
applicationPackage.getOwnedTypes()
.stream()
.filter(ServiceClass.class::isInstance)
.map(ServiceClass.class::cast)
.forEach(serviceClass -> {
String code = ClassCodeGenerator.render(serviceClass, template);
String fileName = serviceClass.getName() + projectConfiguration.getClassExtension();
IFile file = package_.getFile(fileName);
IFileUtils.createFile(file, code);
});
applicationPackage.getOwnedTypes()
.stream()
.filter(ServiceInterface.class::isInstance)
.map(ServiceInterface.class::cast)
.forEach(serviceInterface -> {
// FIXME a busca deve ser feita pela realizacao, mas como ela nao funciona no editor grafico, nao pode ser resgatada.
// Aqui sera feita por meio de nomes. Isso e errado! As realizacoes devem ser consertadas para que isso funcione adequadamente.
List<ServiceClass> serviceClasses = applicationPackage.getOwnedTypes()
.stream()
.filter(ServiceClass.class::isInstance)
.map(ServiceClass.class::cast)
.collect(Collectors.toList());
List<ServiceMethod> serviceMethods = new ArrayList<ServiceMethod>();
for (ServiceClass serviceClass : serviceClasses) {
if (serviceClass.getName().contains(serviceInterface.getName()) || serviceInterface.getName().contains(serviceClass.getName())) {
serviceMethods.addAll(serviceClass.getOperations()
.stream()
.filter(ServiceMethod.class::isInstance)
.map(ServiceMethod.class::cast)
.collect(Collectors.toList()));
break;
}
}
String code = ClassCodeGenerator.render(serviceInterface, serviceMethods, interfaceTemplate);
String fileName = serviceInterface.getName() + projectConfiguration.getClassExtension();
IFile file = package_.getFile(fileName);
IFileUtils.createFile(file, code);
});
// authservice
applicationPackage.getOwnedTypes()
.stream()
.filter(AuthServiceClass.class::isInstance)
.map(AuthServiceClass.class::cast)
.forEach(authServiceClass -> {
String code = ClassCodeGenerator.render(authServiceClass, authTemplate);
String fileName = authServiceClass.getName() + projectConfiguration.getClassExtension();
IFile file = package_.getFile(fileName);
IFileUtils.createFile(file, code);
});
applicationPackage.getOwnedTypes()
.stream()
.filter(AuthServiceInterface.class::isInstance)
.map(AuthServiceInterface.class::cast)
.forEach(authServiceInterface -> {
// FIXME a busca deve ser feita pela realizacao, mas como ela nao funciona no editor grafico, nao pode ser resgatada.
// Aqui sera feita por meio de nomes. Isso e errado! As realizacoes devem ser consertadas para que isso funcione adequadamente.
List<AuthServiceClass> authServiceClasses = applicationPackage.getOwnedTypes()
.stream()
.filter(AuthServiceClass.class::isInstance)
.map(AuthServiceClass.class::cast)
.collect(Collectors.toList());
List<ServiceMethod> serviceMethods = new ArrayList<ServiceMethod>();
for (ServiceClass serviceClass : authServiceClasses) {
if (serviceClass.getName().contains(authServiceInterface.getName()) || authServiceInterface.getName().contains(serviceClass.getName())) {
serviceMethods.addAll(serviceClass.getOperations()
.stream()
.filter(ServiceMethod.class::isInstance)
.map(ServiceMethod.class::cast)
.collect(Collectors.toList()));
break;
}
}
String code = ClassCodeGenerator.render(authServiceInterface, serviceMethods, authInterfaceTemplate);
String fileName = authServiceInterface.getName() + projectConfiguration.getClassExtension();
IFile file = package_.getFile(fileName);
IFileUtils.createFile(file, code);
});
});
}
}
|
jaylinjiehong/NumberOfPasses | Android/android-30/android30_code_view/src/com/company/source/com/android/launcher3/icons/cache/BaseIconCache.java | <filename>Android/android-30/android30_code_view/src/com/company/source/com/android/launcher3/icons/cache/BaseIconCache.java
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.icons.cache;
import static com.android.launcher3.icons.BaseIconFactory.getFullResDefaultActivityIcon;
import static com.android.launcher3.icons.BitmapInfo.LOW_RES_ICON;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.os.Process;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.icons.GraphicsUtils;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.SQLiteCacheHelper;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
public abstract class BaseIconCache {
private static final String TAG = "BaseIconCache";
private static final boolean DEBUG = false;
private static final int INITIAL_ICON_CACHE_CAPACITY = 50;
// Empty class name is used for storing package default entry.
public static final String EMPTY_CLASS_NAME = ".";
public static class CacheEntry {
@NonNull
public BitmapInfo bitmap = BitmapInfo.LOW_RES_INFO;
public CharSequence title = "";
public CharSequence contentDescription = "";
}
private final HashMap<UserHandle, BitmapInfo> mDefaultIcons = new HashMap<>();
protected final Context mContext;
protected final PackageManager mPackageManager;
private final Map<ComponentKey, CacheEntry> mCache;
protected final Handler mWorkerHandler;
protected int mIconDpi;
protected IconDB mIconDb;
protected LocaleList mLocaleList = LocaleList.getEmptyLocaleList();
protected String mSystemState = "";
private final String mDbFileName;
private final BitmapFactory.Options mDecodeOptions;
private final Looper mBgLooper;
public BaseIconCache(Context context, String dbFileName, Looper bgLooper,
int iconDpi, int iconPixelSize, boolean inMemoryCache) {
mContext = context;
mDbFileName = dbFileName;
mPackageManager = context.getPackageManager();
mBgLooper = bgLooper;
mWorkerHandler = new Handler(mBgLooper);
if (inMemoryCache) {
mCache = new HashMap<>(INITIAL_ICON_CACHE_CAPACITY);
} else {
// Use a dummy cache
mCache = new AbstractMap<ComponentKey, CacheEntry>() {
@Override
public Set<Entry<ComponentKey, CacheEntry>> entrySet() {
return Collections.emptySet();
}
@Override
public CacheEntry put(ComponentKey key, CacheEntry value) {
return value;
}
};
}
if (BitmapRenderer.USE_HARDWARE_BITMAP && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mDecodeOptions = new BitmapFactory.Options();
mDecodeOptions.inPreferredConfig = Bitmap.Config.HARDWARE;
} else {
mDecodeOptions = null;
}
updateSystemState();
mIconDpi = iconDpi;
mIconDb = new IconDB(context, dbFileName, iconPixelSize);
}
/**
* Returns the persistable serial number for {@param user}. Subclass should implement proper
* caching strategy to avoid making binder call every time.
*/
protected abstract long getSerialNumberForUser(UserHandle user);
/**
* Return true if the given app is an instant app and should be badged appropriately.
*/
protected abstract boolean isInstantApp(ApplicationInfo info);
/**
* Opens and returns an icon factory. The factory is recycled by the caller.
*/
protected abstract BaseIconFactory getIconFactory();
public void updateIconParams(int iconDpi, int iconPixelSize) {
mWorkerHandler.post(() -> updateIconParamsBg(iconDpi, iconPixelSize));
}
private synchronized void updateIconParamsBg(int iconDpi, int iconPixelSize) {
mIconDpi = iconDpi;
mDefaultIcons.clear();
mIconDb.clear();
mIconDb.close();
mIconDb = new IconDB(mContext, mDbFileName, iconPixelSize);
mCache.clear();
}
private Drawable getFullResIcon(Resources resources, int iconId) {
if (resources != null && iconId != 0) {
try {
return resources.getDrawableForDensity(iconId, mIconDpi);
} catch (Resources.NotFoundException e) { }
}
return getFullResDefaultActivityIcon(mIconDpi);
}
public Drawable getFullResIcon(String packageName, int iconId) {
try {
return getFullResIcon(mPackageManager.getResourcesForApplication(packageName), iconId);
} catch (PackageManager.NameNotFoundException e) { }
return getFullResDefaultActivityIcon(mIconDpi);
}
public Drawable getFullResIcon(ActivityInfo info) {
try {
return getFullResIcon(mPackageManager.getResourcesForApplication(info.applicationInfo),
info.getIconResource());
} catch (PackageManager.NameNotFoundException e) { }
return getFullResDefaultActivityIcon(mIconDpi);
}
private BitmapInfo makeDefaultIcon(UserHandle user) {
try (BaseIconFactory li = getIconFactory()) {
return li.makeDefaultIcon(user);
}
}
/**
* Remove any records for the supplied ComponentName.
*/
public synchronized void remove(ComponentName componentName, UserHandle user) {
mCache.remove(new ComponentKey(componentName, user));
}
/**
* Remove any records for the supplied package name from memory.
*/
private void removeFromMemCacheLocked(String packageName, UserHandle user) {
HashSet<ComponentKey> forDeletion = new HashSet<>();
for (ComponentKey key: mCache.keySet()) {
if (key.componentName.getPackageName().equals(packageName)
&& key.user.equals(user)) {
forDeletion.add(key);
}
}
for (ComponentKey condemned: forDeletion) {
mCache.remove(condemned);
}
}
/**
* Removes the entries related to the given package in memory and persistent DB.
*/
public synchronized void removeIconsForPkg(String packageName, UserHandle user) {
removeFromMemCacheLocked(packageName, user);
long userSerial = getSerialNumberForUser(user);
mIconDb.delete(
IconDB.COLUMN_COMPONENT + " LIKE ? AND " + IconDB.COLUMN_USER + " = ?",
new String[]{packageName + "/%", Long.toString(userSerial)});
}
public IconCacheUpdateHandler getUpdateHandler() {
updateSystemState();
return new IconCacheUpdateHandler(this);
}
/**
* Refreshes the system state definition used to check the validity of the cache. It
* incorporates all the properties that can affect the cache like the list of enabled locale
* and system-version.
*/
private void updateSystemState() {
mLocaleList = mContext.getResources().getConfiguration().getLocales();
mSystemState = mLocaleList.toLanguageTags() + "," + Build.VERSION.SDK_INT;
}
protected String getIconSystemState(String packageName) {
return mSystemState;
}
/**
* Adds an entry into the DB and the in-memory cache.
* @param replaceExisting if true, it will recreate the bitmap even if it already exists in
* the memory. This is useful then the previous bitmap was created using
* old data.
*/
@VisibleForTesting
public synchronized <T> void addIconToDBAndMemCache(T object, CachingLogic<T> cachingLogic,
PackageInfo info, long userSerial, boolean replaceExisting) {
UserHandle user = cachingLogic.getUser(object);
ComponentName componentName = cachingLogic.getComponent(object);
final ComponentKey key = new ComponentKey(componentName, user);
CacheEntry entry = null;
if (!replaceExisting) {
entry = mCache.get(key);
// We can't reuse the entry if the high-res icon is not present.
if (entry == null || entry.bitmap.isNullOrLowRes()) {
entry = null;
}
}
if (entry == null) {
entry = new CacheEntry();
entry.bitmap = cachingLogic.loadIcon(mContext, object);
}
// Icon can't be loaded from cachingLogic, which implies alternative icon was loaded
// (e.g. fallback icon, default icon). So we drop here since there's no point in caching
// an empty entry.
if (entry.bitmap.isNullOrLowRes()) return;
entry.title = cachingLogic.getLabel(object);
entry.contentDescription = mPackageManager.getUserBadgedLabel(entry.title, user);
if (cachingLogic.addToMemCache()) mCache.put(key, entry);
ContentValues values = newContentValues(entry.bitmap, entry.title.toString(),
componentName.getPackageName(), cachingLogic.getKeywords(object, mLocaleList));
addIconToDB(values, componentName, info, userSerial,
cachingLogic.getLastUpdatedTime(object, info));
}
/**
* Updates {@param values} to contain versioning information and adds it to the DB.
* @param values {@link ContentValues} containing icon & title
*/
private void addIconToDB(ContentValues values, ComponentName key,
PackageInfo info, long userSerial, long lastUpdateTime) {
values.put(IconDB.COLUMN_COMPONENT, key.flattenToString());
values.put(IconDB.COLUMN_USER, userSerial);
values.put(IconDB.COLUMN_LAST_UPDATED, lastUpdateTime);
values.put(IconDB.COLUMN_VERSION, info.versionCode);
mIconDb.insertOrReplace(values);
}
public synchronized BitmapInfo getDefaultIcon(UserHandle user) {
if (!mDefaultIcons.containsKey(user)) {
mDefaultIcons.put(user, makeDefaultIcon(user));
}
return mDefaultIcons.get(user);
}
public boolean isDefaultIcon(BitmapInfo icon, UserHandle user) {
return getDefaultIcon(user).icon == icon.icon;
}
/**
* Retrieves the entry from the cache. If the entry is not present, it creates a new entry.
* This method is not thread safe, it must be called from a synchronized method.
*/
protected <T> CacheEntry cacheLocked(
@NonNull ComponentName componentName, @NonNull UserHandle user,
@NonNull Supplier<T> infoProvider, @NonNull CachingLogic<T> cachingLogic,
boolean usePackageIcon, boolean useLowResIcon) {
assertWorkerThread();
ComponentKey cacheKey = new ComponentKey(componentName, user);
CacheEntry entry = mCache.get(cacheKey);
if (entry == null || (entry.bitmap.isLowRes() && !useLowResIcon)) {
entry = new CacheEntry();
if (cachingLogic.addToMemCache()) {
mCache.put(cacheKey, entry);
}
// Check the DB first.
T object = null;
boolean providerFetchedOnce = false;
if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
object = infoProvider.get();
providerFetchedOnce = true;
if (object != null) {
entry.bitmap = cachingLogic.loadIcon(mContext, object);
} else {
if (usePackageIcon) {
CacheEntry packageEntry = getEntryForPackageLocked(
componentName.getPackageName(), user, false);
if (packageEntry != null) {
if (DEBUG) Log.d(TAG, "using package default icon for " +
componentName.toShortString());
entry.bitmap = packageEntry.bitmap;
entry.title = packageEntry.title;
entry.contentDescription = packageEntry.contentDescription;
}
}
if (entry.bitmap == null) {
if (DEBUG) Log.d(TAG, "using default icon for " +
componentName.toShortString());
entry.bitmap = getDefaultIcon(user);
}
}
}
if (TextUtils.isEmpty(entry.title)) {
if (object == null && !providerFetchedOnce) {
object = infoProvider.get();
providerFetchedOnce = true;
}
if (object != null) {
entry.title = cachingLogic.getLabel(object);
entry.contentDescription = mPackageManager.getUserBadgedLabel(
cachingLogic.getDescription(object, entry.title), user);
}
}
}
return entry;
}
public synchronized void clear() {
assertWorkerThread();
mIconDb.clear();
}
/**
* Adds a default package entry in the cache. This entry is not persisted and will be removed
* when the cache is flushed.
*/
protected synchronized void cachePackageInstallInfo(String packageName, UserHandle user,
Bitmap icon, CharSequence title) {
removeFromMemCacheLocked(packageName, user);
ComponentKey cacheKey = getPackageKey(packageName, user);
CacheEntry entry = mCache.get(cacheKey);
// For icon caching, do not go through DB. Just update the in-memory entry.
if (entry == null) {
entry = new CacheEntry();
}
if (!TextUtils.isEmpty(title)) {
entry.title = title;
}
if (icon != null) {
BaseIconFactory li = getIconFactory();
entry.bitmap = li.createIconBitmap(icon);
li.close();
}
if (!TextUtils.isEmpty(title) && entry.bitmap.icon != null) {
mCache.put(cacheKey, entry);
}
}
private static ComponentKey getPackageKey(String packageName, UserHandle user) {
ComponentName cn = new ComponentName(packageName, packageName + EMPTY_CLASS_NAME);
return new ComponentKey(cn, user);
}
/**
* Gets an entry for the package, which can be used as a fallback entry for various components.
* This method is not thread safe, it must be called from a synchronized method.
*/
protected CacheEntry getEntryForPackageLocked(String packageName, UserHandle user,
boolean useLowResIcon) {
assertWorkerThread();
ComponentKey cacheKey = getPackageKey(packageName, user);
CacheEntry entry = mCache.get(cacheKey);
if (entry == null || (entry.bitmap.isLowRes() && !useLowResIcon)) {
entry = new CacheEntry();
boolean entryUpdated = true;
// Check the DB first.
if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
try {
int flags = Process.myUserHandle().equals(user) ? 0 :
PackageManager.GET_UNINSTALLED_PACKAGES;
PackageInfo info = mPackageManager.getPackageInfo(packageName, flags);
ApplicationInfo appInfo = info.applicationInfo;
if (appInfo == null) {
throw new NameNotFoundException("ApplicationInfo is null");
}
BaseIconFactory li = getIconFactory();
// Load the full res icon for the application, but if useLowResIcon is set, then
// only keep the low resolution icon instead of the larger full-sized icon
BitmapInfo iconInfo = li.createBadgedIconBitmap(
appInfo.loadIcon(mPackageManager), user, appInfo.targetSdkVersion,
isInstantApp(appInfo));
li.close();
entry.title = appInfo.loadLabel(mPackageManager);
entry.contentDescription = mPackageManager.getUserBadgedLabel(entry.title, user);
entry.bitmap = BitmapInfo.of(
useLowResIcon ? LOW_RES_ICON : iconInfo.icon, iconInfo.color);
// Add the icon in the DB here, since these do not get written during
// package updates.
ContentValues values = newContentValues(
iconInfo, entry.title.toString(), packageName, null);
addIconToDB(values, cacheKey.componentName, info, getSerialNumberForUser(user),
info.lastUpdateTime);
} catch (NameNotFoundException e) {
if (DEBUG) Log.d(TAG, "Application not installed " + packageName);
entryUpdated = false;
}
}
// Only add a filled-out entry to the cache
if (entryUpdated) {
mCache.put(cacheKey, entry);
}
}
return entry;
}
protected boolean getEntryFromDB(ComponentKey cacheKey, CacheEntry entry, boolean lowRes) {
Cursor c = null;
try {
c = mIconDb.query(
lowRes ? IconDB.COLUMNS_LOW_RES : IconDB.COLUMNS_HIGH_RES,
IconDB.COLUMN_COMPONENT + " = ? AND " + IconDB.COLUMN_USER + " = ?",
new String[]{
cacheKey.componentName.flattenToString(),
Long.toString(getSerialNumberForUser(cacheKey.user))});
if (c.moveToNext()) {
// Set the alpha to be 255, so that we never have a wrong color
entry.bitmap = BitmapInfo.of(LOW_RES_ICON, setColorAlphaBound(c.getInt(0), 255));
entry.title = c.getString(1);
if (entry.title == null) {
entry.title = "";
entry.contentDescription = "";
} else {
entry.contentDescription = mPackageManager.getUserBadgedLabel(
entry.title, cacheKey.user);
}
if (!lowRes) {
byte[] data = c.getBlob(2);
try {
entry.bitmap = BitmapInfo.of(
BitmapFactory.decodeByteArray(data, 0, data.length, mDecodeOptions),
entry.bitmap.color);
} catch (Exception e) { }
}
return true;
}
} catch (SQLiteException e) {
Log.d(TAG, "Error reading icon cache", e);
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Returns a cursor for an arbitrary query to the cache db
*/
public synchronized Cursor queryCacheDb(String[] columns, String selection,
String[] selectionArgs) {
return mIconDb.query(columns, selection, selectionArgs);
}
/**
* Cache class to store the actual entries on disk
*/
public static final class IconDB extends SQLiteCacheHelper {
private static final int RELEASE_VERSION = 27;
public static final String TABLE_NAME = "icons";
public static final String COLUMN_ROWID = "rowid";
public static final String COLUMN_COMPONENT = "componentName";
public static final String COLUMN_USER = "profileId";
public static final String COLUMN_LAST_UPDATED = "lastUpdated";
public static final String COLUMN_VERSION = "version";
public static final String COLUMN_ICON = "icon";
public static final String COLUMN_ICON_COLOR = "icon_color";
public static final String COLUMN_LABEL = "label";
public static final String COLUMN_SYSTEM_STATE = "system_state";
public static final String COLUMN_KEYWORDS = "keywords";
public static final String[] COLUMNS_HIGH_RES = new String[] {
IconDB.COLUMN_ICON_COLOR, IconDB.COLUMN_LABEL, IconDB.COLUMN_ICON };
public static final String[] COLUMNS_LOW_RES = new String[] {
IconDB.COLUMN_ICON_COLOR, IconDB.COLUMN_LABEL };
public IconDB(Context context, String dbFileName, int iconPixelSize) {
super(context, dbFileName, (RELEASE_VERSION << 16) + iconPixelSize, TABLE_NAME);
}
@Override
protected void onCreateTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
+ COLUMN_COMPONENT + " TEXT NOT NULL, "
+ COLUMN_USER + " INTEGER NOT NULL, "
+ COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, "
+ COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, "
+ COLUMN_ICON + " BLOB, "
+ COLUMN_ICON_COLOR + " INTEGER NOT NULL DEFAULT 0, "
+ COLUMN_LABEL + " TEXT, "
+ COLUMN_SYSTEM_STATE + " TEXT, "
+ COLUMN_KEYWORDS + " TEXT, "
+ "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ") "
+ ");");
}
}
private ContentValues newContentValues(BitmapInfo bitmapInfo, String label,
String packageName, @Nullable String keywords) {
ContentValues values = new ContentValues();
values.put(IconDB.COLUMN_ICON,
bitmapInfo.isLowRes() ? null : GraphicsUtils.flattenBitmap(bitmapInfo.icon));
values.put(IconDB.COLUMN_ICON_COLOR, bitmapInfo.color);
values.put(IconDB.COLUMN_LABEL, label);
values.put(IconDB.COLUMN_SYSTEM_STATE, getIconSystemState(packageName));
values.put(IconDB.COLUMN_KEYWORDS, keywords);
return values;
}
private void assertWorkerThread() {
if (Looper.myLooper() != mBgLooper) {
throw new IllegalStateException("Cache accessed on wrong thread " + Looper.myLooper());
}
}
}
|
perfectrecall/aws-sdk-cpp | aws-cpp-sdk-lexv2-models/source/model/ImportResourceSpecification.cpp | <filename>aws-cpp-sdk-lexv2-models/source/model/ImportResourceSpecification.cpp
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lexv2-models/model/ImportResourceSpecification.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LexModelsV2
{
namespace Model
{
ImportResourceSpecification::ImportResourceSpecification() :
m_botImportSpecificationHasBeenSet(false),
m_botLocaleImportSpecificationHasBeenSet(false)
{
}
ImportResourceSpecification::ImportResourceSpecification(JsonView jsonValue) :
m_botImportSpecificationHasBeenSet(false),
m_botLocaleImportSpecificationHasBeenSet(false)
{
*this = jsonValue;
}
ImportResourceSpecification& ImportResourceSpecification::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("botImportSpecification"))
{
m_botImportSpecification = jsonValue.GetObject("botImportSpecification");
m_botImportSpecificationHasBeenSet = true;
}
if(jsonValue.ValueExists("botLocaleImportSpecification"))
{
m_botLocaleImportSpecification = jsonValue.GetObject("botLocaleImportSpecification");
m_botLocaleImportSpecificationHasBeenSet = true;
}
return *this;
}
JsonValue ImportResourceSpecification::Jsonize() const
{
JsonValue payload;
if(m_botImportSpecificationHasBeenSet)
{
payload.WithObject("botImportSpecification", m_botImportSpecification.Jsonize());
}
if(m_botLocaleImportSpecificationHasBeenSet)
{
payload.WithObject("botLocaleImportSpecification", m_botLocaleImportSpecification.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
|
myke-roly/mipergamino | components/icons/Inmobiliaria.js | <gh_stars>1-10
import GenericIcon from "./GenericIcon";
const Inmobiliaria = props => (
<GenericIcon {...props}>
<path xmlns="http://www.w3.org/2000/svg" d="m0 117.382812 16.640625 27.335938 31.679687-19.277344v213.605469h288v-213.613281l31.679688 19.277344 16.640625-27.335938-192.320313-117.054688zm304.320312 189.664063h-71.695312l-12.3125-59.144531 54.75-10.566406-18.183594-94.265626-141.390625 27.28125 18.183594 94.265626 55.214844-10.65625 11.050781 53.085937h-119.617188v-201.09375l112-68.175781 112 68.175781zm-145.296874-79.910156-6.0625-31.425781 78.550781-15.160157 6.0625 31.425781zm0 0" />
</GenericIcon>
)
export default Inmobiliaria;
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSenseitranslationBlogspotCom.py | def extractSenseitranslationBlogspotCom(item):
'''
Parser for 'senseitranslation.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
titlemap = [
('S. B. F. C Chapter ', 'Salvation Began From Cafe', 'translated'),
('S. B. F. C. Chapter ', 'Salvation Began From Cafe', 'translated'),
('S.B.F.C Chapter', 'Salvation Began From Cafe', 'translated'),
('S.B.F.C. Chapter', 'Salvation Began From Cafe', 'translated'),
('OPJ Chapter ', 'One Punch of Justice', 'translated'),
('M. F. Chapter ', 'Monster Factory', 'translated'),
('M. F Chapter ', 'Monster Factory', 'translated'),
('Master of Dungeon', 'Master of Dungeon', 'oel'),
]
for titlecomponent, name, tl_type in titlemap:
if titlecomponent.lower() in item['title'].lower():
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
AjayGhanwat/AllWork | FundooPay/app/src/main/java/com/bridgelabz/fundoopay/MainActivity.java | package com.bridgelabz.fundoopay;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import com.bridgelabz.fundoopay.base.BaseActivity;
import com.bridgelabz.fundoopay.register.welcomefragment;
public class MainActivity extends BaseActivity {
Fragment fragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new welcomefragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainactivityPanel, fragment);
fragmentTransaction.commit();
}
@Override
public void initView() {
}
@Override
public void clickListner() {
}
}
|
alovn/tutorials | golang/design-parttern/08.adapter/adapter_test.go | <gh_stars>1-10
package adapter
import "testing"
func TestPowerAdapter_Charge(t *testing.T) {
adapter := &PowerAdapter{}
adapter.SetPower(&AmericaPower{})
adapter.Charge(&ChinaPlug{})
}
|
alexaries/CocosCreatorPlugins | packages/res-compress/panel/index.js | let packageName = "res-compress";
let fs = require('fire-fs');
let path = require('fire-path');
let Electron = require('electron');
let fs_extra = require('fs-extra');
let lameJs = Editor.require('packages://' + packageName + '/node_modules/lamejs');
let co = Editor.require('packages://' + packageName + '/node_modules/co');
let child_process = require('child_process');
let mp3item = Editor.require('packages://' + packageName + '/panel/item/mp3item.js');
let image_item = Editor.require('packages://' + packageName + '/panel/item/image-item.js');
let imageMin = Editor.require('packages://' + packageName + '/node_modules/imagemin');
let imageminPngquant = Editor.require('packages://' + packageName + '/node_modules/imagemin-pngquant');
let imageminJpegtran = Editor.require('packages://' + packageName + '/node_modules/imagemin-jpegtran');
let imageminJpegRecompress = Editor.require('packages://' + packageName + '/node_modules/imagemin-jpeg-recompress');
// 同步执行exec
child_process.execPromise = function (cmd, options, callback) {
return new Promise(function (resolve, reject) {
child_process.exec(cmd, options, function (err, stdout, stderr) {
// console.log("执行完毕!");
if (err) {
console.log(err);
callback && callback(stderr);
reject(err);
return;
}
resolve();
})
});
};
let importPromise = function (path, url, isShowProcess, callBack) {
return new Promise(function (resolve, reject) {
Editor.assetdb.import(path, url, isShowProcess, function (err, results) {
if (err) {
console.log(err);
reject(err);
}
callBack && callBack(results);
resolve();
return results;
})
});
};
let queryAssetsPromise = function (url, type, callBack) {
return new Promise(function (resolve, reject) {
Editor.assetdb.queryAssets(url, type, function (err, results) {
if (err) {
console.log(err);
reject(err);
}
callBack && callBack(results);
resolve();
return results;
})
})
};
Editor.Panel.extend({
style: fs.readFileSync(Editor.url('packages://' + packageName + '/panel/index.css', 'utf8')) + "",
template: fs.readFileSync(Editor.url('packages://' + packageName + '/panel/index.html', 'utf8')) + "",
$: {
logTextArea: '#logTextArea',
},
ready() {
let logCtrl = this.$logTextArea;
let logListScrollToBottom = function () {
setTimeout(function () {
logCtrl.scrollTop = logCtrl.scrollHeight;
}, 10);
};
mp3item.init();
image_item.init();
window.plugin = new window.Vue({
el: this.shadowRoot,
created() {
this._getLamePath();
this.onBtnClickGetProject();
},
init() {
},
data: {
logView: "",
mp3Path: null,
lameFilePath: null,// lame程序路径
mp3Array: [
{uuid: "88a33018-0323-4c25-9b0c-c54f147f5dd8"},
],
imageArray: [],
},
methods: {
_addLog(str) {
let time = new Date();
// this.logView = "[" + time.toLocaleString() + "]: " + str + "\n" + this.logView;
this.logView += "[" + time.toLocaleString() + "]: " + str + "\n";
logListScrollToBottom();
},
onBtnClickCompressAllMusic() {
console.log("压缩整个项目音频文件");
this._compressMp3(this.mp3Array);
},
onBtnClickCompressAllImage() {
console.log("压缩整个项目图片文件");
this._compressImage(this.imageArray);
},
// 检索项目中的声音文件mp3类型
onBtnClickGetProject(event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.mp3Array = [];
this.imageArray = [];
// co(function* () {
// console.log("11");
// yield queryAssetsPromise('db://assets/**\/*', ['audio-clip', 'texture'], function (results) {
// results.forEach(function (result) {
// let ext = path.extname(result.path);
// if (ext === '.mp3') {
// this.mp3Array.push(result);
// } else if (ext === '.png' || ext === '.jpg') {
// this.imageArray.push(result);
// }
// }.bind(this));
// console.log("222");
// }.bind(this));
// }.bind(this));
// return;
Editor.assetdb.queryAssets('db://assets/**\/*', ['audio-clip', 'texture'], function (err, results) {
this.mp3Array = [];
this.imageArray = [];
results.forEach(function (result) {
let ext = path.extname(result.path);
if (ext === '.mp3') {
this.mp3Array.push(result);
} else if (ext === '.png' || ext === '.jpg') {
this.imageArray.push(result);
}
}.bind(this));
// 按照字母排序
this._sortArr(this.mp3Array);
this._sortArr(this.imageArray);
}.bind(this));
},
_sortArr(arr) {
arr.sort(function (a, b) {
let pathA = a.path;
let pathB = b.path;
let extA = path.basename(pathA).toLowerCase();
let extB = path.basename(pathB).toLowerCase();
let numA = extA.charCodeAt(0);
let numB = extB.charCodeAt(0);
return numA - numB;
})
},
onMusicItemCompress(data) {
// 进行压缩
console.log("音频压缩");
this._compressMp3([data]);
},
onImageItemCompress(data) {
console.log("图片压缩");
this._compressImage([data]);
},
_compressImage(dataArr) {
let tmp = this._getTempMp3Dir();
co(function* () {
for (let i = 0; i < dataArr.length; i++) {
let data = dataArr[i];
// todo 对于图片格式的判断
let files = yield imageMin([data.path], tmp, {
plugins: [
imageminJpegRecompress({
accurate: true,//高精度模式
quality: "high",//图像质量:low, medium, high and veryhigh;
method: "smallfry",//网格优化:mpe, ssim, ms-ssim and smallfry;
min: 70,//最低质量
loops: 0,//循环尝试次数, 默认为6;
progressive: false,//基线优化
subsample: "default"//子采样:default, disable;
}),
imageminJpegtran(),
imageminPngquant({quality: '65-80'})
]
});
this._addLog("压缩成功 [" + (i + 1) + "/" + dataArr.length + "]:" + data.url);
// 导入到项目原位置
let newNamePath = files[0].path;
let name = path.basename(newNamePath);
let url = data.url.substr(0, data.url.length - name.length - 1);
yield importPromise([newNamePath], url, true, function (results) {
results.forEach(function (result) {
if (result.type === "texture") {
console.log("del: " + result.path);
if (fs.existsSync(newNamePath)) {
fs.unlinkSync(newNamePath);// 删除临时文件
}
}
});
}.bind(this));
}
this._addLog("压缩完毕!");
}.bind(this));
},
_getLamePath() {
let lamePath = null;
let lameBasePath = path.join(Editor.projectInfo.path, "packages/res-compress/file");
let runPlatform = cc.sys.os;
if (runPlatform === "Windows") {
lamePath = path.join(lameBasePath, 'lame.exe');
} else if (runPlatform === "OS X") {
// 添加执行权限
lamePath = path.join(lameBasePath, 'lame');
let cmd = "chmod u+x " + lamePath;
child_process.exec(cmd, null, function (err) {
if (err) {
console.log(err);
}
//console.log("添加执行权限成功");
}.bind(this));
}
return lamePath;
},
_getTempMp3Dir() {
let userPath = Electron.remote.app.getPath('userData');
let tempMp3Dir = path.join(userPath, "/mp3Compress");// 临时目录
return tempMp3Dir;
},
_compressMp3(fileDataArray) {
// 设置lame路径
let lamePath = this._getLamePath();
if (!fs.existsSync(lamePath)) {
this._addLog("文件不存在: " + lamePath);
return;
}
console.log("压缩");
co(function* () {
// 处理要压缩的音频文件
for (let i = 0; i < fileDataArray.length; i++) {
let voiceFile = fileDataArray[i].path;
let voiceFileUrl = fileDataArray[i].url;
if (!fs.existsSync(voiceFile)) {
this._addLog("声音文件不存在: " + voiceFile);
return;
}
if (path.extname(voiceFile) === ".mp3") {
// 检测临时缓存目录
let tempMp3Dir = this._getTempMp3Dir();// 临时目录
if (!fs.existsSync(tempMp3Dir)) {
fs.mkdirSync(tempMp3Dir);
}
console.log("mp3目录: " + tempMp3Dir);
let dir = path.dirname(voiceFile);
let arr = voiceFile.split('.');
let fileName = arr[0].substr(dir.length + 1, arr[0].length - dir.length);
let tempMp3Path = path.join(tempMp3Dir, 'temp_' + fileName + '.mp3');
// 压缩mp3
let cmd = `${lamePath} -V 0 -q 0 -b 45 -B 80 --abr 64 "${voiceFile}" "${tempMp3Path}"`;
console.log("------------------------------exec began" + i);
yield child_process.execPromise(cmd, null, function (err) {
this._addLog("出现错误: \n" + err);
}.bind(this));
console.log("------------------------------exec end" + i);
// 临时文件重命名
let newNamePath = path.join(tempMp3Dir, fileName + '.mp3');
fs.renameSync(tempMp3Path, newNamePath);
this._addLog(`压缩成功 [${(i + 1)}/${fileDataArray.length}] : ${voiceFileUrl} `);
let fullFileName = fileName + '.mp3';
let url = voiceFileUrl.substr(0, voiceFileUrl.length - fullFileName.length - 1);
// 导入到项目原位置
yield importPromise([newNamePath], url, true,
function (results) {
results.forEach(function (result) {
// 删除临时目录的文件
// console.log("type: " + result.type);
if (result.type = "audio-clip") {
console.log("del: " + result.path);
if (fs.existsSync(newNamePath)) {
fs.unlinkSync(newNamePath);// 删除临时文件
}
}
});
}.bind(this));
} else {
console.log("不支持的文件类型:" + voiceFile);
}
}
this._addLog("处理完毕!");
}.bind(this));
},
onBtnCompress() {
console.log("test");
this.onBtnClickGetProject(null);
this.onBtnClickGetProject(null);
},
dropFile(event) {
event.preventDefault();
let files = event.dataTransfer.files;
if (files.length > 0) {
let file = files[0].path;
console.log(file);
this.mp3Path = file;
} else {
console.log("no file");
}
},
drag(event) {
event.preventDefault();
event.stopPropagation();
// console.log("dragOver");
},
}
});
},
messages: {
'res-compress:hello'(event, target) {
console.log("刷新文件列表");
// 检测变动的文件里面是否包含mp3
let b = false;
for (let i = 0; i < target.length; i++) {
let ext = require('fire-path').extname(target[i].path || target[i].destPath);
if (ext === '.mp3' || ext === ".png" || ext === ".jpg") {
b = true;
break;
}
}
if (b) {
window.plugin.onBtnClickGetProject();
} else {
// console.log("未发现音频文件,无需刷新:");
}
}
}
}); |
elusivecodes/FrostCore | src/Core/math.js | <reponame>elusivecodes/FrostCore
/**
* Math methods
*/
/**
* Clamp a value between a min and max.
* @param {number} value The value to clamp.
* @param {number} [min=0] The minimum value of the clamped range.
* @param {number} [max=1] The maximum value of the clamped range.
* @returns {number} The clamped value.
*/
Core.clamp = (value, min = 0, max = 1) =>
Math.max(
min,
Math.min(
max,
value
)
);
/**
* Clamp a value between 0 and 100.
* @param {number} value The value to clamp.
* @returns {number} The clamped value.
*/
Core.clampPercent = value =>
Core.clamp(value, 0, 100);
/**
* Get the distance between two vectors.
* @param {number} x1 The first vector X co-ordinate.
* @param {number} y1 The first vector Y co-ordinate.
* @param {number} x2 The second vector X co-ordinate.
* @param {number} y2 The second vector Y co-ordinate.
* @returns {number} The distance between the vectors.
*/
Core.dist = (x1, y1, x2, y2) =>
Core.len(
x1 - x2,
y1 - y2
);
/**
* Inverse linear interpolation from one value to another.
* @param {number} v1 The starting value.
* @param {number} v2 The ending value.
* @param {number} value The value to inverse interpolate.
* @returns {number} The interpolated amount.
*/
Core.inverseLerp = (v1, v2, value) =>
(value - v1) / (v2 - v1);
/**
* Get the length of an X,Y vector.
* @param {number} x The X co-ordinate.
* @param {number} y The Y co-ordinate.
* @returns {number} The length of the vector.
*/
Core.len = Math.hypot;
/**
* Linear interpolation from one value to another.
* @param {number} v1 The starting value.
* @param {number} v2 The ending value.
* @param {number} amount The amount to interpolate.
* @returns {number} The interpolated value.
*/
Core.lerp = (v1, v2, amount) =>
v1
* (1 - amount)
+ v2
* amount;
/**
* Map a value from one range to another.
* @param {number} value The value to map.
* @param {number} fromMin The minimum value of the current range.
* @param {number} fromMax The maximum value of the current range.
* @param {number} toMin The minimum value of the target range.
* @param {number} toMax The maximum value of the target range.
* @returns {number} The mapped value.
*/
Core.map = (value, fromMin, fromMax, toMin, toMax) =>
(value - fromMin)
* (toMax - toMin)
/ (fromMax - fromMin)
+ toMin;
/**
* Return a random floating-point number.
* @param {number} [a=1] The minimum value (inclusive).
* @param {number} [b] The maximum value (exclusive).
* @returns {number} A random number.
*/
Core.random = (a = 1, b = null) =>
Core.isNull(b) ?
Math.random() * a :
Core.map(
Math.random(),
0,
1,
a,
b
);
/**
* Return a random number.
* @param {number} [a=1] The minimum value (inclusive).
* @param {number} [b] The maximum value (exclusive).
* @returns {number} A random number.
*/
Core.randomInt = (a = 1, b = null) =>
Core.random(a, b) | 0;
/**
* Constrain a number to a specified step-size.
* @param {number} value The value to constrain.
* @param {number} step The minimum step-size.
* @returns {number} The constrained value.
*/
Core.toStep = (value, step = 0.01) =>
parseFloat(
(
Math.round(value / step)
* step
).toFixed(
`${step}`.replace('\d*\.?/', '').length
)
);
|
wizardassassin/Fun-Coding | Project Euler/solutions/problem047.js | /*
Distinct primes factors
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
https://projecteuler.net/problem=47
The preceding problem was taken from Project Euler and is under a Creative Commons Licence:
Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0).
This does not apply to the solution/code.
*/
import {
nextPrime
} from "./dependency.js";
export default function problem47(n = 4) { // Scale it to n variables and n prime factors
let n1 = 2;
while (true) {
if (distinctPrimeFactorsSum(n1 + 3) != 4)
n1 += 4;
else if (distinctPrimeFactorsSum(n1 + 2) != 4)
n1 += 3;
else if (distinctPrimeFactorsSum(n1 + 1) != 4)
n1 += 2;
else if (distinctPrimeFactorsSum(n1) != 4)
n1 += 1;
else
return n1;
}
} // went from 147 seconds to 13 seconds. Yay!
function distinctPrimeFactorsSum(a) { // Not a big diff
if (a < 2)
return -1;
let arr = 0;
let fac = 2;
while (a > 1) {
if (a % fac == 0)
arr++;
while (a % fac == 0)
a /= fac;
fac = nextPrime(fac);
}
return arr;
} |
diegopablomansilla/massoftware | src/main/java/com/massoftware/service/logistica/Transportes.java | <filename>src/main/java/com/massoftware/service/logistica/Transportes.java
package com.massoftware.service.logistica;
import com.massoftware.service.EntityId;
public class Transportes extends EntityId implements Cloneable {
// ---------------------------------------------------------------------------------------------------------------------------
private String id;
// Nº transporte
private Integer numero;
// CUIT
private Long cuit;
// Nombre
private String nombre;
// Domicilio
private String domicilio;
// CP
private String codigoPostal;
// Ciudad
private String nombreCiudad;
// Provincia
private String nombreProvincia;
// Pais
private String nombrePais;
// ---------------------------------------------------------------------------------------------------------------------------
// GET ID
public String getId() {
return this.id;
}
// SET ID
public void setId(String id){
this.id = (id == null || id.trim().length() == 0) ? null : id.trim();
}
// GET Nº transporte
public Integer getNumero() {
return this.numero;
}
// SET Nº transporte
public void setNumero(Integer numero ){
this.numero = numero;
}
// GET CUIT
public Long getCuit() {
return this.cuit;
}
// SET CUIT
public void setCuit(Long cuit ){
this.cuit = cuit;
}
// GET Nombre
public String getNombre() {
return this.nombre;
}
// SET Nombre
public void setNombre(String nombre ){
this.nombre = (nombre == null || nombre.trim().length() == 0) ? null : nombre.trim();
}
// GET Domicilio
public String getDomicilio() {
return this.domicilio;
}
// SET Domicilio
public void setDomicilio(String domicilio ){
this.domicilio = (domicilio == null || domicilio.trim().length() == 0) ? null : domicilio.trim();
}
// GET CP
public String getCodigoPostal() {
return this.codigoPostal;
}
// SET CP
public void setCodigoPostal(String codigoPostal ){
this.codigoPostal = (codigoPostal == null || codigoPostal.trim().length() == 0) ? null : codigoPostal.trim();
}
// GET Ciudad
public String getNombreCiudad() {
return this.nombreCiudad;
}
// SET Ciudad
public void setNombreCiudad(String nombreCiudad ){
this.nombreCiudad = (nombreCiudad == null || nombreCiudad.trim().length() == 0) ? null : nombreCiudad.trim();
}
// GET Provincia
public String getNombreProvincia() {
return this.nombreProvincia;
}
// SET Provincia
public void setNombreProvincia(String nombreProvincia ){
this.nombreProvincia = (nombreProvincia == null || nombreProvincia.trim().length() == 0) ? null : nombreProvincia.trim();
}
// GET Pais
public String getNombrePais() {
return this.nombrePais;
}
// SET Pais
public void setNombrePais(String nombrePais ){
this.nombrePais = (nombrePais == null || nombrePais.trim().length() == 0) ? null : nombrePais.trim();
}
// ---------------------------------------------------------------------------------------------------------------------------
public String toString() {
if(this.getNumero() != null && this.getCuit() != null){
return this.getNumero() + " - " + this.getCuit();
} else if(this.getNumero() != null && this.getCuit() == null){
return this.getNumero().toString();
} else if(this.getNumero() == null && this.getCuit() != null){
return this.getCuit().toString();
} else {
return super.toString();
}
}
public Transportes clone() {
Transportes other = new Transportes();
other.setId(this.getId());
other.setNumero(this.getNumero());
other.setCuit(this.getCuit());
other.setNombre(this.getNombre());
other.setDomicilio(this.getDomicilio());
other.setCodigoPostal(this.getCodigoPostal());
other.setNombreCiudad(this.getNombreCiudad());
other.setNombreProvincia(this.getNombreProvincia());
other.setNombrePais(this.getNombrePais());
// -------------------------------------------------------------------
return other;
// -------------------------------------------------------------------
}
} // END CLASS ---------------------------------------------------------------------------------------------------------- |
jalenyang/Rougamo | mybatis/src/main/java/com.rougamo.mybatis/mapper/StudentMapper.java | package com.pork.mybatis.mapper;
import com.pork.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface StudentMapper {
@Select("select * from Student where teacherId=#{teacherId}")
List<Student> getStuentsByTeacherId(@Param("teacherId") Integer teacherId);
@Select("select * from Student s, teacher t where s.teacherid=t.id and teacherid=#{teacherid}")
List<Student> getStuents(@Param("teacherid") Integer teacherId);
}
|
Mattlk13/chefspec | examples/bff_package/spec/remove_spec.rb | require 'chefspec'
describe 'bff_package::remove' do
platform 'aix'
describe 'removes a bff_package with an explicit action' do
it { is_expected.to remove_bff_package('explicit_action') }
it { is_expected.to_not remove_bff_package('not_explicit_action') }
end
describe 'removes a bff_package with attributes' do
it { is_expected.to remove_bff_package('with_attributes').with(version: '1.0.0') }
it { is_expected.to_not remove_bff_package('with_attributes').with(version: '1.2.3') }
end
describe 'removes a bff_package when specifying the identity attribute' do
it { is_expected.to remove_bff_package('identity_attribute') }
end
end
|
bis83/pomdog | experimental/Pomdog.Experimental/Rendering/Processors/ParticleBatchCommandProcessor.cpp | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#include "ParticleBatchCommandProcessor.hpp"
#include "Pomdog.Experimental/Rendering/Commands/ParticleBatchCommand.hpp"
namespace Pomdog {
namespace {
static Matrix3x2 CreateTransformMatrix(Particle const& particle)
{
return Matrix3x2::CreateScale(particle.Size)
* Matrix3x2::CreateRotation(particle.Rotation)
* Matrix3x2::CreateTranslation(particle.Position);
}
} // unnamed namespace
//-----------------------------------------------------------------------
ParticleBatchCommandProcessor::ParticleBatchCommandProcessor(
std::shared_ptr<GraphicsContext> const& graphicsContext,
std::shared_ptr<GraphicsDevice> const& graphicsDevice,
AssetManager & assets)
: spriteBatch(graphicsContext, graphicsDevice, assets)
, drawCallCount(0)
{
}
//-----------------------------------------------------------------------
void ParticleBatchCommandProcessor::Begin(GraphicsContext & graphicsContext)
{
drawCallCount = 0;
spriteBatch.Begin(Matrix4x4::Identity);
}
//-----------------------------------------------------------------------
void ParticleBatchCommandProcessor::Draw(GraphicsContext & graphicsContext, RenderCommand & command)
{
using Detail::Rendering::ParticleBatchCommand;
auto & particleCommand = static_cast<ParticleBatchCommand &>(command);
for (auto & particle: *particleCommand.particles)
{
auto transform = CreateTransformMatrix(particle);
spriteBatch.Draw(particleCommand.texture, transform,
particleCommand.textureRegion.Subrect, particle.Color, {0.5f, 0.5f});
}
}
//-----------------------------------------------------------------------
void ParticleBatchCommandProcessor::End(GraphicsContext & graphicsContext)
{
spriteBatch.End();
drawCallCount += spriteBatch.DrawCallCount();
}
//-----------------------------------------------------------------------
int ParticleBatchCommandProcessor::DrawCallCount() const
{
return drawCallCount;
}
//-----------------------------------------------------------------------
void ParticleBatchCommandProcessor::SetViewProjection(Matrix4x4 const& view, Matrix4x4 const& projection)
{
auto viewProjection = view * projection;
spriteBatch.SetProjectionMatrix(viewProjection);
}
//-----------------------------------------------------------------------
} // namespace Pomdog
|
UCD4IDS/sage | src/sage/schemes/elliptic_curves/ec_database.py | r"""
Tables of elliptic curves of given rank
The default database of curves contains the following data:
+------+------------------+--------------------+
| Rank | Number of curves | Maximal conductor |
+======+==================+====================+
| 0 | 30427 | 9999 |
+------+------------------+--------------------+
| 1 | 31871 | 9999 |
+------+------------------+--------------------+
| 2 | 2388 | 9999 |
+------+------------------+--------------------+
| 3 | 836 | 119888 |
+------+------------------+--------------------+
| 4 | 10 | 1175648 |
+------+------------------+--------------------+
| 5 | 5 | 37396136 |
+------+------------------+--------------------+
| 6 | 5 | 6663562874 |
+------+------------------+--------------------+
| 7 | 5 | 896913586322 |
+------+------------------+--------------------+
| 8 | 6 | 457532830151317 |
+------+------------------+--------------------+
| 9 | 7 | ~9.612839e+21 |
+------+------------------+--------------------+
| 10 | 6 | ~1.971057e+21 |
+------+------------------+--------------------+
| 11 | 6 | ~1.803406e+24 |
+------+------------------+--------------------+
| 12 | 1 | ~2.696017e+29 |
+------+------------------+--------------------+
| 14 | 1 | ~3.627533e+37 |
+------+------------------+--------------------+
| 15 | 1 | ~1.640078e+56 |
+------+------------------+--------------------+
| 17 | 1 | ~2.750021e+56 |
+------+------------------+--------------------+
| 19 | 1 | ~1.373776e+65 |
+------+------------------+--------------------+
| 20 | 1 | ~7.381324e+73 |
+------+------------------+--------------------+
| 21 | 1 | ~2.611208e+85 |
+------+------------------+--------------------+
| 22 | 1 | ~2.272064e+79 |
+------+------------------+--------------------+
| 23 | 1 | ~1.139647e+89 |
+------+------------------+--------------------+
| 24 | 1 | ~3.257638e+95 |
+------+------------------+--------------------+
| 28 | 1 | ~3.455601e+141 |
+------+------------------+--------------------+
Note that lists for r>=4 are not exhaustive; there may well be curves
of the given rank with conductor less than the listed maximal conductor,
which are not included in the tables.
AUTHORS:
- <NAME> (2007-10-07): initial version
- <NAME> (2014-10-24): Added examples of more high-rank curves
See also the functions cremona_curves() and cremona_optimal_curves()
which enable easy looping through the Cremona elliptic curve database.
"""
import os
from ast import literal_eval
from .constructor import EllipticCurve
class EllipticCurves:
def rank(self, rank, tors=0, n=10, labels=False):
r"""
Return a list of at most `n` curves with given
rank and torsion order.
INPUT:
- ``rank`` (int) -- the desired rank
- ``tors`` (int, default 0) -- the desired torsion order (ignored if 0)
- ``n`` (int, default 10) -- the maximum number of curves returned.
- ``labels`` (bool, default False) -- if True, return Cremona
labels instead of curves.
OUTPUT:
(list) A list at most `n` of elliptic curves of required rank.
EXAMPLES::
sage: elliptic_curves.rank(n=5, rank=3, tors=2, labels=True)
['59450i1', '59450i2', '61376c1', '61376c2', '65481c1']
::
sage: elliptic_curves.rank(n=5, rank=0, tors=5, labels=True)
['11a1', '11a3', '38b1', '50b1', '50b2']
::
sage: elliptic_curves.rank(n=5, rank=1, tors=7, labels=True)
['574i1', '4730k1', '6378c1']
::
sage: e = elliptic_curves.rank(6)[0]; e.ainvs(), e.conductor()
((1, 1, 0, -2582, 48720), 5187563742)
sage: e = elliptic_curves.rank(7)[0]; e.ainvs(), e.conductor()
((0, 0, 0, -10012, 346900), 382623908456)
sage: e = elliptic_curves.rank(8)[0]; e.ainvs(), e.conductor()
((1, -1, 0, -106384, 13075804), 249649566346838)
For large conductors, the labels are not known::
sage: L = elliptic_curves.rank(6, n=3); L
[Elliptic Curve defined by y^2 + x*y = x^3 + x^2 - 2582*x + 48720 over Rational Field,
Elliptic Curve defined by y^2 + y = x^3 - 7077*x + 235516 over Rational Field,
Elliptic Curve defined by y^2 + x*y = x^3 - x^2 - 2326*x + 43456 over Rational Field]
sage: L[0].cremona_label()
Traceback (most recent call last):
...
LookupError: Cremona database does not contain entry for Elliptic Curve defined by y^2 + x*y = x^3 + x^2 - 2582*x + 48720 over Rational Field
sage: elliptic_curves.rank(6, n=3, labels=True)
[]
"""
from sage.env import ELLCURVE_DATA_DIR
data = os.path.join(ELLCURVE_DATA_DIR, 'rank%s'%rank)
try:
f = open(data)
except IOError:
return []
v = []
tors = int(tors)
for w in f.readlines():
N, iso, num, ainvs, r, t = w.split()
N = int(N)
t = int(t)
if tors and tors != t:
continue
# Labels are only known to be correct for small conductors.
# NOTE: only change this bound below after checking/fixing
# the Cremona labels in the elliptic_curves package!
if N <= 400000:
label = '%s%s%s'%(N, iso, num)
else:
label = None
if labels:
if label is not None:
v.append(label)
else:
E = EllipticCurve(literal_eval(ainvs))
E._set_rank(r)
E._set_torsion_order(t)
E._set_conductor(N)
if label is not None:
E._set_cremona_label(label)
v.append(E)
if len(v) >= n:
break
return v
elliptic_curves = EllipticCurves()
|
EgorBolt/studying | netprog/lab6/src/chernovik.java | //import java.io.IOException;
//import java.net.InetAddress;
//import java.net.InetSocketAddress;
//import java.net.SocketAddress;
//import java.nio.ByteBuffer;
//import java.nio.channels.*;
//import java.util.Iterator;
//import java.nio.charset.Charset;
//
//public class Forwarder {
// private int lport;
// private String rhost;
// private int rport;
//
// public Forwarder(int lport, String rhost, int rport) {
// this.lport = lport;
// this.rhost = rhost;
// this.rport = rport;
// }
//
//
// public void doJob() {
// int id = 0;
// final int BUFFER_SIZE = 65536;
//
// try (
// Selector selector = Selector.open();
// ServerSocketChannel serverSocket = ServerSocketChannel.open();
// ) {
//
// SocketAddress listenAddress = new InetSocketAddress("localhost", lport);
// SocketAddress target = new InetSocketAddress(InetAddress.getByName(rhost), rport);
//
// serverSocket.configureBlocking(false);
// serverSocket.bind(listenAddress);
// serverSocket.register(selector, SelectionKey.OP_ACCEPT);
// System.out.println("Forwarder started...");
//
// TODO: Сделать чтение ТОЛЬКО ПОСЛЕ ТОГО, как я приконнектился к серверу
// TODO: Сделать для каждого соединения свой персональный буффер
// TODO: Сделать дополнительный класс для хранения соответствия сооединений, буффера для каждого процесса и так далее
//
// while (true) {
// selector.select();
// Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
// int size = selector.selectedKeys().size();
//
// while(keys.hasNext()) {
//
// SelectionKey key = keys.next();
//
// if (key.isAcceptable()) {
// SocketChannel from = serverSocket.accept();
// SocketChannel to = SocketChannel.open();
// from.configureBlocking(false);
// to.configureBlocking(false);
// ByteBuffer buffer = ByteBuffer.allocate(65536);
//
// ForwarderInfo fi = new ForwarderInfo(from, to, buffer, id);
//
// id++;
//
// to.register(selector, SelectionKey.OP_CONNECT, fi);
//
// } else if (key.isConnectable()) {
// ForwarderInfo attachment = (ForwarderInfo)key.attachment();
// int channelId = attachment.getId();
// SocketChannel channel = (SocketChannel)key.channel();
//
// channel.connect(target);
// if (channel.finishConnect()) {
// System.out.println("connected");
// attachment.getFrom().register(selector, SelectionKey.OP_READ, attachment);
// } else {
// System.err.println("cant connect, terminating");
// System.exit(-100);
// }
//
// } else if (key.isReadable()) {
// SocketChannel channel = (SocketChannel)key.channel();
// ForwarderInfo attachment = (ForwarderInfo)key.attachment();
//
// SocketChannel from = attachment.getFrom();
// SocketChannel to = attachment.getTo();
// ByteBuffer buffer = attachment.getInfo();
// int channelId = attachment.getId();
// buffer.clear();
//
// int haveRead = channel.read(buffer);
// String v = new String(buffer.array(), Charset.forName("UTF-8"));
//
// if (haveRead != -1) {
// buffer.flip();
// ForwarderInfo newInfo = new ForwarderInfo(from, to, buffer, channelId);
// if (channel.equals(attachment.getFrom())) {
// to.register(selector, SelectionKey.OP_WRITE, newInfo);
// } else {
// from.register(selector, SelectionKey.OP_WRITE, newInfo);
// }
// }
// else {
// channel.close();
// }
//
// } else if (key.isWritable()) {
// ForwarderInfo info = (ForwarderInfo)key.attachment();
// SocketChannel channel = (SocketChannel)key.channel();
// boolean isConnected = channel.isConnected();
// ByteBuffer buffer = info.getInfo();
// int channelId = info.getId();
// String v = new String(buffer.array(), Charset.forName("UTF-8"));
//
// if (isConnected) {
// channel.write(buffer);
// }
//
// if (channel.equals(info.getTo())) {
// channel.register(selector, SelectionKey.OP_READ, info);
// }
// }
//
// keys.remove();
// }
// }
// } catch (IOException eIO) {
// System.err.println("ERROR: Something wrong in doJob.");
// eIO.printStackTrace();
// System.exit(-3);
// }
// }
//}
//import java.nio.ByteBuffer;
//import java.nio.channels.SocketChannel;
//
//public class ForwarderInfo {
// private SocketChannel from;
// private SocketChannel to;
// private ByteBuffer info;
//
// public ForwarderInfo(SocketChannel from, SocketChannel to, ByteBuffer info) {
// this.from = from;
// this.to = to;
// this.info = info;
// }
//
// public void setFrom(SocketChannel channel) {
// this.from = channel;
// }
//
// public void setTo(SocketChannel channel) {
// this.to = channel;
// }
//
// public void setInfo(ByteBuffer buffer) {
// this.info = buffer;
// }
//
// public SocketChannel getFrom() {
// return this.from;
// }
//
// public SocketChannel getTo() {
// return this.to;
// }
//
// public ByteBuffer getInfo() {
// return this.info;
// }
//
// public void flipInfo() {
// this.info.flip();
// }
//} |
obsidian-btc/raygun-client | materials/raygun_struct.rb | {
"occurredOn": string,
"details": {
"machineName": string,
"version": string,
"client": {
"name": string,
"version": string,
"clientUrl": string
},
"error": {
"innerError": string,
"data": object,
"className": string,
"message": string,
"stackTrace": [
{
"lineNumber": number,
"className": string,
"fileName": string,
"methodName": string
}]
},
"environment": {
"processorCount": number,
"osVersion": string ,
"windowBoundsWidth": number,
"windowBoundsHeight": number,
"resolutionScale": string,
"currentOrientation": string,
"cpu": string,
"packageVersion": string,
"architecture": string,
"totalPhysicalMemory": number,
"availablePhysicalMemory": number,
"totalVirtualMemory": number,
"availableVirtualMemory": number,
"diskSpaceFree": array,
"deviceName": string,
"locale": string
},
"tags": array,
"userCustomData": object,
"request": {
"hostName": string,
"url": string,
"httpMethod": string,
"iPAddress": string,
"queryString": object,
"form": object,
"headers": object,
"rawData": object
},
"response": {
"statusCode": number
},
"user": {
"identifier": string
},
"context": {
"identifier": string
}
}
}
|
jiripetrlik/kie-wb-common | kie-wb-common-forms/kie-wb-common-forms-integrations/kie-wb-common-forms-jbpm-integration/kie-wb-common-forms-jbpm-integration-backend/src/test/java/org/kie/workbench/common/forms/jbpm/server/service/impl/BPMFinderServiceImplTest.java | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.forms.jbpm.server.service.impl;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.forms.jbpm.model.authoring.JBPMProcessModel;
import org.kie.workbench.common.services.backend.project.ModuleClassLoaderHelper;
import org.kie.workbench.common.services.shared.project.KieModule;
import org.kie.workbench.common.services.shared.project.KieModuleService;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.Files;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.fs.file.SimpleFileSystemProvider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class BPMFinderServiceImplTest {
public static final String RESOURCES_PATH = "/definitions/";
private static final int EXPECTED_PROCESSES = 4;
private static final String PROCESS_WITHOUT_VARIABLES_ID = "myProject.process-without-variables";
private static final int PROCESS_WITHOUT_VARIABLES_TASKS = 0;
private static final String PROCESS_WITH_ALL_VARIABLES_ID = "myProject.process-with-all-possible-variables";
private static final int PROCESS_WITH_ALL_VARIABLES_TASKS = 5;
private static final String PROCESS_WITH_SHARED_FORMS_ID = "myProject.processTaskSharedForms";
private static final int PROCESS_WITH_SHARED_FORMS_TASKS = 2;
private static final String PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_ID = "myProject.processTaskSharedFormsWrongMappings";
private static final int PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_TASKS = 1;
private SimpleFileSystemProvider simpleFileSystemProvider = null;
private Path rootPath;
@Mock
private IOService ioService;
@Mock
private KieModule module;
@Mock
private KieModuleService moduleService;
@Mock
private ModuleClassLoaderHelper moduleClassLoaderHelper;
@Mock
private ClassLoader classLoader;
private BPMNFormModelGeneratorImpl bpmnFormModelGenerator;
private BPMFinderServiceImpl finderService;
@Mock
private org.uberfire.backend.vfs.Path testPath;
@Before
public void initialize() throws URISyntaxException, ClassNotFoundException {
when(ioService.newDirectoryStream(any(),
any())).thenAnswer(invocationOnMock -> Files.newDirectoryStream((Path) invocationOnMock.getArguments()[0],
(DirectoryStream.Filter<Path>) invocationOnMock.getArguments()[1]));
when(ioService.newInputStream(any())).thenAnswer(invocationOnMock -> new FileInputStream(((Path) invocationOnMock.getArguments()[0]).toFile()));
simpleFileSystemProvider = new SimpleFileSystemProvider();
simpleFileSystemProvider.forceAsDefault();
rootPath = simpleFileSystemProvider.getPath(this.getClass().getResource(RESOURCES_PATH).toURI());
when(moduleService.resolveModule(any())).thenReturn(module);
when(module.getRootPath()).thenReturn(Paths.convert(rootPath));
when(classLoader.loadClass(any())).thenAnswer((Answer<Class>) invocation -> String.class);
when(moduleClassLoaderHelper.getModuleClassLoader(any())).thenReturn(classLoader);
bpmnFormModelGenerator = new BPMNFormModelGeneratorImpl(moduleService,
moduleClassLoaderHelper);
finderService = new BPMFinderServiceImpl(ioService,
moduleService,
bpmnFormModelGenerator);
finderService.init();
}
@Test
public void testFindAllProcessFormModels() {
List<JBPMProcessModel> models = finderService.getAvailableProcessModels(testPath);
assertNotNull(models);
assertEquals(EXPECTED_PROCESSES,
models.size());
models.forEach(model -> {
assertNotNull(model.getProcessFormModel());
if (model.getProcessFormModel().getProcessId().equals(PROCESS_WITH_ALL_VARIABLES_ID)) {
assertEquals(PROCESS_WITH_ALL_VARIABLES_TASKS,
model.getTaskFormModels().size());
} else if (model.getProcessFormModel().getProcessId().equals(PROCESS_WITHOUT_VARIABLES_ID)) {
assertEquals(PROCESS_WITHOUT_VARIABLES_TASKS,
model.getTaskFormModels().size());
} else if (model.getProcessFormModel().getProcessId().equals(PROCESS_WITH_SHARED_FORMS_ID)) {
assertEquals(PROCESS_WITH_SHARED_FORMS_TASKS,
model.getTaskFormModels().size());
} else if (model.getProcessFormModel().getProcessId().equals(PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_ID)) {
assertEquals(PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_TASKS,
model.getTaskFormModels().size());
} else {
fail("Unexpected process: " + model.getProcessFormModel().getProcessId());
}
});
}
@Test
public void testFindProcessWithAllVariablesFormModel() {
testFindProcess(PROCESS_WITH_ALL_VARIABLES_ID,
PROCESS_WITH_ALL_VARIABLES_TASKS);
}
@Test
public void testFindProcessWithoutVariablesFormModel() {
testFindProcess(PROCESS_WITHOUT_VARIABLES_ID,
PROCESS_WITHOUT_VARIABLES_TASKS);
}
@Test
public void testFindProcessWithoutSharedTaskFormFormModel() {
testFindProcess(PROCESS_WITH_SHARED_FORMS_ID,
PROCESS_WITH_SHARED_FORMS_TASKS);
}
@Test
public void testFindProcessWithoutSharedTaskFormWithWrongMappingsFormModel() {
testFindProcess(PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_ID,
PROCESS_WITH_SHARED_FORMS_WRONG_MAPPINGS_TASKS);
}
protected void testFindProcess(String processId,
int expectedTasks) {
JBPMProcessModel model = finderService.getModelForProcess(processId,
testPath);
assertNotNull(model);
assertNotNull(model.getProcessFormModel());
assertEquals(processId,
model.getProcessFormModel().getProcessId());
assertEquals(expectedTasks,
model.getTaskFormModels().size());
}
}
|
Ziang-Lu/Design-Patterns | 3-Structural Patterns/4-Composite Pattern/Topic-Lecture-Video Example/Python/composite_pattern_test.py | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Application that actually uses Composite Pattern.
"""
__author__ = '<NAME>'
from model import Lecture, Topic, Video
def main():
design_patterns = Topic('Design Patterns')
patterns_intro = Lecture('Intro to Design Patterns')
design_patterns.add_module(patterns_intro)
composite = Topic('Composite Pattern')
design_patterns.add_module(composite)
composite_intro = Lecture('Intro to Composite Pattern')
composite.add_module(composite_intro)
composite_video = Video("Let's compose!")
composite.add_module(composite_video)
observer = Topic('Iterator Pattern')
design_patterns.add_module(observer)
observer_intro = Lecture('Intro to Observer Pattern')
observer.add_module(observer_intro)
design_patterns.display('\t')
if __name__ == '__main__':
main()
# Output:
# Topic - Design Patterns
# Lecture - Intro to Design Patterns
# Topic - Composite Pattern
# Lecture - Intro to Composite Pattern
# Video - Let's compose!
# Topic - Observer Pattern
# Lecture - Intro to Observer Pattern
|
BlazicIvan/Net-CQA | src/test/src/Metrics/Test/NumOfMethods/C0.java | <reponame>BlazicIvan/Net-CQA<gh_stars>0
package Metrics.Test.NumOfMethods;
public class C0 {
protected void m0() {}
protected void m5(){}
}
|
rtbtech/libsniper | sniper/strings/join.h | /*
* Copyright (c) 2019, MetaHash, <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.
*/
#pragma once
#include <sniper/std/string.h>
#include <type_traits>
namespace sniper::strings {
template<class T>
string join(const T& arr)
{
string res;
for (auto& e : arr) {
if (!res.empty())
res += ", ";
if constexpr (std::is_same_v<typename T::value_type, string>)
res += e;
else
res += std::to_string(e);
}
return res;
}
} // namespace sniper::strings
|
PaulElcampeon/War-Version-1.0-ReleasedOnHeroku | src/main/java/com/example/Services/BattleServices/BattleServiceImplementation.java | package com.example.Services.BattleServices;
import com.example.Models.BattleSection.Battle.Battle;
import com.example.Models.BattleSection.BattleReceipt.BattleReceipt;
import com.example.Models.Warrior.Warrior;
import java.util.ArrayList;
public class BattleServiceImplementation implements BattleService {
private static Battle battle = new Battle();
@Override
public void battlePrep(Warrior aggressor, Warrior defender) {
battle.battlePrep(aggressor,defender);
}
@Override
public void startBattle() {
battle.startBattle();
}
@Override
public void startBattleAll(Warrior aggressor, Warrior defender) {
battle.startBattleAll(aggressor, defender);
}
@Override
public void setVictorAndLoser() {
battle.setVictorAndLoser();
}
@Override
public void createBattleRececipt() {
battle.createBattleReceipt();
}
@Override
public void giveBattleReceiptsToBothPlayers() {
battle.giveBattleReceiptsToBothPlayers();
}
@Override
public Battle returnBattle() {
return battle;
}
@Override
public ArrayList<Double> getAttacksDamagePattern() {
return battle.getAttackersDamagePattern();
}
@Override
public ArrayList<Double> getDefendersDamagePattern() {
return battle.getDefendersDamagePattern();
}
@Override
public Warrior getVictor() {
return battle.getVictor();
}
@Override
public Warrior getLoser() {
return battle.getLoser();
}
@Override
public BattleReceipt getBattleReceipt() {
return battle.getBattleReceipt();
}
}
|
oonsamyi/flow | src/parser/test/flow/types/annotations/migrated_0058.js | <filename>src/parser/test/flow/types/annotations/migrated_0058.js<gh_stars>1000+
var {x}: {x: string; } = { x: "hello" };
|
Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/SkinParamBackcolored.java | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, <NAME>
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: <NAME>
*/
package net.sourceforge.plantuml;
import java.util.EnumMap;
import java.util.Map;
import net.sourceforge.plantuml.cucadiagram.Stereotype;
import net.sourceforge.plantuml.graphic.HtmlColor;
public class SkinParamBackcolored extends SkinParamDelegator {
final private HtmlColor backColorElement;
final private HtmlColor backColorGeneral;
final private boolean forceClickage;
public SkinParamBackcolored(ISkinParam skinParam, HtmlColor backColorElement) {
this(skinParam, backColorElement, null, false);
}
public SkinParamBackcolored(ISkinParam skinParam, HtmlColor backColorElement, boolean forceClickage) {
this(skinParam, backColorElement, null, forceClickage);
}
public SkinParamBackcolored(ISkinParam skinParam, HtmlColor backColorElement, HtmlColor backColorGeneral) {
this(skinParam, backColorElement, backColorGeneral, false);
}
public SkinParamBackcolored(ISkinParam skinParam, HtmlColor backColorElement, HtmlColor backColorGeneral,
boolean forceClickage) {
super(skinParam);
this.forceClickage = forceClickage;
this.backColorElement = backColorElement;
this.backColorGeneral = backColorGeneral;
}
@Override
public HtmlColor getBackgroundColor() {
if (backColorGeneral != null) {
return backColorGeneral;
}
return super.getBackgroundColor();
}
@Override
public HtmlColor getHtmlColor(ColorParam param, Stereotype stereotype, boolean clickable) {
if (param.isBackground() && backColorElement != null) {
return backColorElement;
}
if (forceClickage) {
final HtmlColor c1 = super.getHtmlColor(param, stereotype, true);
if (c1 != null) {
return c1;
}
// clickable = true;
}
final HtmlColor forcedColor = forced.get(param);
if (forcedColor != null) {
return forcedColor;
}
return super.getHtmlColor(param, stereotype, clickable);
}
private final Map<ColorParam, HtmlColor> forced = new EnumMap<ColorParam, HtmlColor>(ColorParam.class);
public void forceColor(ColorParam param, HtmlColor color) {
forced.put(param, color);
}
}
|
gaoht/house | java/classes/com/alipay/android/a/a/a/v.java | <reponame>gaoht/house<filename>java/classes/com/alipay/android/a/a/a/v.java<gh_stars>1-10
package com.alipay.android.a.a.a;
import android.content.Context;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
public final class v
implements i
{
private static v g = null;
private static final ThreadFactory i = new x();
Context a;
l b;
long c;
long d;
long e;
int f;
private ThreadPoolExecutor h;
private v(Context paramContext)
{
this.a = paramContext;
this.b = l.a("android");
this.h = new ThreadPoolExecutor(10, 11, 3L, TimeUnit.SECONDS, new ArrayBlockingQueue(20), i, new ThreadPoolExecutor.CallerRunsPolicy());
try
{
this.h.allowCoreThreadTimeOut(true);
CookieSyncManager.createInstance(this.a);
CookieManager.getInstance().setAcceptCookie(true);
return;
}
catch (Exception paramContext)
{
for (;;) {}
}
}
public static final v a(Context paramContext)
{
if (g != null) {
return g;
}
return b(paramContext);
}
/* Error */
private static final v b(Context paramContext)
{
// Byte code:
// 0: ldc 2
// 2: monitorenter
// 3: getstatic 26 com/alipay/android/a/a/a/v:g Lcom/alipay/android/a/a/a/v;
// 6: ifnull +12 -> 18
// 9: getstatic 26 com/alipay/android/a/a/a/v:g Lcom/alipay/android/a/a/a/v;
// 12: astore_0
// 13: ldc 2
// 15: monitorexit
// 16: aload_0
// 17: areturn
// 18: new 2 com/alipay/android/a/a/a/v
// 21: dup
// 22: aload_0
// 23: invokespecial 96 com/alipay/android/a/a/a/v:<init> (Landroid/content/Context;)V
// 26: astore_0
// 27: aload_0
// 28: putstatic 26 com/alipay/android/a/a/a/v:g Lcom/alipay/android/a/a/a/v;
// 31: goto -18 -> 13
// 34: astore_0
// 35: ldc 2
// 37: monitorexit
// 38: aload_0
// 39: athrow
// Local variable table:
// start length slot name signature
// 0 40 0 paramContext Context
// Exception table:
// from to target type
// 3 13 34 finally
// 18 31 34 finally
}
public final Future<af> a(ae paramae)
{
long l2 = 0L;
String str;
int j;
long l3;
long l4;
long l1;
if (ad.a(this.a))
{
str = "HttpManager" + hashCode() + ": Active Task = %d, Completed Task = %d, All Task = %d,Avarage Speed = %d KB/S, Connetct Time = %d ms, All data size = %d bytes, All enqueueConnect time = %d ms, All socket time = %d ms, All request times = %d times";
j = this.h.getActiveCount();
l3 = this.h.getCompletedTaskCount();
l4 = this.h.getTaskCount();
if (this.e != 0L) {
break label209;
}
l1 = 0L;
if (this.f != 0) {
break label229;
}
}
for (;;)
{
String.format(str, new Object[] { Integer.valueOf(j), Long.valueOf(l3), Long.valueOf(l4), Long.valueOf(l1), Long.valueOf(l2), Long.valueOf(this.c), Long.valueOf(this.d), Long.valueOf(this.e), Integer.valueOf(this.f) });
paramae = new ab(this, (z)paramae);
paramae = new w(this, paramae, paramae);
this.h.execute(paramae);
return paramae;
label209:
l1 = this.c * 1000L / this.e >> 10;
break;
label229:
l2 = this.d / this.f;
}
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/alipay/android/a/a/a/v.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
jackh423/python | CIS41B/Threading/T0.py | # start threads by passing function to Thread constructor
import threading
import time
import random
def tfunc(*t):
time.sleep(random.randint(1,10))
print('Thread running: ',t)
return
t1 = ("Thread-",1)
t2 = ("Thread-",2)
t3 = ("Thread-",3)
thd1 = threading.Thread(target=tfunc,args=t1)
thd2 = threading.Thread(target=tfunc,args=t2)
thd3 = threading.Thread(target=tfunc,args=t3)
thd1.start()
thd2.start()
thd3.start()
thd1.join()
thd2.join()
thd3.join() |
wuping5719/JustFun | 12-Sort/12-14-Test.java | <reponame>wuping5719/JustFun
package sort;
import java.util.Random;
/**
* @author WuPing
* @date 2016年4月2日 下午10:27:00
* @version 1.0
* @parameter
* @since
* @return
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int N = 100;
int[] arrayA = new int[N];
int[] arrayB = new int[N];
for (int i = 0; i < N; i++) {
Random radomNum = new Random();
arrayB[i] = radomNum.nextInt(90);
}
System.out.println("冒泡排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long bubbleSortStartTime = System.nanoTime(); // 获取开始时间
BubbleSort.bubbleSort(arrayA);
long bubbleSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("冒泡排序执行时间: "
+ (bubbleSortEndTime - bubbleSortStartTime) + "ns");
System.out.println("冒泡排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("选择排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long selectSortStartTime = System.nanoTime(); // 获取开始时间
SelectSort.selectSort(arrayA);
long selectSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("选择排序执行时间: "
+ (selectSortEndTime - selectSortStartTime) + "ns");
System.out.println("选择排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("插入排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long insertSortStartTime = System.nanoTime(); // 获取开始时间
InsertSort.insertSort(arrayA);
long insertSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("插入排序执行时间: "
+ (insertSortEndTime - insertSortStartTime) + "ns");
System.out.println("插入排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("快速排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long quickSortStartTime = System.nanoTime(); // 获取开始时间
QuickSort.sort(arrayA);
long quickSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("快速排序执行时间: "
+ (quickSortEndTime - quickSortStartTime) + "ns");
System.out.println("快速排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("堆排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long heapSortStartTime = System.nanoTime(); // 获取开始时间
HeapSort.heapSort(arrayA);
long heapSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("堆排序执行时间: " + (heapSortEndTime - heapSortStartTime)
+ "ns");
System.out.println("堆排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("希尔排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long shellSortStartTime = System.nanoTime(); // 获取开始时间
ShellSort.shellSort(arrayA);
long shellSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("希尔排序执行时间: "
+ (shellSortEndTime - shellSortStartTime) + "ns");
System.out.println("希尔排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("归并排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long mergeSortStartTime = System.nanoTime(); // 获取开始时间
MergeSort.mergeSort(arrayA);
long mergeSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("归并排序执行时间: "
+ (mergeSortEndTime - mergeSortStartTime) + "ns");
System.out.println("归并排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("计数排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long countSortStartTime = System.nanoTime(); // 获取开始时间
CountSort.countSort(arrayA);
long countSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("计数排序执行时间: "
+ (countSortEndTime - countSortStartTime) + "ns");
System.out.println("计数排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("桶排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long bucketSortStartTime = System.nanoTime(); // 获取开始时间
BucketSort.bucketSort(arrayA);
long bucketSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("桶排序执行时间: "
+ (bucketSortEndTime - bucketSortStartTime) + "ns");
System.out.println("桶排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("基数排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long radixSortStartTime = System.nanoTime(); // 获取开始时间
RadixSort.radixSort(arrayA);
long radixSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("基数排序执行时间: "
+ (radixSortEndTime - radixSortStartTime) + "ns");
System.out.println("基数排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("折半插入排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long binaiSortStartTime = System.nanoTime(); // 获取开始时间
BinaiSort.binaiSort(arrayA);
long binaiSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("折半插入排序执行时间: "
+ (binaiSortEndTime - binaiSortStartTime) + "ns");
System.out.println("折半插入排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("2路插入排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long twoSortStartTime = System.nanoTime(); // 获取开始时间
TwoSort.twoSort(arrayA);
long twoSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("2路插入排序执行时间: " + (twoSortEndTime - twoSortStartTime)
+ "ns");
System.out.println("2路插入排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("树形选择排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long treeSelectSortStartTime = System.nanoTime(); // 获取开始时间
TreeSelectSort.treeSelectSort(arrayA);
long treeSelectSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("树形选择排序执行时间: "
+ (treeSelectSortEndTime - treeSelectSortStartTime) + "ns");
System.out.println("树形选择排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
System.out.println();
System.out.println("梳排序前的整形数组:");
for (int i = 0; i < N; i++) {
arrayA[i] = arrayB[i];
System.out.print(arrayA[i] + " ");
}
System.out.println();
long combSortStartTime = System.nanoTime(); // 获取开始时间
CombSort.combSort(arrayA);
long combSortEndTime = System.nanoTime(); // 获取结束时间
System.out.println("梳排序执行时间: "
+ (combSortEndTime - combSortStartTime) + "ns");
System.out.println("梳排序后的整形数组:");
for (int i = 0; i < arrayA.length; i++) {
System.out.print(arrayA[i] + " ");
}
System.out.println();
}
}
|
icebreakersentertainment/ice_engine | include/IMessageEventListener.hpp | <reponame>icebreakersentertainment/ice_engine
#ifndef IMESSAGEEVENTLISTENER_H_
#define IMESSAGEEVENTLISTENER_H_
#include "networking/Event.hpp"
namespace ice_engine
{
class IMessageEventListener
{
public:
virtual ~IMessageEventListener()
{
}
;
virtual bool processEvent(const networking::MessageEvent& event) = 0;
};
}
#endif /* IMESSAGEEVENTLISTENER_H_ */
|
yoyooli8/dubbo-plus | restful/src/main/java/net/dubboclub/restful/export/mapping/RequestEntity.java | <filename>restful/src/main/java/net/dubboclub/restful/export/mapping/RequestEntity.java<gh_stars>100-1000
package net.dubboclub.restful.export.mapping;
import com.alibaba.fastjson.JSONObject;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @date: 2016/2/22.
* @author:bieber.
* @project:dubbo-plus.
* @package:net.dubboclub.restful.export.mapping.
* @version:1.0.0
* @fix:
* @description: 请求的实体
*/
public class RequestEntity implements Serializable {
private final static Pattern argPattern = Pattern.compile("^(arg[1-9]{1}[0-9]{0,})$");
private final static Pattern argIndexPattern = Pattern.compile("[1-9]{1}[0-9]{0,}");
private String group;
private String version;
private String[] args;
private String method;
public RequestEntity(){
}
public RequestEntity(JSONObject jsonObject){
if(jsonObject!=null){
this.setGroup(jsonObject.getString("group"));
this.setVersion(jsonObject.getString("version"));
this.setMethod(jsonObject.getString("method"));
Set<String> keys = jsonObject.keySet();
for(String key:keys){
Matcher matcher = argPattern.matcher(key);
if(matcher.matches()){
matcher = argIndexPattern.matcher(key);
matcher.find();
int index = Integer.parseInt(matcher.group());
setArg(index,jsonObject.getString(key));
}
}
}
}
/**
* 注意此时的index是从1开始,而非0
* @param index
* @param arg
*/
public void setArg(int index,String arg){
if(args==null){
args = new String[index];
}else if(args.length<index){
String[] newArgs = new String[index];
System.arraycopy(args,0,newArgs,0,args.length);
args = newArgs;
}
args[index-1]=arg;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String[] getArgs() {
return args;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
@Override
public String toString() {
return "RequestEntity{" +
"group='" + group + '\'' +
", version='" + version + '\'' +
", args=" + Arrays.toString(args) +
", method='" + method + '\'' +
'}';
}
}
|
cilium/kube-apate | api/k8s/v1/server/restapi/apps_v1/patch_apps_v1_namespaced_stateful_set_responses.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2017-2020 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0
package apps_v1
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/cilium/kube-apate/api/k8s/v1/models"
)
// PatchAppsV1NamespacedStatefulSetOKCode is the HTTP code returned for type PatchAppsV1NamespacedStatefulSetOK
const PatchAppsV1NamespacedStatefulSetOKCode int = 200
/*PatchAppsV1NamespacedStatefulSetOK OK
swagger:response patchAppsV1NamespacedStatefulSetOK
*/
type PatchAppsV1NamespacedStatefulSetOK struct {
/*
In: Body
*/
Payload *models.IoK8sAPIAppsV1StatefulSet `json:"body,omitempty"`
}
// NewPatchAppsV1NamespacedStatefulSetOK creates PatchAppsV1NamespacedStatefulSetOK with default headers values
func NewPatchAppsV1NamespacedStatefulSetOK() *PatchAppsV1NamespacedStatefulSetOK {
return &PatchAppsV1NamespacedStatefulSetOK{}
}
// WithPayload adds the payload to the patch apps v1 namespaced stateful set o k response
func (o *PatchAppsV1NamespacedStatefulSetOK) WithPayload(payload *models.IoK8sAPIAppsV1StatefulSet) *PatchAppsV1NamespacedStatefulSetOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the patch apps v1 namespaced stateful set o k response
func (o *PatchAppsV1NamespacedStatefulSetOK) SetPayload(payload *models.IoK8sAPIAppsV1StatefulSet) {
o.Payload = payload
}
// WriteResponse to the client
func (o *PatchAppsV1NamespacedStatefulSetOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// PatchAppsV1NamespacedStatefulSetUnauthorizedCode is the HTTP code returned for type PatchAppsV1NamespacedStatefulSetUnauthorized
const PatchAppsV1NamespacedStatefulSetUnauthorizedCode int = 401
/*PatchAppsV1NamespacedStatefulSetUnauthorized Unauthorized
swagger:response patchAppsV1NamespacedStatefulSetUnauthorized
*/
type PatchAppsV1NamespacedStatefulSetUnauthorized struct {
}
// NewPatchAppsV1NamespacedStatefulSetUnauthorized creates PatchAppsV1NamespacedStatefulSetUnauthorized with default headers values
func NewPatchAppsV1NamespacedStatefulSetUnauthorized() *PatchAppsV1NamespacedStatefulSetUnauthorized {
return &PatchAppsV1NamespacedStatefulSetUnauthorized{}
}
// WriteResponse to the client
func (o *PatchAppsV1NamespacedStatefulSetUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(401)
}
|
caidaoli/rrestjs | app/controller/message.js | <filename>app/controller/message.js
var home = {},
fs = require('fs'),
pagenum = 20,//首页发送20条数据
fdate = _rrest.mod.stools.fdate,//实用工具模块
htmltostring = _rrest.mod.stools.htmltostring,//字符串转html
check_all_param = _rrest.mod.stools.check_all_param,//检查所有参数是否存在
checkemail = _rrest.mod.stools.checkemail,
addstar = _rrest.mod.stools.addstar,
AsyncProxy = _rrest.AsyncProxy,//异步代理库
ca = require('../modules/captcha'),//验证码模块
gr = _rrest.mod.gravatar,//gravatar模块
mongo = _rrest.mongo,//连接mongo数据库方法
get_id = _rrest.mod.stools.get_id,//mongodb的_id生成方法
title = _rrest.config.webtitle;
function getmsg(sname, condition, pagenum, callback){ //获取数据
mongo(function(err, db, release){
if(err) return;
db.collection("msg", function(err, col){
if(err) return release();
var sortc = {"sort":[['_id','desc']], "limit": pagenum},//每次发送多少个
findc = sname === true? {} : (function(){//创建查找作者的正则
var reg=new RegExp(sname,'i');
return {"name":reg}})();
if(condition != true) findc._id = {"$lt":get_id(db, condition)};
findc.pid = 0;
var cursor = col.find(findc,sortc);//获得查询条件游标
cursor.count(function(err, total){
var total = total||0;//总数
cursor.toArray(function(err, results){
var msgarray = results||[],//获取全部条件的内容
len = msgarray.length;//本次获取的长度
if(len == 0){
release();
return callback(err, msgarray, total);
}
var ap = new AsyncProxy(true),
apfunc = [],//异步操作函数数组
apall = function(){//异步操作执行完毕函数
//restlog.info('数据获取完毕');
release();//释放链接
ap=null;
return callback(err, msgarray, total);
};
msgarray.forEach(function(value, index){
var func = function(rec){//根据msgarray数组查找回复
col.find({"pid":value._id+''}).toArray(function(err, results){
//restlog.info(order);
//restlog.info(results)
var n = msgarray[index].name
msgarray[index].name = addstar(n);
results.forEach(function(value, i){
var m = results[i].name;
results[i].name = addstar(m);
})
msgarray[index].reply = results
rec();
})
}
apfunc.push(func);//放入异步数组
});
apfunc.push(apall);//放入总方法
var t = ap.ap.apply(ap, apfunc);
//restlog.info("共有多少次异步操作:"+t)
})//toarray方法
})//count
})//collection
})//mongo
}
home.initial = function(){ //初始化
mongo(function(err, db, release){
if(err) return;
db.createCollection("msg", function(err, col){
if(err) return release();
col.ensureIndex({"pid":-1}, function(err, r){ //这里建立一个根据plus点数排序的索引
if(err){
release();
return restlog.error('索引建立失败:'+err);
}
col.indexInformation(function(err,array){
if(!err) restlog.info('当前msg集合所有索引为:'+JSON.stringify(array))
release();
});
})
});
});
}();
home.index = function(req, res){
var sname = req.getparam['sname'] || true,
email = req.session.email || '';
if(!sname){sname = htmltostring(sname);}
getmsg(sname, true, pagenum, function(err, msgarray, total){
if(!err) res.render('/message.jade', {pagetitle:_rrest.config.webtitle+'-留言板', h1class:'h1_p', msg:msgarray, total:total, email:email});
})
}
home.more = function(req, res, pathobj){//获得更多接口
var sname = htmltostring(req.getparam['sname']),//查询用户名
condition = req.getparam['condition'],//最后一个_id用于快速分页
pagenum = req.getparam['pagenum'],//拿多少个数据
pageint = parseInt(pagenum);
sname = sname == 'true' ? true:sname;
if(!check_all_param(condition, pagenum)){
return res.sendjson({"suc":0,"fail":"获取更多信息参数错误"});
}//参数错误
if(sname == '' || typeof sname === 'undefined'){
return res.sendjson({"suc":0,"fail":"作者名错误"});
};//查询用户名
if(condition.length != 24){
return res.sendjson({"suc":0,"fail":"condition参数错误1"});
}
if(pageint != pagenum && pageint>100){//防止恶意获取大于100条的数据,查爆服务器内存和数据库
return res.sendjson({"suc":0,"fail":"pagenum参数错误"});
}
getmsg(sname, condition, pageint, function(err, msgarray, total){
if(err){
res.sendjson({"suc":0,"fail":"获取失败1"});
restlog.error('getmore错误:'+err);
}
else{
res.compiletemp('/include/msg.jade', {msg:msgarray}, function(err, data){
if(err) return res.sendjson({"suc":0,"fail":"获取失败2"});
res.sendjson({"suc":1,"content":data});
});
}
})
}
home.getcaptcha = function(req, res){//获取验证码
var ac = req.getparam['a'];
if(!check_all_param(ac)){
return res.sendjson({"suc":0,"fail":"获取验证码参数错误"});
}
if(ac != 'getcap'){
return res.sendjson({"suc":0,"fail":"获取验证码action错误"})
}
var sendca = function(caobj){//生成验证码的回调
if(!caobj) return res.sendjson({"suc":0,"fail":"验证码获取失败"});
res.sendjson({"suc":1, "data":caobj});//发送验证码
}
ca.creat(sendca);//生成验证码
}
home.send = function(req, res){
var name = req.getparam['name'],//用户名
content = req.getparam['content'],//内容
pid = req.getparam['pid'],//是否为回复
po = req.getparam['po'],//验证码选择位置
poid = req.getparam['poid'];//验证码id
if(!check_all_param(name, content, pid, po, poid)){
return res.sendjson({"suc":0,"fail":"send参数错误"});
}//这些参数都必须存在
if(parseInt(po) != po || parseInt(po)<0 || parseInt(po)>(ca.canum-1)){
return res.sendjson({"suc":0,"fail":"位置错误"});
}//用户拖拽的图片位置参数错误
if(poid.length !== 24){
return res.sendjson({"suc":0,"fail":"验证码ID错误"});
}
if(!checkemail(name) || name.length>50){
return res.sendjson({"suc":0,"fail":"用户名过长或不为邮箱"});
}
if(content.length>150){
return res.sendjson({"suc":0,"fail":"内容过长"});
}
req.session.email = name;//将用户传入的name值设置session,方便用户重复输入
var sendc = function(ca_bool){//对比完验证码执行
if(!pid || pid.length !== 24){pid=0;}
if(!ca_bool){
return res.sendjson({"suc":0,"fail":"验证码失败,你是非人类!"});
}
var data = {
name : htmltostring(name),
content : htmltostring(content),
time : fdate('y-m-d h:m:s'),
plus:0,
pid:pid,
ip:req.ip,
};
mongo(function(err, db, release){//操作mongodb数据库
if(err) return;
db.collection("msg", function(err, col){
if(err) return release();
col.insert(data, function(err, record){
if(err){
release();
restlog.error('提交留言失败:'+err);
return res.sendjson({"suc":0, "fail":"提交失败"});
}
res.sendjson({"suc":1});
gr(data.name, function(err, url){//生成gravatar头像
if(err){
release();
return restlog.info('gravatar头像获取失败:'+err);
}
var url = url || '';
col.update({"_id":record[0]._id}, {"$set": {"gr":url}}, function(err){
if(err) restlog.info('gravatar头像更新失败:'+err);
release();
});//update
});//gr.create
});//insert
});//collection
});//mongo
}
ca.contrast(poid, po, sendc);//去验证验证码
}
home.del = function(req, res){//执行删除操作
var id = req.getparam['id'];
var pwd = req.getparam['pwd'];
if(id.length !== 24){
return res.sendjson({"suc":0,"fail":"id无效"});
}
if(pwd !== '<PASSWORD>'){//这里应该有后台,这里为了简便
return res.sendjson({"suc":0,"fail":"对不起,您没有权限"});
}
//判断合法性id的合法性和用户是否有权力
mongo(function(err, db, release){//操作mongodb数据库
if(err) return;
db.collection("msg", function(err, col){
if(err) return release();
col.remove({$or:[{_id:get_id(db, id)}, {pid:id}]},function(err, r){//删除id并且将回复一并删除
release();
if(err){
restlog.error('删除失败,id为:'+id+'失败原因:'+err);
res.sendjson({"suc":0,"fail":"操作失败"});
}
else res.sendjson({"suc":1});
})//remove
});//collcetion
});//mongo
}
module.exports = home;
|
gzsll/X-APM | x-apm-app/src/main/java/github/tornaco/xposedmoduletest/ui/tiles/app/CrashDump.java | package github.tornaco.xposedmoduletest.ui.tiles.app;
import android.content.Context;
import android.widget.RelativeLayout;
import dev.nick.tiles.tile.QuickTile;
import dev.nick.tiles.tile.SwitchTileView;
import github.tornaco.xposedmoduletest.R;
import github.tornaco.xposedmoduletest.xposed.app.XAPMManager;
/**
* Created by guohao4 on 2017/11/10.
* Email: <EMAIL>
*/
public class CrashDump extends QuickTile {
public CrashDump(final Context context) {
super(context);
this.titleRes = R.string.title_crash_dump;
this.summaryRes = R.string.summary_crash_dump;
this.iconRes = R.drawable.ic_developer_board_black_24dp;
this.tileView = new SwitchTileView(context) {
@Override
protected void onBindActionView(RelativeLayout container) {
super.onBindActionView(container);
setChecked(XAPMManager.get().isServiceAvailable() && XAPMManager.get().isAppCrashDumpEnabled());
}
@Override
protected int getImageViewBackgroundRes() {
return R.drawable.tile_bg_green;
}
@Override
protected void onCheckChanged(boolean checked) {
super.onCheckChanged(checked);
if (XAPMManager.get().isServiceAvailable()) {
XAPMManager.get().setAppCrashDumpEnabled(checked);
}
}
};
}
}
|
ImageMarkup/isic | isic/ingest/migrations/0021_auto_20210310_2256.py | <filename>isic/ingest/migrations/0021_auto_20210310_2256.py<gh_stars>0
# Generated by Django 3.1.4 on 2021-03-10 22:56
# flake8: noqa
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ingest', '0020_auto_20210309_2108'),
]
operations = [
migrations.AlterField(
model_name='contributor',
name='default_attribution',
field=models.CharField(
blank=True,
help_text='Text which must be reproduced by users of your images, to comply with Creative Commons Attribution requirements.',
max_length=255,
verbose_name='Default Attribution',
),
),
]
|
ayuryev/java-client | src/test/java/io/appium/java_client/ios/AppIOSTest.java | package io.appium.java_client.ios;
import io.appium.java_client.ios.options.XCUITestOptions;
import io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException;
import org.junit.BeforeClass;
import org.openqa.selenium.SessionNotCreatedException;
import java.net.URL;
import java.time.Duration;
import static io.appium.java_client.TestResources.testAppZip;
public class AppIOSTest extends BaseIOSTest {
public static final String BUNDLE_ID = "io.appium.TestApp";
@BeforeClass
public static void beforeClass() throws Exception {
final String ip = startAppiumServer();
if (service == null || !service.isRunning()) {
throw new AppiumServerHasNotBeenStartedLocallyException("An appium server node is not started!");
}
XCUITestOptions options = new XCUITestOptions()
.setDeviceName(DEVICE_NAME)
.setCommandTimeouts(Duration.ofSeconds(240))
.setApp(testAppZip().toAbsolutePath().toString())
.setWdaLaunchTimeout(WDA_LAUNCH_TIMEOUT);
try {
driver = new IOSDriver(new URL("http://" + ip + ":" + PORT + "/wd/hub"), options);
} catch (SessionNotCreatedException e) {
options.useNewWDA();
driver = new IOSDriver(new URL("http://" + ip + ":" + PORT + "/wd/hub"), options);
}
}
} |
kamilagraf/react-swm-icon-pack | src/Icons/Basket.js | <reponame>kamilagraf/react-swm-icon-pack<gh_stars>10-100
import * as React from 'react';
import { iconType } from '../types';
import createIcon from '../helpers/createIcon';
const Basket = ({ color, strokeWidth, set }) => {
const Broken = () => (
<g>
<path d="M5 20H19L21 10H3L4 15" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M3 10L9 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M18 7L15 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />{' '}
</g>
);
const Curved = () => (
<g>
<path d="M21 10L15 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M3 10L9 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path
d="M3 10H21L19.6431 16.7845C19.2692 18.6542 17.6275 20 15.7208 20H8.27922C6.37249 20 4.73083 18.6542 4.35689 16.7845L3 10Z"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
</g>
);
const Duotone = () => (
<g>
<path opacity="0.15" d="M3 10H21L19 20H5L3 10Z" fill={color} />
<path d="M21 10H3L5 20H19L21 10Z" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M3 10L9 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M21 10L15 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</g>
);
const Outline = () => (
<g>
<path d="M21 10H3L5 20H19L21 10Z" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M3 10L9 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<path d="M21 10L15 4" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</g>
);
switch (set) {
case 'broken':
return <Broken />;
case 'curved':
return <Curved />;
case 'duotone':
return <Duotone />;
case 'outline':
return <Outline />;
default:
return <Outline />;
}
};
Basket.propTypes = {
props: iconType,
};
Basket.displayName = 'Basket';
export default createIcon(Basket);
|
JerryFox/karel | scripts/prikazy-funkce-slovnik.js | /*
* [Česky]
* Projekt: Robot Karel
* Copyright: Viz KOPIROVANI v kořenovém adresáři projektu
*
* [English]
* Project: Karel, the Robot
* Copyright: See COPYING in the top level directory
*/
// JavaScript - příkazy a ovládání slovníku
// ===========================================================================
// =~ Globální nastavení ~====================================================
// Při smazání slovníku: zachovat zobrazený příkaz, nebo nezachovat?
nastaveni.zachovej_zobrazeny_prikaz = false;
// ===========================================================================
// =~ Globální proměnné ~=====================================================
// Počet systémových příkazů
prikazy.pocet_systemovych = prikazy.seznam.length;
// Tooltip
prikazy.tooltip = {
spustit: "Proveď příkaz",
zastavit: "Zastav provádění příkazu"
};
// Prefix pro ID příkazů
prikazy.id_prefix = "příkaz ";
// Prefix pro název příkazů
prikazy.nazev_prefix = "název ";
// Prefix pro celý příkaz
prikazy.prikaz_prefix = "celý příkaz ";
// Zobrazený název, když není nic vybraného
prikazy.zadny_prikaz = "(žádný)";
// Panel nástrojů
prikazy.nastroje = new Array(
[ "zobraz", "tip-zobraz", "Ukaž příkaz", "Ukaž vybraný příkaz" ],
[ "smaz", "tip-smaz-prikaz", "Smaž příkaz", "Vymaž vybraný příkaz z paměti" ],
null,
[ "smaz-vse", "tip-smaz-vse", "Reset paměti", "Vymaž všechny naučené příkazy z paměti" ],
null,
[ "nacist", "tip-nacist", "Načti slovník", "Načti uložený slovník (i město)" ],
[ "ulozit", "tip-ulozit", "Ulož slovník", "Ulož slovník pro budoucí použití. " +
"Při ukládání se automaticky použije nejstarší formát vhodný pro uložení" ],
null,
[ "exportovat-12", "tip-exportovat-12", "Ulož slovník",
"Ulož slovník ve starším formátu rozpoznaném starším Karlem 1.2. "+
"Komentáře a prázdné řádky nebudou zachovány. Při ukládání se " +
"automaticky použije nejstarší formát vhodný pro uložení" ],
[ "exportovat-k99", "tip-exportovat-k99", "Exportuj slovník",
"Ulož slovník do formátu Visual Karel 99" ]
);
prikazy.nastroje.id_prefix = "slovnik-";
prikazy.nastroje.mys = "prikazy.mys_nastroje";
// Myš nad tlačítkem
prikazy.mys_tlacitko = new Mys(new Tooltip());
// Myš nad příkazem
prikazy.mys_prikaz = new Mys();
// Myš nad nástroji
prikazy.mys_nastroje = new Mys(new Tooltip());
// ===========================================================================
// =~ Základní funkce pro práci se slovníkem ~================================
// Kontrola prázdného slovníku
prikazy.je_slovnik_prazdny = function ()
{
return ( prikazy.seznam[prikazy.seznam.length-1].systemovy );
}
// Zobraz nový příkaz v seznamu příkazů
prikazy.pridej = function (prikaz)
{
var id = prikazy.id_prefix+prikaz.jmeno;
var nazev = prikazy.nazev_prefix+prikaz.jmeno;
var prikaz_id = prikazy.prikaz_prefix+prikaz.jmeno;
// Elementy
var element = document.getElementById('zobrazene');
var element_prikaz = document.createElement('DIV');
var element_nazev = element_prikaz.cloneNode(false);
var element_nazev_text = document.createElement('DIV');
// Text
element_nazev_text.appendChild( document.createTextNode(prikaz.jmeno) );
// Události
tvoric.nastav_udalosti_mysi( element_nazev, "prikazy.mys_prikaz",
'\''+nazev+'\'', '\''+prikaz.jmeno+'\'' );
// Styly
element_prikaz.className = "prikaz";
element_nazev.className = "nazev";
element_nazev.id = nazev;
element_nazev_text.className = "nazev-text";
element_prikaz.id = prikaz_id;
// Tlačítko
var element_tlacitko = tvoric.vytvor_tlacitko( false, id,
"prikazy.mys_tlacitko", '\''+id+'\'', '\''+prikaz.jmeno+'\'' );
// Tvar
element_nazev.appendChild( element_nazev_text );
element_prikaz.appendChild( element_tlacitko );
element_prikaz.appendChild( element_nazev );
// Zařazení do HTML
element.appendChild( element_prikaz );
}
// Smaž příkaz ze zobrazeného seznamu příkazů
prikazy.zrus = function (prikaz)
{
var prikaz_id = prikazy.prikaz_prefix+prikaz.jmeno;
var element_prikaz = document.getElementById( prikaz_id );
element_prikaz.parentNode.removeChild(element_prikaz);
}
// Inicializace nového příkazu
prikazy.nastav_novy = function (prikaz)
{
prikaz.zobrazit = true;
prikaz.spust = prikazy.jadro.UZIVATELSKY;
prikaz.kompatibilita = prikazy.min_VERZE_10;
prikaz.verze_ulozeni = prikazy.min_VERZE_10;
}
// Přidej nový příkaz a obnov zobrazený seznam
prikazy.pridej_novy = function (prikaz)
{
if ( ! (prikaz instanceof Object) ) {
ladici_vypis( DETAIL, "prikazy.pridej_novy", "přidávám nový příkaz " +
prikaz );
prikaz = { jmeno: prikaz, telo: [ [ prikazy.KONEC ]] };
prikaz.telo.unshift( [ prikazy.NAZEV, prikaz ] );
} else {
ladici_vypis( DETAIL, "prikazy.pridej_novy", "přidávám nový příkaz " +
prikaz.jmeno );
}
prikazy.nastav_novy(prikaz);
prikazy.seznam.push(prikaz);
prikazy.prikaz[prikaz.jmeno] = prikaz;
prikazy.pridej( prikaz );
return prikaz;
}
// Změň příkaz v tělech ostatních příkazů. Pokud je novy_prikaz prazdny, smaže
// ho z příkazu
prikazy.nahrad_telo = function (stary_prikaz, novy_prikaz)
{
if ( novy_prikaz ) {
ladici_vypis( DETAIL, "prikazy.nahrad_telo", "měním výskyt příkazu " +
stary_prikaz.jmeno + " na " + novy_prikaz.jmeno );
} else {
ladici_vypis( DETAIL, "prikazy.nahrad_telo", "mažu výskyt příkazu " +
stary_prikaz.jmeno + " ze všech příkazů" );
}
var i = prikazy.seznam.length-1;
while ( i >= 0 && !prikazy.seznam[i].systemovy ) {
var prikaz = prikazy.seznam[i];
for ( var j = prikaz.telo.length-1; j >= 0; j-- ) {
if ( prikaz.telo[j][0] == stary_prikaz ) {
if ( novy_prikaz ) {
ladici_vypis( LADENI, "prikazy.nahrad_telo", "změna v příkazu " +
prikaz.jmeno + " na řádce " + (j+1) );
prikaz.telo[j][0] = novy_prikaz;
} else {
ladici_vypis( LADENI, "prikazy.nahrad_telo", "smazán z příkazu " +
prikaz.jmeno + " z řádky " + (j+1) );
var pred_prikazem = prikaz.telo.slice(0, j);
var po_prikazu = prikaz.telo.slice(j+1);
prikaz.telo = pred_prikazem.concat(po_prikazu);
}
}
}
i--;
}
}
// Připrav příkaz na smazání
prikazy.dokonci_smazani = function (prikaz)
{
delete prikaz.telo;
}
// Obnov informaci v seznamu známých příkazů. Pokud není uveden novy_prikaz,
// je příkaz smazán
prikazy.zmen_seznam = function (stary_prikaz, novy_prikaz)
{
if ( novy_prikaz ) {
ladici_vypis( LADENI, "prikazy.zmen_seznam",
"měním v seznamu příkaz " + stary_prikaz.jmeno + " na " +
novy_prikaz.jmeno );
} else {
ladici_vypis( LADENI, "prikazy.zmen_seznam",
"mažu ze seznamu příkaz " + stary_prikaz.jmeno );
}
var i;
for ( i = prikazy.seznam.length - 1; i >= 0; i-- ) {
if ( prikazy.seznam[i] == stary_prikaz ) {
if ( novy_prikaz ) {
prikazy.seznam[i] = novy_prikaz;
} else {
prikazy.dokonci_smazani( prikazy.seznam[i] );
var pred_prikazem = prikazy.seznam.slice(0, i);
var po_prikazu = prikazy.seznam.slice(i+1);
prikazy.seznam = pred_prikazem.concat(po_prikazu);
}
break;
}
}
if ( i < 0 ) {
ladici_vypis( CHYBA, "prikazy.zmen_seznam", "příkaz " +
stary_prikaz.jmeno + " nebyl nalezen v seznamu příkazů" );
return false;
} else {
return true;
}
}
// Změň příkaz a obnov zobrazenou informaci
prikazy.zmen_prikaz = function (stary_prikaz, novy_prikaz)
{
if ( stary_prikaz.jmeno == novy_prikaz.jmeno ) {
ladici_vypis( DETAIL, "prikazy.zmen_prikaz", "aktualizuji příkaz " +
novy_prikaz.jmeno );
} else {
ladici_vypis( DETAIL, "prikazy.zmen_prikaz", "měním příkaz " +
stary_prikaz.jmeno + " na " + novy_prikaz.jmeno );
}
// Obnov seznam známých příkazů
if ( !this.zmen_seznam(stary_prikaz, novy_prikaz) ) {
ladici_vypis( CHYBA, "prikazy.zmen_prikaz", "starý příkaz " +
stary_prikaz.jmeno + " nenalezen v seznamu, raději přidám nový" );
prikazy.pridej_novy( novy_prikaz );
return;
}
// Atributy nového příkazu
prikazy.nastav_novy(novy_prikaz);
delete prikazy.prikaz[stary_prikaz.jmeno];
prikazy.prikaz[novy_prikaz.jmeno] = novy_prikaz;
var stary_id = prikazy.id_prefix+stary_prikaz.jmeno;
var stary_nazev = prikazy.nazev_prefix+stary_prikaz.jmeno;
var novy_id = prikazy.id_prefix+novy_prikaz.jmeno;
var novy_nazev = prikazy.nazev_prefix+novy_prikaz.jmeno;
var novy_prikaz_id = prikazy.prikaz_prefix+novy_prikaz.jmeno;
// Zjisti, jestli je co upravovat u tlačítek a zobrazení
if ( novy_nazev != stary_nazev || novy_id != stary_id
|| stary_prikaz.jmeno != novy_prikaz.jmeno ) {
var element_nazev = document.getElementById(stary_nazev);
var element_ikona = document.getElementById(stary_id);
var element_maska = tvoric.maska_tlacitka_z_ikony(element_ikona);
var element_prikaz = element_nazev.parentNode;
// Uprav Id
element_nazev.id = novy_nazev;
element_ikona.id = novy_id;
element_prikaz.id = novy_prikaz_id;
// Uprav název
element_nazev.firstChild.firstChild.nodeValue = novy_prikaz.jmeno;
// Obnov informaci myši
tvoric.nastav_udalosti_mysi( element_nazev, "prikazy.mys_prikaz",
'\''+novy_nazev+'\'', '\''+novy_prikaz.jmeno+'\'' );
tvoric.nastav_udalosti_mysi( element_maska, "prikazy.mys_tlacitko",
'\''+novy_id+'\'', '\''+novy_prikaz.jmeno+'\'' );
// Informace objektu myši, že proběhlo přejmenování
ladici_vypis( LADENI, "prikazy.zmen_prikaz",
"měním detaily u názvu příkazu" );
prikazy.mys_prikaz.prejmenuj(stary_nazev, novy_nazev, novy_prikaz.jmeno);
ladici_vypis( LADENI, "prikazy.zmen_prikaz",
"měním detaily u tlačítka příkazu" );
prikazy.mys_tlacitko.prejmenuj(stary_id, novy_id, novy_prikaz.jmeno);
}
this.nahrad_telo( stary_prikaz, novy_prikaz );
prikazy.dokonci_smazani( stary_prikaz );
}
// Smaž příkaz (i z těl příkazů) a obnov zobrazenou informaci
prikazy.proved_smazani = function (prikaz)
{
ladici_vypis( DETAIL, "prikazy.proved_smazani", "mažu příkaz " +
prikaz.jmeno );
var nazev = prikazy.nazev_prefix+prikaz.jmeno;
// Informace objektu myši, že proběhlo přejmenování
ladici_vypis( LADENI, "prikazy.proved_smazani",
"mažu detaily u názvu příkazu" );
prikazy.mys_prikaz.smaz(nazev, prikaz.jmeno);
ladici_vypis( LADENI, "prikazy.proved_smazani",
"mažu detaily u tlačítka příkazu" );
prikazy.mys_tlacitko.smaz(nazev, prikaz.jmeno);
// Vymaž příkaz z těl ostatních příkazů
this.nahrad_telo( prikaz );
// Vymaž příkaz ze známých příkazů
this.zmen_seznam( prikaz );
// Smaž příkaz ze zobrazeného seznamu příkazů
this.zrus( prikaz );
}
prikazy.obsahuje_prikaz = function (ktery_prikaz)
{
var seznam = new Array();
for ( var i = 0; i < prikazy.seznam.length; i++ ) {
var prikaz = prikazy.seznam[i];
if ( !prikaz.systemovy && prikaz != ktery_prikaz ) {
for ( var j = 0; j < prikaz.telo.length; j++ ) {
if ( prikaz.telo[j][0] == ktery_prikaz ) {
seznam.push(prikaz.jmeno);
break;
}
}
}
}
return seznam;
}
prikazy.smaz_prikaz = function (prikaz)
{
if ( !prikazy.test_spusteni() ) return;
var obsahuje = prikazy.obsahuje_prikaz(prikaz);
var detail = "";
if ( obsahuje.length ) {
var detail_prikaz;
if ( obsahuje.length == 1 ) {
detail_prikaz = "příkazu ";
} else {
detail_prikaz = "příkazech ";
}
detail = "\n\nPříkaz je obsažen v " + detail_prikaz + obsahuje.join(", ") +
".";
}
var uzivatel_chce = window.confirm( "Opravdu si přejete smazat příkaz " +
prikaz.jmeno + "?" + detail );
if ( uzivatel_chce ) {
prikazy.proved_smazani(prikaz);
editor.smaz_prikaz(prikaz);
}
}
// Smaž celý slovník
prikazy.smaz_vse = function (bez_kontroly, bez_noveho_prikazu)
{
if ( !prikazy.test_spusteni() ) return;
if ( prikazy.je_slovnik_prazdny() ) {
if ( !bez_noveho_prikazu ) {
if ( editor.nastav_zmenu() && !nastaveni.zachovej_zobrazeny_prikaz ) {
if ( bez_kontroly
|| !bez_kontroly && window.confirm( "Slovník je prázdný. " +
"Přejete si začít novým příkazem?" ) ) {
editor.prikaz_novy(true);
}
} else {
if ( !bez_kontroly ) alert( "Slovník je prázdný." );
editor.prikaz_novy(true);
}
}
} else {
if ( bez_kontroly || !bez_kontroly
&& window.confirm( "Opravdu si přejete smazat všechny příkazy?" ) ) {
var i = prikazy.seznam.length-1;
while ( i >= 0 && !prikazy.seznam[i].systemovy ) {
var prikaz = prikazy.seznam[i];
prikazy.proved_smazani(prikaz);
if ( nastaveni.zachovej_zobrazeny_prikaz ) editor.smaz_prikaz(prikaz);
i--;
}
if ( !bez_noveho_prikazu ) {
if ( !editor.nastav_zmenu() || !nastaveni.zachovej_zobrazeny_prikaz ) {
editor.prikaz_novy(true);
}
}
}
}
}
// Obnov ikonu přehrání a tooltip
prikazy.obnov_stav = function (probiha)
{
var element = document.getElementById('zobrazene');
if ( probiha ) {
element.className = "zastavit";
} else {
element.className = "spustit";
}
for ( var i = 0; i < prikazy.seznam.length; i++ ) {
var prikaz = prikazy.seznam[i];
if ( prikaz.zobrazit ) {
var element_ikona = document.getElementById(prikazy.id_prefix+prikaz.jmeno);
var element_maska = element_ikona.parentNode.nextSibling;
}
}
prikazy.mys_tlacitko.tooltip.prekresli();
}
// Nahrání nového slovníku
prikazy.nahraj_slovnik = function (novy_slovnik)
{
if ( !novy_slovnik.length ) return;
if ( !window.confirm(
"Opravdu si přejete nahrát příkazy?\n\n" +
"Všechny současné příkazy budou ztraceny. Mám pokračovat?" ) ) return;
if ( !prikazy.test_spusteni() ) return;
prikazy.smaz_vse(true, true);
for ( var i = 0; i < novy_slovnik.length; i++ ) {
var prikaz = novy_slovnik[i];
prikazy.pridej_novy( prikaz );
}
if ( editor.nastav_zmenu() ) {
if ( !nastaveni.zachovej_zobrazeny_prikaz ) {
editor.prikaz_novy(true);
}
} else {
editor.prikaz_novy(true);
}
}
// ===========================================================================
// =~ Práce myši ~============================================================
prikazy.mys_tlacitko.proved_zvyrazneni = function(info, detail)
{
return true;
}
prikazy.mys_tlacitko.prekresli_stav = function(info, detail, zvyraznen,
stisknut, vybran)
{
tvoric.zvyraznovac(info, zvyraznen, stisknut, vybran);
}
prikazy.mys_tlacitko.proved_vyber = function(info, detail)
{
var vysledek = prikazy.jadro.proved_nebo_zastav(detail);
vysledek.zobraz_chybu();
return false;
}
prikazy.mys_prikaz.proved_zvyrazneni = function(info, detail)
{
return true;
}
prikazy.mys_prikaz.proved_vyber = function(info, detail)
{
var element = document.getElementById('vybrany-prikaz');
element.lastChild.nodeValue = detail;
return true;
}
prikazy.mys_prikaz.zrus_vyber = function(info, detail)
{
var element = document.getElementById('vybrany-prikaz');
element.lastChild.nodeValue = prikazy.zadny_prikaz;
return true;
}
prikazy.mys_prikaz.smaz_vyber = function(info, detail)
{
this.zrus_vyber(info, detail);
}
prikazy.mys_prikaz.prekresli_stav = function(info, detail, zvyraznen, stisknut,
vybran)
{
var element = document.getElementById(info);
var vybrany = (vybran?"-vybrany":"");
var zvyrazneny = (zvyraznen?"-zvyrazneny":"");
if ( stisknut ) {
element.className = "nazev"+vybrany+"-stisknuty";
} else {
element.className = "nazev"+vybrany+zvyrazneny;
}
}
prikazy.mys_nastroje.proved_zvyrazneni = function(info, detail)
{
return true;
}
prikazy.mys_nastroje.prekresli_stav = function(nastroj, detail, zvyraznen,
stisknut, vybran)
{
tvoric.zvyraznovac(prikazy.nastroje.id_prefix+nastroj, zvyraznen, stisknut,
vybran);
}
prikazy.mys_nastroje.proved_vyber = function(nastroj, detail)
{
switch (nastroj) {
case "zobraz":
case "smaz": {
// Kontrola vybraného příkazu
var jmeno = prikazy.vybrany_prikaz();
if ( jmeno && prikazy.prikaz[jmeno] ) {
prikazy.zobraz_nebo_smaz( nastroj, jmeno );
} else {
alert( "Není vybrán žádný příkaz.\n\n" +
"Příkaz vyberte klepnutím myši." );
}
break;
}
case "smaz-vse": {
prikazy.smaz_vse();
break;
}
case "ulozit":
case "exportovat-12":
case "exportovat-k99": {
if ( editor.kontrola_zmeny() ) {
if ( nastroj != "exportovat-k99" ) {
data.ukladani.uloz_slovnik(
(nastroj == "ulozit"?data.FORMAT_20:data.FORMAT_12) );
} else {
data.ukladani.export_slovnik_k99();
}
}
break;
}
case "nacist": {
data.nacitani.nacti();
}
}
return false;
}
// Zobraz nebo smaž vybraný příkaz
prikazy.zobraz_nebo_smaz = function(akce, jmeno)
{
var prikaz = prikazy.prikaz[jmeno];
if ( !prikaz.systemovy ) {
if ( akce == "zobraz" ) {
editor.zobraz_vybrany_prikaz();
} else {
prikazy.smaz_prikaz(prikaz);
}
} else {
if ( akce == "zobraz" ) {
alert( "Nelze prohližet systémový příkaz." );
// TODO: Nápověda k systémovým příkazům?
} else {
alert( "Nelze smazat systémový příkaz." );
}
}
}
// Který příkaz je vybraný
prikazy.vybrany_prikaz = function()
{
return this.mys_prikaz.vybran.detail;
}
// Vyber konkrétní příkaz
prikazy.vyber_prikaz = function(nazev)
{
var prikaz = prikazy.prikaz[nazev];
if ( prikaz && prikaz.zobrazit ) {
this.mys_prikaz.vyber(prikazy.nazev_prefix+nazev, prikaz.jmeno);
} else {
ladici_vypis(CHYBA, "prikazy.vyber_prikaz", nazev,
"výběr neexistujícího příkazu");
}
}
// ===========================================================================
// =~ Tooltipy ~==============================================================
prikazy.text_tooltipu = function (jmeno)
{
var tooltip = new Object();
if ( prikazy.jadro.probiha() ) {
tooltip.nadpis = prikazy.tooltip["zastavit"];
} else {
tooltip.nadpis = prikazy.tooltip["spustit"]+" "+jmeno;
if ( prikazy.prikaz[jmeno] instanceof Object ) {
var prikaz = prikazy.prikaz[jmeno];
if ( prikaz.tooltip ) {
tooltip.popis = prikaz.tooltip;
} else if ( prikaz.telo ) {
var radka = prikaz.telo[0];
if ( radka && radka[0] == prikazy.HLAVICKA_KOMENTAR ) {
tooltip.popis = radka[1];
}
}
}
}
return tooltip;
}
prikazy.mys_tlacitko.tooltip.muzu_zobrazit = function (info, detail)
{
return ( prikazy.prikaz[detail] ? true : false );
}
prikazy.mys_tlacitko.tooltip.obnov = function (tooltip, info, detail)
{
var obsah = prikazy.text_tooltipu(detail);
tvoric.obnov_tooltip(tooltip, "", obsah.nadpis, obsah.popis);
}
prikazy.mys_tlacitko.tooltip.zjisti_rozmery = function (objekt)
{
var rozmery = zjisti_rozmery(objekt);
var element = document.getElementById('zobrazene');
if ( element.scrollTop ) {
rozmery = posun_y(rozmery, -element.scrollTop);
}
return rozmery;
}
prikazy.mys_nastroje.tooltip.obnov = function (tooltip, info, detail)
{
tvoric.obnov_tooltip(tooltip, detail.ikona, detail.nadpis, detail.popis);
}
|
esy-ocaml-old/esy-old | __tests__/util/misc.js | <reponame>esy-ocaml-old/esy-old
/* @flow */
import * as misc from '../../src/util/misc.js';
test('sortAlpha', () => {
expect([
'foo@6.x',
'foo@^6.5.0',
'foo@~6.8.x',
'foo@^6.7.0',
'foo@~6.8.0',
'foo@^6.8.0',
'foo@6.8.0',
].sort(misc.sortAlpha)).toEqual([
'foo@6.8.0',
'foo@6.x',
'foo@^6.5.0',
'foo@^6.7.0',
'foo@^6.8.0',
'foo@~6.8.0',
'foo@~6.8.x',
]);
});
test('has2xxResponse', () => {
const response = {responseCode: 200};
expect(misc.has2xxResponse(response)).toEqual(true);
});
|
tarceri/VK-GL-CTS | external/vulkancts/modules/vulkan/sparse_resources/vktSparseResourcesImageSparseBinding.cpp | /*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group 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.
*
*//*!
* \file vktSparseResourcesImageSparseBinding.cpp
* \brief Sparse fully resident images with mipmaps tests
*//*--------------------------------------------------------------------*/
#include "vktSparseResourcesBufferSparseBinding.hpp"
#include "vktSparseResourcesTestsUtil.hpp"
#include "vktSparseResourcesBase.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkDefs.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPlatform.hpp"
#include "vkPrograms.hpp"
#include "vkMemUtil.hpp"
#include "vkBarrierUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "deUniquePtr.hpp"
#include "deStringUtil.hpp"
#include <string>
#include <vector>
using namespace vk;
namespace vkt
{
namespace sparse
{
namespace
{
class ImageSparseBindingCase : public TestCase
{
public:
ImageSparseBindingCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const ImageType imageType,
const tcu::UVec3& imageSize,
const VkFormat format,
const bool useDeviceGroups = false);
TestInstance* createInstance (Context& context) const;
virtual void checkSupport (Context& context) const;
private:
const bool m_useDeviceGroups;
const ImageType m_imageType;
const tcu::UVec3 m_imageSize;
const VkFormat m_format;
};
ImageSparseBindingCase::ImageSparseBindingCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const ImageType imageType,
const tcu::UVec3& imageSize,
const VkFormat format,
const bool useDeviceGroups)
: TestCase (testCtx, name, description)
, m_useDeviceGroups (useDeviceGroups)
, m_imageType (imageType)
, m_imageSize (imageSize)
, m_format (format)
{
}
void ImageSparseBindingCase::checkSupport (Context& context) const
{
context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_SPARSE_BINDING);
if (!isImageSizeSupported(context.getInstanceInterface(), context.getPhysicalDevice(), m_imageType, m_imageSize))
TCU_THROW(NotSupportedError, "Image size not supported for device");
}
class ImageSparseBindingInstance : public SparseResourcesBaseInstance
{
public:
ImageSparseBindingInstance (Context& context,
const ImageType imageType,
const tcu::UVec3& imageSize,
const VkFormat format,
const bool useDeviceGroups);
tcu::TestStatus iterate (void);
private:
const bool m_useDeviceGroups;
const ImageType m_imageType;
const tcu::UVec3 m_imageSize;
const VkFormat m_format;
};
ImageSparseBindingInstance::ImageSparseBindingInstance (Context& context,
const ImageType imageType,
const tcu::UVec3& imageSize,
const VkFormat format,
const bool useDeviceGroups)
: SparseResourcesBaseInstance (context, useDeviceGroups)
, m_useDeviceGroups (useDeviceGroups)
, m_imageType (imageType)
, m_imageSize (imageSize)
, m_format (format)
{
}
tcu::TestStatus ImageSparseBindingInstance::iterate (void)
{
const InstanceInterface& instance = m_context.getInstanceInterface();
{
// Create logical device supporting both sparse and compute queues
QueueRequirementsVec queueRequirements;
queueRequirements.push_back(QueueRequirements(VK_QUEUE_SPARSE_BINDING_BIT, 1u));
queueRequirements.push_back(QueueRequirements(VK_QUEUE_COMPUTE_BIT, 1u));
createDeviceSupportingQueues(queueRequirements);
}
const VkPhysicalDevice physicalDevice = getPhysicalDevice();
VkImageCreateInfo imageSparseInfo;
std::vector<DeviceMemorySp> deviceMemUniquePtrVec;
const DeviceInterface& deviceInterface = getDeviceInterface();
const Queue& sparseQueue = getQueue(VK_QUEUE_SPARSE_BINDING_BIT, 0);
const Queue& computeQueue = getQueue(VK_QUEUE_COMPUTE_BIT, 0);
const PlanarFormatDescription formatDescription = getPlanarFormatDescription(m_format);
// Go through all physical devices
for (deUint32 physDevID = 0; physDevID < m_numPhysicalDevices; ++physDevID)
{
const deUint32 firstDeviceID = physDevID;
const deUint32 secondDeviceID = (firstDeviceID + 1) % m_numPhysicalDevices;
imageSparseInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; //VkStructureType sType;
imageSparseInfo.pNext = DE_NULL; //const void* pNext;
imageSparseInfo.flags = VK_IMAGE_CREATE_SPARSE_BINDING_BIT; //VkImageCreateFlags flags;
imageSparseInfo.imageType = mapImageType(m_imageType); //VkImageType imageType;
imageSparseInfo.format = m_format; //VkFormat format;
imageSparseInfo.extent = makeExtent3D(getLayerSize(m_imageType, m_imageSize)); //VkExtent3D extent;
imageSparseInfo.arrayLayers = getNumLayers(m_imageType, m_imageSize); //deUint32 arrayLayers;
imageSparseInfo.samples = VK_SAMPLE_COUNT_1_BIT; //VkSampleCountFlagBits samples;
imageSparseInfo.tiling = VK_IMAGE_TILING_OPTIMAL; //VkImageTiling tiling;
imageSparseInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //VkImageLayout initialLayout;
imageSparseInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT; //VkImageUsageFlags usage;
imageSparseInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; //VkSharingMode sharingMode;
imageSparseInfo.queueFamilyIndexCount = 0u; //deUint32 queueFamilyIndexCount;
imageSparseInfo.pQueueFamilyIndices = DE_NULL; //const deUint32* pQueueFamilyIndices;
if (m_imageType == IMAGE_TYPE_CUBE || m_imageType == IMAGE_TYPE_CUBE_ARRAY)
{
imageSparseInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
}
{
VkImageFormatProperties imageFormatProperties;
if (instance.getPhysicalDeviceImageFormatProperties(physicalDevice,
imageSparseInfo.format,
imageSparseInfo.imageType,
imageSparseInfo.tiling,
imageSparseInfo.usage,
imageSparseInfo.flags,
&imageFormatProperties) == VK_ERROR_FORMAT_NOT_SUPPORTED)
{
TCU_THROW(NotSupportedError, "Image format does not support sparse binding operations");
}
imageSparseInfo.mipLevels = getMipmapCount(m_format, formatDescription, imageFormatProperties, imageSparseInfo.extent);
}
// Create sparse image
const Unique<VkImage> imageSparse(createImage(deviceInterface, getDevice(), &imageSparseInfo));
// Create sparse image memory bind semaphore
const Unique<VkSemaphore> imageMemoryBindSemaphore(createSemaphore(deviceInterface, getDevice()));
// Get sparse image general memory requirements
const VkMemoryRequirements imageMemoryRequirements = getImageMemoryRequirements(deviceInterface, getDevice(), *imageSparse);
// Check if required image memory size does not exceed device limits
if (imageMemoryRequirements.size > getPhysicalDeviceProperties(instance, getPhysicalDevice(secondDeviceID)).limits.sparseAddressSpaceSize)
TCU_THROW(NotSupportedError, "Required memory size for sparse resource exceeds device limits");
DE_ASSERT((imageMemoryRequirements.size % imageMemoryRequirements.alignment) == 0);
{
std::vector<VkSparseMemoryBind> sparseMemoryBinds;
const deUint32 numSparseBinds = static_cast<deUint32>(imageMemoryRequirements.size / imageMemoryRequirements.alignment);
const deUint32 memoryType = findMatchingMemoryType(instance, getPhysicalDevice(secondDeviceID), imageMemoryRequirements, MemoryRequirement::Any);
if (memoryType == NO_MATCH_FOUND)
return tcu::TestStatus::fail("No matching memory type found");
if (firstDeviceID != secondDeviceID)
{
VkPeerMemoryFeatureFlags peerMemoryFeatureFlags = (VkPeerMemoryFeatureFlags)0;
const deUint32 heapIndex = getHeapIndexForMemoryType(instance, getPhysicalDevice(secondDeviceID), memoryType);
deviceInterface.getDeviceGroupPeerMemoryFeatures(getDevice(), heapIndex, firstDeviceID, secondDeviceID, &peerMemoryFeatureFlags);
if (((peerMemoryFeatureFlags & VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT) == 0) ||
((peerMemoryFeatureFlags & VK_PEER_MEMORY_FEATURE_COPY_DST_BIT) == 0))
{
TCU_THROW(NotSupportedError, "Peer memory does not support COPY_SRC and COPY_DST");
}
}
for (deUint32 sparseBindNdx = 0; sparseBindNdx < numSparseBinds; ++sparseBindNdx)
{
const VkSparseMemoryBind sparseMemoryBind = makeSparseMemoryBind(deviceInterface, getDevice(),
imageMemoryRequirements.alignment, memoryType, imageMemoryRequirements.alignment * sparseBindNdx);
deviceMemUniquePtrVec.push_back(makeVkSharedPtr(Move<VkDeviceMemory>(check<VkDeviceMemory>(sparseMemoryBind.memory), Deleter<VkDeviceMemory>(deviceInterface, getDevice(), DE_NULL))));
sparseMemoryBinds.push_back(sparseMemoryBind);
}
const VkSparseImageOpaqueMemoryBindInfo opaqueBindInfo = makeSparseImageOpaqueMemoryBindInfo(*imageSparse, static_cast<deUint32>(sparseMemoryBinds.size()), sparseMemoryBinds.data());
const VkDeviceGroupBindSparseInfo devGroupBindSparseInfo =
{
VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO_KHR, //VkStructureType sType;
DE_NULL, //const void* pNext;
firstDeviceID, //deUint32 resourceDeviceIndex;
secondDeviceID, //deUint32 memoryDeviceIndex;
};
const VkBindSparseInfo bindSparseInfo =
{
VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, //VkStructureType sType;
m_useDeviceGroups ? &devGroupBindSparseInfo : DE_NULL, //const void* pNext;
0u, //deUint32 waitSemaphoreCount;
DE_NULL, //const VkSemaphore* pWaitSemaphores;
0u, //deUint32 bufferBindCount;
DE_NULL, //const VkSparseBufferMemoryBindInfo* pBufferBinds;
1u, //deUint32 imageOpaqueBindCount;
&opaqueBindInfo, //const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds;
0u, //deUint32 imageBindCount;
DE_NULL, //const VkSparseImageMemoryBindInfo* pImageBinds;
1u, //deUint32 signalSemaphoreCount;
&imageMemoryBindSemaphore.get() //const VkSemaphore* pSignalSemaphores;
};
// Submit sparse bind commands for execution
VK_CHECK(deviceInterface.queueBindSparse(sparseQueue.queueHandle, 1u, &bindSparseInfo, DE_NULL));
}
deUint32 imageSizeInBytes = 0;
for (deUint32 planeNdx = 0; planeNdx < formatDescription.numPlanes; ++planeNdx)
for (deUint32 mipmapNdx = 0; mipmapNdx < imageSparseInfo.mipLevels; ++mipmapNdx)
imageSizeInBytes += getImageMipLevelSizeInBytes(imageSparseInfo.extent, imageSparseInfo.arrayLayers, formatDescription, planeNdx, mipmapNdx, BUFFER_IMAGE_COPY_OFFSET_GRANULARITY);
std::vector<VkBufferImageCopy> bufferImageCopy(formatDescription.numPlanes * imageSparseInfo.mipLevels);
{
deUint32 bufferOffset = 0;
for (deUint32 planeNdx = 0; planeNdx < formatDescription.numPlanes; ++planeNdx)
{
const VkImageAspectFlags aspect = (formatDescription.numPlanes > 1) ? getPlaneAspect(planeNdx) : VK_IMAGE_ASPECT_COLOR_BIT;
for (deUint32 mipmapNdx = 0; mipmapNdx < imageSparseInfo.mipLevels; ++mipmapNdx)
{
bufferImageCopy[planeNdx*imageSparseInfo.mipLevels + mipmapNdx] =
{
bufferOffset, // VkDeviceSize bufferOffset;
0u, // deUint32 bufferRowLength;
0u, // deUint32 bufferImageHeight;
makeImageSubresourceLayers(aspect, mipmapNdx, 0u, imageSparseInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource;
makeOffset3D(0, 0, 0), // VkOffset3D imageOffset;
vk::getPlaneExtent(formatDescription, imageSparseInfo.extent, planeNdx, mipmapNdx) // VkExtent3D imageExtent;
};
bufferOffset += getImageMipLevelSizeInBytes(imageSparseInfo.extent, imageSparseInfo.arrayLayers, formatDescription, planeNdx, mipmapNdx, BUFFER_IMAGE_COPY_OFFSET_GRANULARITY);
}
}
}
// Create command buffer for compute and transfer operations
const Unique<VkCommandPool> commandPool(makeCommandPool(deviceInterface, getDevice(), computeQueue.queueFamilyIndex));
const Unique<VkCommandBuffer> commandBuffer(allocateCommandBuffer(deviceInterface, getDevice(), *commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY));
// Start recording commands
beginCommandBuffer(deviceInterface, *commandBuffer);
const VkBufferCreateInfo inputBufferCreateInfo = makeBufferCreateInfo(imageSizeInBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
const Unique<VkBuffer> inputBuffer (createBuffer(deviceInterface, getDevice(), &inputBufferCreateInfo));
const de::UniquePtr<Allocation> inputBufferAlloc (bindBuffer(deviceInterface, getDevice(), getAllocator(), *inputBuffer, MemoryRequirement::HostVisible));
std::vector<deUint8> referenceData(imageSizeInBytes);
for (deUint32 valueNdx = 0; valueNdx < imageSizeInBytes; ++valueNdx)
{
referenceData[valueNdx] = static_cast<deUint8>((valueNdx % imageMemoryRequirements.alignment) + 1u);
}
{
deMemcpy(inputBufferAlloc->getHostPtr(), referenceData.data(), imageSizeInBytes);
flushAlloc(deviceInterface, getDevice(), *inputBufferAlloc);
const VkBufferMemoryBarrier inputBufferBarrier = makeBufferMemoryBarrier (
VK_ACCESS_HOST_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
*inputBuffer,
0u,
imageSizeInBytes
);
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 1u, &inputBufferBarrier, 0u, DE_NULL);
}
{
std::vector<VkImageMemoryBarrier> imageSparseTransferDstBarriers;
for (deUint32 planeNdx = 0; planeNdx < formatDescription.numPlanes; ++planeNdx)
{
const VkImageAspectFlags aspect = (formatDescription.numPlanes > 1) ? getPlaneAspect(planeNdx) : VK_IMAGE_ASPECT_COLOR_BIT;
imageSparseTransferDstBarriers.push_back( makeImageMemoryBarrier (
0u,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
*imageSparse,
makeImageSubresourceRange(aspect, 0u, imageSparseInfo.mipLevels, 0u, imageSparseInfo.arrayLayers),
sparseQueue.queueFamilyIndex != computeQueue.queueFamilyIndex ? sparseQueue.queueFamilyIndex : VK_QUEUE_FAMILY_IGNORED,
sparseQueue.queueFamilyIndex != computeQueue.queueFamilyIndex ? computeQueue.queueFamilyIndex : VK_QUEUE_FAMILY_IGNORED
));
}
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imageSparseTransferDstBarriers.size()), imageSparseTransferDstBarriers.data());
}
deviceInterface.cmdCopyBufferToImage(*commandBuffer, *inputBuffer, *imageSparse, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<deUint32>(bufferImageCopy.size()), bufferImageCopy.data());
{
std::vector<VkImageMemoryBarrier> imageSparseTransferSrcBarriers;
for (deUint32 planeNdx = 0; planeNdx < formatDescription.numPlanes; ++planeNdx)
{
const VkImageAspectFlags aspect = (formatDescription.numPlanes > 1) ? getPlaneAspect(planeNdx) : VK_IMAGE_ASPECT_COLOR_BIT;
imageSparseTransferSrcBarriers.push_back( makeImageMemoryBarrier (
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
*imageSparse,
makeImageSubresourceRange(aspect, 0u, imageSparseInfo.mipLevels, 0u, imageSparseInfo.arrayLayers)
));
}
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imageSparseTransferSrcBarriers.size()), imageSparseTransferSrcBarriers.data());
}
const VkBufferCreateInfo outputBufferCreateInfo = makeBufferCreateInfo(imageSizeInBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
const Unique<VkBuffer> outputBuffer (createBuffer(deviceInterface, getDevice(), &outputBufferCreateInfo));
const de::UniquePtr<Allocation> outputBufferAlloc (bindBuffer(deviceInterface, getDevice(), getAllocator(), *outputBuffer, MemoryRequirement::HostVisible));
deviceInterface.cmdCopyImageToBuffer(*commandBuffer, *imageSparse, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *outputBuffer, static_cast<deUint32>(bufferImageCopy.size()), bufferImageCopy.data());
{
const VkBufferMemoryBarrier outputBufferBarrier = makeBufferMemoryBarrier
(
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_HOST_READ_BIT,
*outputBuffer,
0u,
imageSizeInBytes
);
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &outputBufferBarrier, 0u, DE_NULL);
}
// End recording commands
endCommandBuffer(deviceInterface, *commandBuffer);
const VkPipelineStageFlags stageBits[] = { VK_PIPELINE_STAGE_TRANSFER_BIT };
// Submit commands for execution and wait for completion
submitCommandsAndWait(deviceInterface, getDevice(), computeQueue.queueHandle, *commandBuffer, 1u, &imageMemoryBindSemaphore.get(), stageBits,
0, DE_NULL, m_useDeviceGroups, firstDeviceID);
// Retrieve data from buffer to host memory
invalidateAlloc(deviceInterface, getDevice(), *outputBufferAlloc);
// Wait for sparse queue to become idle
deviceInterface.queueWaitIdle(sparseQueue.queueHandle);
const deUint8* outputData = static_cast<const deUint8*>(outputBufferAlloc->getHostPtr());
for (deUint32 planeNdx = 0; planeNdx < formatDescription.numPlanes; ++planeNdx)
{
for (deUint32 mipmapNdx = 0; mipmapNdx < imageSparseInfo.mipLevels; ++mipmapNdx)
{
const deUint32 mipLevelSizeInBytes = getImageMipLevelSizeInBytes(imageSparseInfo.extent, imageSparseInfo.arrayLayers, formatDescription, planeNdx, mipmapNdx);
const deUint32 bufferOffset = static_cast<deUint32>(bufferImageCopy[ planeNdx * imageSparseInfo.mipLevels + mipmapNdx].bufferOffset);
if (deMemCmp(outputData + bufferOffset, &referenceData[bufferOffset], mipLevelSizeInBytes) != 0)
return tcu::TestStatus::fail("Failed");
}
}
}
return tcu::TestStatus::pass("Passed");
}
TestInstance* ImageSparseBindingCase::createInstance (Context& context) const
{
return new ImageSparseBindingInstance(context, m_imageType, m_imageSize, m_format, m_useDeviceGroups);
}
} // anonymous ns
tcu::TestCaseGroup* createImageSparseBindingTestsCommon(tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup> testGroup, const bool useDeviceGroup = false)
{
const std::vector<TestImageParameters> imageParameters =
{
{ IMAGE_TYPE_1D, { tcu::UVec3(512u, 1u, 1u ), tcu::UVec3(1024u, 1u, 1u), tcu::UVec3(11u, 1u, 1u) }, getTestFormats(IMAGE_TYPE_1D) },
{ IMAGE_TYPE_1D_ARRAY, { tcu::UVec3(512u, 1u, 64u), tcu::UVec3(1024u, 1u, 8u), tcu::UVec3(11u, 1u, 3u) }, getTestFormats(IMAGE_TYPE_1D_ARRAY) },
{ IMAGE_TYPE_2D, { tcu::UVec3(512u, 256u, 1u ), tcu::UVec3(1024u, 128u, 1u), tcu::UVec3(11u, 137u, 1u) }, getTestFormats(IMAGE_TYPE_2D) },
{ IMAGE_TYPE_2D_ARRAY, { tcu::UVec3(512u, 256u, 6u ), tcu::UVec3(1024u, 128u, 8u), tcu::UVec3(11u, 137u, 3u) }, getTestFormats(IMAGE_TYPE_2D_ARRAY) },
{ IMAGE_TYPE_3D, { tcu::UVec3(512u, 256u, 6u ), tcu::UVec3(1024u, 128u, 8u), tcu::UVec3(11u, 137u, 3u) }, getTestFormats(IMAGE_TYPE_3D) },
{ IMAGE_TYPE_CUBE, { tcu::UVec3(256u, 256u, 1u ), tcu::UVec3(128u, 128u, 1u), tcu::UVec3(137u, 137u, 1u) }, getTestFormats(IMAGE_TYPE_CUBE) },
{ IMAGE_TYPE_CUBE_ARRAY, { tcu::UVec3(256u, 256u, 6u ), tcu::UVec3(128u, 128u, 8u), tcu::UVec3(137u, 137u, 3u) }, getTestFormats(IMAGE_TYPE_CUBE_ARRAY) }
};
for (size_t imageTypeNdx = 0; imageTypeNdx < imageParameters.size(); ++imageTypeNdx)
{
const ImageType imageType = imageParameters[imageTypeNdx].imageType;
de::MovePtr<tcu::TestCaseGroup> imageTypeGroup (new tcu::TestCaseGroup(testCtx, getImageTypeName(imageType).c_str(), ""));
for (size_t formatNdx = 0; formatNdx < imageParameters[imageTypeNdx].formats.size(); ++formatNdx)
{
VkFormat format = imageParameters[imageTypeNdx].formats[formatNdx].format;
tcu::UVec3 imageSizeAlignment = getImageSizeAlignment(format);
de::MovePtr<tcu::TestCaseGroup> formatGroup (new tcu::TestCaseGroup(testCtx, getImageFormatID(format).c_str(), ""));
for (size_t imageSizeNdx = 0; imageSizeNdx < imageParameters[imageTypeNdx].imageSizes.size(); ++imageSizeNdx)
{
const tcu::UVec3 imageSize = imageParameters[imageTypeNdx].imageSizes[imageSizeNdx];
// skip test for images with odd sizes for some YCbCr formats
if ((imageSize.x() % imageSizeAlignment.x()) != 0)
continue;
if ((imageSize.y() % imageSizeAlignment.y()) != 0)
continue;
std::ostringstream stream;
stream << imageSize.x() << "_" << imageSize.y() << "_" << imageSize.z();
formatGroup->addChild(new ImageSparseBindingCase(testCtx, stream.str(), "", imageType, imageSize, format, useDeviceGroup));
}
imageTypeGroup->addChild(formatGroup.release());
}
testGroup->addChild(imageTypeGroup.release());
}
return testGroup.release();
}
tcu::TestCaseGroup* createImageSparseBindingTests(tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "image_sparse_binding", "Image Sparse Binding"));
return createImageSparseBindingTestsCommon(testCtx, testGroup);
}
tcu::TestCaseGroup* createDeviceGroupImageSparseBindingTests(tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "device_group_image_sparse_binding", "Device Group Image Sparse Binding"));
return createImageSparseBindingTestsCommon(testCtx, testGroup, true);
}
} // sparse
} // vkt
|
frunox/dynamic-portfolio | client/src/components/LogoutForm/LogoutModal.js | import React, { useState, useContext } from "react";
import Modal from 'react-modal';
import { Button } from 'semantic-ui-react'
import { Redirect, useHistory } from "react-router-dom";
import API from "../../utils/API";
import './styles.css'
import DevDataContext from '../../contexts/DevDataContext';
import SetupContext from '../../contexts/SetupContext';
Modal.setAppElement(document.getElementById('root'))
// console.log('in LogoutModal')
const LogoutModal = () => {
const devCtx = useContext(DevDataContext);
const setupCtx = useContext(SetupContext);
// console.log("LOGOUTMODAL setupCtx", setupCtx)
const [state, setState] = useState({
loggedIn: null,
clearUser: false
});
// const [modalIsOpen, setModalIsOpen] = useState(false)
const history = useHistory();
let openModal = setupCtx.state.logoutModalOpen;
console.log('LOGOUTMODAL openModal', openModal)
const logout = () => {
// console.log('Logout logout');
localStorage.setItem("jtsy-login", "false");
setState({
...state,
loggedIn: false
})
// history.push("/home")
setupCtx.updateLoggedIn();
setupCtx.openLogoutModal(false);
};
const developer = () => {
// console.log('Logout developer');
setState({
...state,
loggedIn: false
})
setupCtx.updateLoggedIn();
setupCtx.openLogoutModal(false);
};
const removeUser = () => {
// console.log('LogoutForm removeUser');
API.deleteDeveloper();
localStorage.clear();
setState({
...state,
clearUser: true
});
setupCtx.resetSetup();
devCtx.resetDev();
setupCtx.openLogoutModal(false);
};
let content = (
<div>
<Modal isOpen={openModal} onRequestClose={() => setupCtx.openLogoutModal(false)}
// shouldCloseOnOverlayClick={false}
style={{
overlay: {
backgroundColor: 'rgba(155, 155, 155, 0.5)'
},
content: {
borderRadius: '10px',
top: '90px',
border: '1px solid black',
width: '400px',
margin: '0 auto',
height: '255px',
}
}}
>
<h1>Log Out</h1>
<div
className="confirmButton"
onClick={logout}>
<button type="submit">Confirm</button>
</div>
<div
className="removeButton"
onClick={removeUser}>
<button type="submit">Remove All User Data</button>
</div>
<div
className="returnButton"
onClick={developer}>
<button type="submit">Return</button>
</div>
{!state.loggedIn && (
<Redirect to={'/developer'} />
)}
{state.loggedIn && (
<Redirect to={'/developer'} />
)}
{state.clearUser && (
<Redirect to={'/'} />
)}
</Modal >
</div >
);
return content;
}
export default LogoutModal;
|
tech-microworld/magic4j | magic4j-application/src/main/java/com/itgacl/magic4j/modules/sys/controller/SysTenantController.java | package com.itgacl.magic4j.modules.sys.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itgacl.magic4j.common.base.SuperController;
import com.itgacl.magic4j.common.bean.PageData;
import com.itgacl.magic4j.common.bean.PageParam;
import com.itgacl.magic4j.libcommon.annotation.Auth;
import com.itgacl.magic4j.libcommon.annotation.Log;
import com.itgacl.magic4j.libcommon.bean.R;
import com.itgacl.magic4j.libcommon.constant.Constants;
import com.itgacl.magic4j.modules.sys.dto.SysTenantDTO;
import com.itgacl.magic4j.modules.sys.entity.SysTenant;
import com.itgacl.magic4j.modules.sys.service.SysTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
/**
* SysTenantController
* @author 孤傲苍狼
* @since 2020-04-02
*/
@Api(tags = "租户管理")
@Auth(name = "租户管理")
@RestController
@RequestMapping("/api/sys/tenant")
public class SysTenantController extends SuperController{
@Autowired
private SysTenantService sysTenantService;
/**
* 创建
* @param sysTenant
* @return
*/
@ApiOperation("新增")
@Log(operation="创建",remark = "创建租户",moduleName = "租户管理")
@PostMapping
public R<Void> create(@RequestBody @Validated(Constants.Create.class) SysTenantDTO sysTenant){
sysTenantService.create(sysTenant);
return R.ok();
}
/**
* 更新
* @param sysTenant
* @return
*/
@ApiOperation("修改")
@Log(operation="修改",remark = "修改租户",moduleName = "租户管理")
@PutMapping
public R<Void> update(@RequestBody @Validated(Constants.Update.class) SysTenantDTO sysTenant){
sysTenantService.update(sysTenant);
return R.ok();
}
/**
* 根据ID查找
* @param id
* @return
*/
@ApiOperation("根据ID查找")
@Auth(isAuth = false)//不进行权限控制
@GetMapping("/{id}")
public R<SysTenantDTO> get(@PathVariable("id") Long id){
SysTenantDTO sysTenantDTO = sysTenantService.getSysTenantById(id);
return R.ok(sysTenantDTO);
}
/**
* 查询全部
* @return
*/
@ApiOperation("查询全部")
@Auth(isAuth = false)//不进行权限控制
@GetMapping
public R<List<SysTenantDTO>> get() {
List<SysTenantDTO> sysTenantList = sysTenantService.getList(null);
return R.ok(sysTenantList);
}
/**
* 根据ID批量删除
* @param ids
* @return
*/
@ApiOperation("根据ID批量删除")
@Log(operation="删除",remark = "根据ID批量删除",moduleName = "租户管理")
@DeleteMapping("/{ids}")
public R<Void> delete(@PathVariable("ids") Long[] ids){
if(ids.length==1){
sysTenantService.deleteById(ids[0]);
}else {
List<Long> idList = Arrays.asList(ids);
sysTenantService.deleteByIds(idList);
}
return R.ok();
}
/**
* 分页查询
* @return
*/
@ApiOperation("分页查询")
@Auth(isAuth = false)//不进行权限控制
@GetMapping(value = "/list")
public R<PageData<SysTenant>> pageList(SysTenantDTO sysTenantDTO, PageParam pageParam){
//构建查询条件
QueryWrapper<SysTenant> queryWrapper = buildQueryWrapper(sysTenantDTO);
Page<SysTenant> page = getPage(pageParam);//获取mybatisPlus分页对象
IPage<SysTenant> pageInfo = sysTenantService.page(page,queryWrapper);//mybatisPlus分页查询
return R.ok(PageData.build(pageInfo));
}
/**
* 构建查询条件QueryWrapper
* @param sysTenantDTO
* @return
*/
private QueryWrapper<SysTenant> buildQueryWrapper(SysTenantDTO sysTenantDTO) {
QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc(SysTenant.CREATE_TIME);
if(StrUtil.isNotEmpty(sysTenantDTO.getName())){
queryWrapper.like(SysTenant.NAME,sysTenantDTO.getName());
}
if(ObjectUtil.isNotEmpty(sysTenantDTO.getStatus())){
queryWrapper.eq(SysTenant.STATUS,sysTenantDTO.getStatus());
}
return queryWrapper;
}
} |
sigurasg/ghidra | Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/ThreadStorageSymbolInternals.java | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.bin.format.pdb2.pdbreader.symbol;
import ghidra.app.util.bin.format.pdb2.pdbreader.*;
/**
* This class represents various flavors of Internals of Thread Storage symbol.
* <P>
* Note: we do not necessarily understand each of these symbol type classes. Refer to the
* base class for more information.
*/
public class ThreadStorageSymbolInternals extends AbstractSymbolInternals {
/**
* Factory for "32" version of ThreadStorageSymbolInternals.
* @param pdb {@link AbstractPdb} to which this symbol belongs.
* @param reader {@link PdbByteReader} from which this internals is deserialized.
* @return the parsed instance.
* @throws PdbException upon error parsing a field.
*/
public static ThreadStorageSymbolInternals parse32(PdbByteReader reader, AbstractPdb pdb)
throws PdbException {
ThreadStorageSymbolInternals result = new ThreadStorageSymbolInternals(pdb);
result.typeRecordNumber = RecordNumber.parse(pdb, reader, RecordCategory.TYPE, 32);
result.offset = reader.parseVarSizedOffset(32);
result.segment = pdb.parseSegment(reader);
result.name = reader.parseString(pdb, StringParseType.StringUtf8Nt);
reader.align4();
return result;
}
/**
* Factory for "3216" version of ThreadStorageSymbolInternals.
* @param pdb {@link AbstractPdb} to which this symbol belongs.
* @param reader {@link PdbByteReader} from which this internals is deserialized.
* @return the parsed instance.
* @throws PdbException upon error parsing a field.
*/
public static ThreadStorageSymbolInternals parse3216(PdbByteReader reader, AbstractPdb pdb)
throws PdbException {
ThreadStorageSymbolInternals result = new ThreadStorageSymbolInternals(pdb);
result.offset = reader.parseVarSizedOffset(32);
result.segment = pdb.parseSegment(reader);
result.typeRecordNumber = RecordNumber.parse(pdb, reader, RecordCategory.TYPE, 16);
result.name = reader.parseString(pdb, StringParseType.StringUtf8St);
reader.align4();
return result;
}
/**
* Factory for "32St" version of ThreadStorageSymbolInternals.
* @param pdb {@link AbstractPdb} to which this symbol belongs.
* @param reader {@link PdbByteReader} from which this internals is deserialized.
* @return the parsed instance.
* @throws PdbException upon error parsing a field.
*/
public static ThreadStorageSymbolInternals parse32St(PdbByteReader reader, AbstractPdb pdb)
throws PdbException {
ThreadStorageSymbolInternals result = new ThreadStorageSymbolInternals(pdb);
result.typeRecordNumber = RecordNumber.parse(pdb, reader, RecordCategory.TYPE, 32);
result.offset = reader.parseVarSizedOffset(32);
result.segment = pdb.parseSegment(reader);
result.name = reader.parseString(pdb, StringParseType.StringUtf8St);
reader.align4();
return result;
}
protected RecordNumber typeRecordNumber;
protected long offset;
protected int segment;
protected String name;
/**
* Constructor for this symbol internals.
* @param pdb {@link AbstractPdb} to which this symbol belongs.
*/
public ThreadStorageSymbolInternals(AbstractPdb pdb) {
super(pdb);
}
/**
* Returns the offset.
* @return Offset.
*/
public long getOffset() {
return offset;
}
/**
* Returns the segment.
* @return Segment.
*/
public int getSegment() {
return segment;
}
/**
* Returns the type record number.
* @return Type record number.
*/
public RecordNumber getTypeRecordNumber() {
return typeRecordNumber;
}
/**
* Returns the name.
* @return Name.
*/
public String getName() {
return name;
}
@Override
public void emit(StringBuilder builder) {
builder.append(String.format(": [%04X:%08X], Type: %s, %s", segment, offset,
pdb.getTypeRecord(typeRecordNumber), name));
}
}
|
EnjoyLifeFund/py36pkgs | astropy/io/ascii/ipac.py | <gh_stars>0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""An extensible ASCII table reader and writer.
ipac.py:
Classes to read IPAC table format
:Copyright: Smithsonian Astrophysical Observatory (2011)
:Author: <NAME> (<EMAIL>)
"""
from __future__ import absolute_import, division, print_function
import re
from collections import defaultdict, OrderedDict
from textwrap import wrap
from warnings import warn
from ...extern import six
from ...extern.six.moves import zip
from . import core
from . import fixedwidth
from . import basic
from ...utils.exceptions import AstropyUserWarning
from ...table.pprint import _format_funcs, get_auto_format_func
class IpacFormatErrorDBMS(Exception):
def __str__(self):
return '{0}\nSee {1}'.format(
super(Exception, self).__str__(),
'http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/DBMSrestriction.html')
class IpacFormatError(Exception):
def __str__(self):
return '{0}\nSee {1}'.format(
super(Exception, self).__str__(),
'http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html')
class IpacHeaderSplitter(core.BaseSplitter):
'''Splitter for Ipac Headers.
This splitter is similar its parent when reading, but supports a
fixed width format (as required for Ipac table headers) for writing.
'''
process_line = None
process_val = None
delimiter = '|'
delimiter_pad = ''
skipinitialspace = False
comment = r'\s*\\'
write_comment = r'\\'
col_starts = None
col_ends = None
def join(self, vals, widths):
pad = self.delimiter_pad or ''
delimiter = self.delimiter or ''
padded_delim = pad + delimiter + pad
bookend_left = delimiter + pad
bookend_right = pad + delimiter
vals = [' ' * (width - len(val)) + val for val, width in zip(vals, widths)]
return bookend_left + padded_delim.join(vals) + bookend_right
class IpacHeader(fixedwidth.FixedWidthHeader):
"""IPAC table header"""
splitter_class = IpacHeaderSplitter
# Defined ordered list of possible types. Ordering is needed to
# distinguish between "d" (double) and "da" (date) as defined by
# the IPAC standard for abbreviations. This gets used in get_col_type().
col_type_list = (('integer', core.IntType),
('long', core.IntType),
('double', core.FloatType),
('float', core.FloatType),
('real', core.FloatType),
('char', core.StrType),
('date', core.StrType))
definition = 'ignore'
start_line = None
def process_lines(self, lines):
"""Generator to yield IPAC header lines, i.e. those starting and ending with
delimiter character (with trailing whitespace stripped)"""
delim = self.splitter.delimiter
for line in lines:
line = line.rstrip()
if line.startswith(delim) and line.endswith(delim):
yield line.strip(delim)
def update_meta(self, lines, meta):
"""
Extract table-level comments and keywords for IPAC table. See:
http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html#kw
"""
def process_keyword_value(val):
"""
Take a string value and convert to float, int or str, and strip quotes
as needed.
"""
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
# Strip leading/trailing quote. The spec says that a matched pair
# of quotes is required, but this code will allow a non-quoted value.
for quote in ('"', "'"):
if val.startswith(quote) and val.endswith(quote):
val = val[1:-1]
break
return val
table_meta = meta['table']
table_meta['comments'] = []
table_meta['keywords'] = OrderedDict()
keywords = table_meta['keywords']
re_keyword = re.compile(r'\\'
r'(?P<name> \w+)'
r'\s* = (?P<value> .+) $',
re.VERBOSE)
for line in lines:
# Keywords and comments start with "\". Once the first non-slash
# line is seen then bail out.
if not line.startswith('\\'):
break
m = re_keyword.match(line)
if m:
name = m.group('name')
val = process_keyword_value(m.group('value'))
# IPAC allows for continuation keywords, e.g.
# \SQL = 'WHERE '
# \SQL = 'SELECT (25 column names follow in next row.)'
if name in keywords and isinstance(val, six.string_types):
prev_val = keywords[name]['value']
if isinstance(prev_val, six.string_types):
val = prev_val + val
keywords[name] = {'value': val}
else:
# Comment is required to start with "\ "
if line.startswith('\\ '):
val = line[2:].strip()
if val:
table_meta['comments'].append(val)
def get_col_type(self, col):
for (col_type_key, col_type) in self.col_type_list:
if col_type_key.startswith(col.raw_type.lower()):
return col_type
else:
raise ValueError('Unknown data type ""{}"" for column "{}"'.format(
col.raw_type, col.name))
def get_cols(self, lines):
"""
Initialize the header Column objects from the table ``lines``.
Based on the previously set Header attributes find or create the column names.
Sets ``self.cols`` with the list of Columns.
Parameters
----------
lines : list
List of table lines
"""
header_lines = self.process_lines(lines) # generator returning valid header lines
header_vals = [vals for vals in self.splitter(header_lines)]
if len(header_vals) == 0:
raise ValueError('At least one header line beginning and ending with '
'delimiter required')
elif len(header_vals) > 4:
raise ValueError('More than four header lines were found')
# Generate column definitions
cols = []
start = 1
for i, name in enumerate(header_vals[0]):
col = core.Column(name=name.strip(' -'))
col.start = start
col.end = start + len(name)
if len(header_vals) > 1:
col.raw_type = header_vals[1][i].strip(' -')
col.type = self.get_col_type(col)
if len(header_vals) > 2:
col.unit = header_vals[2][i].strip() or None # Can't strip dashes here
if len(header_vals) > 3:
# The IPAC null value corresponds to the io.ascii bad_value.
# In this case there isn't a fill_value defined, so just put
# in the minimal entry that is sure to convert properly to the
# required type.
#
# Strip spaces but not dashes (not allowed in NULL row per
# https://github.com/astropy/astropy/issues/361)
null = header_vals[3][i].strip()
fillval = '' if issubclass(col.type, core.StrType) else '0'
self.data.fill_values.append((null, fillval, col.name))
start = col.end + 1
cols.append(col)
# Correct column start/end based on definition
if self.ipac_definition == 'right':
col.start -= 1
elif self.ipac_definition == 'left':
col.end += 1
self.names = [x.name for x in cols]
self.cols = cols
def str_vals(self):
if self.DBMS:
IpacFormatE = IpacFormatErrorDBMS
else:
IpacFormatE = IpacFormatError
namelist = self.colnames
if self.DBMS:
countnamelist = defaultdict(int)
for name in self.colnames:
countnamelist[name.lower()] += 1
doublenames = [x for x in countnamelist if countnamelist[x] > 1]
if doublenames != []:
raise IpacFormatE('IPAC DBMS tables are not case sensitive. '
'This causes duplicate column names: {0}'.format(doublenames))
for name in namelist:
m = re.match(r'\w+', name)
if m.end() != len(name):
raise IpacFormatE('{0} - Only alphanumeric characters and _ '
'are allowed in column names.'.format(name))
if self.DBMS and not(name[0].isalpha() or (name[0] == '_')):
raise IpacFormatE('Column name cannot start with numbers: {}'.format(name))
if self.DBMS:
if name in ['x', 'y', 'z', 'X', 'Y', 'Z']:
raise IpacFormatE('{0} - x, y, z, X, Y, Z are reserved names and '
'cannot be used as column names.'.format(name))
if len(name) > 16:
raise IpacFormatE(
'{0} - Maximum length for column name is 16 characters'.format(name))
else:
if len(name) > 40:
raise IpacFormatE(
'{0} - Maximum length for column name is 40 characters.'.format(name))
dtypelist = []
unitlist = []
nullist = []
for col in self.cols:
col_dtype = col.info.dtype
col_unit = col.info.unit
col_format = col.info.format
if col_dtype.kind in ['i', 'u']:
dtypelist.append('long')
elif col_dtype.kind == 'f':
dtypelist.append('double')
else:
dtypelist.append('char')
if col_unit is None:
unitlist.append('')
else:
unitlist.append(str(col.info.unit))
# This may be incompatible with mixin columns
null = col.fill_values[core.masked]
try:
format_key = (col_format, col.info.name)
auto_format_func = get_auto_format_func(id(col))
format_func = _format_funcs.get(format_key, auto_format_func)
nullist.append((format_func(col_format, null)).strip())
except Exception:
# It is possible that null and the column values have different
# data types (e.g. number and null = 'null' (i.e. a string).
# This could cause all kinds of exceptions, so a catch all
# block is needed here
nullist.append(str(null).strip())
return [namelist, dtypelist, unitlist, nullist]
def write(self, lines, widths):
'''Write header.
The width of each column is determined in Ipac.write. Writing the header
must be delayed until that time.
This function is called from there, once the width information is
available.'''
for vals in self.str_vals():
lines.append(self.splitter.join(vals, widths))
return lines
class IpacDataSplitter(fixedwidth.FixedWidthSplitter):
delimiter = ' '
delimiter_pad = ''
bookend = True
class IpacData(fixedwidth.FixedWidthData):
"""IPAC table data reader"""
comment = r'[|\\]'
start_line = 0
splitter_class = IpacDataSplitter
fill_values = [(core.masked, 'null')]
def write(self, lines, widths, vals_list):
""" IPAC writer, modified from FixedWidth writer """
for vals in vals_list:
lines.append(self.splitter.join(vals, widths))
return lines
class Ipac(basic.Basic):
r"""Read or write an IPAC format table. See
http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html::
\\name=value
\\ Comment
| column1 | column2 | column3 | column4 | column5 |
| double | double | int | double | char |
| unit | unit | unit | unit | unit |
| null | null | null | null | null |
2.0978 29.09056 73765 2.06000 B8IVpMnHg
Or::
|-----ra---|----dec---|---sao---|------v---|----sptype--------|
2.09708 29.09056 73765 2.06000 B8IVpMnHg
The comments and keywords defined in the header are available via the output
table ``meta`` attribute::
>>> import os
>>> from astropy.io import ascii
>>> filename = os.path.join(ascii.__path__[0], 'tests/t/ipac.dat')
>>> data = ascii.read(filename)
>>> print(data.meta['comments'])
['This is an example of a valid comment']
>>> for name, keyword in data.meta['keywords'].items():
... print(name, keyword['value'])
...
intval 1
floatval 2300.0
date Wed Sp 20 09:48:36 1995
key_continue IPAC keywords can continue across lines
Note that there are different conventions for characters occuring below the
position of the ``|`` symbol in IPAC tables. By default, any character
below a ``|`` will be ignored (since this is the current standard),
but if you need to read files that assume characters below the ``|``
symbols belong to the column before or after the ``|``, you can specify
``definition='left'`` or ``definition='right'`` respectively when reading
the table (the default is ``definition='ignore'``). The following examples
demonstrate the different conventions:
* ``definition='ignore'``::
| ra | dec |
| float | float |
1.2345 6.7890
* ``definition='left'``::
| ra | dec |
| float | float |
1.2345 6.7890
* ``definition='right'``::
| ra | dec |
| float | float |
1.2345 6.7890
IPAC tables can specify a null value in the header that is shown in place
of missing or bad data. On writing, this value defaults to ``null``.
To specify a different null value, use the ``fill_values`` option to
replace masked values with a string or number of your choice as
described in :ref:`io_ascii_write_parameters`::
>>> from astropy.io.ascii import masked
>>> fill = [(masked, 'N/A', 'ra'), (masked, -999, 'sptype')]
>>> ascii.write(data, format='ipac', fill_values=fill)
\ This is an example of a valid comment
...
| ra| dec| sai| v2| sptype|
| double| double| long| double| char|
| unit| unit| unit| unit| ergs|
| N/A| null| null| null| -999|
N/A 29.09056 null 2.06 -999
2345678901.0 3456789012.0 456789012 4567890123.0 567890123456789012
Parameters
----------
definition : str, optional
Specify the convention for characters in the data table that occur
directly below the pipe (``|``) symbol in the header column definition:
* 'ignore' - Any character beneath a pipe symbol is ignored (default)
* 'right' - Character is associated with the column to the right
* 'left' - Character is associated with the column to the left
DBMS : bool, optional
If true, this verifies that written tables adhere (semantically)
to the `IPAC/DBMS <http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/DBMSrestriction.html>`_
definition of IPAC tables. If 'False' it only checks for the (less strict)
`IPAC <http://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html>`_
definition.
"""
_format_name = 'ipac'
_io_registry_format_aliases = ['ipac']
_io_registry_can_write = True
_description = 'IPAC format table'
data_class = IpacData
header_class = IpacHeader
def __init__(self, definition='ignore', DBMS=False):
super(Ipac, self).__init__()
# Usually the header is not defined in __init__, but here it need a keyword
if definition in ['ignore', 'left', 'right']:
self.header.ipac_definition = definition
else:
raise ValueError("definition should be one of ignore/left/right")
self.header.DBMS = DBMS
def write(self, table):
"""
Write ``table`` as list of strings.
Parameters
----------
table : `~astropy.table.Table`
Input table data
Returns
-------
lines : list
List of strings corresponding to ASCII table
"""
# Set a default null value for all columns by adding at the end, which
# is the position with the lowest priority.
# We have to do it this late, because the fill_value
# defined in the class can be overwritten by ui.write
self.data.fill_values.append((core.masked, 'null'))
# Check column names before altering
self.header.cols = list(six.itervalues(table.columns))
self.header.check_column_names(self.names, self.strict_names, self.guessing)
core._apply_include_exclude_names(table, self.names, self.include_names, self.exclude_names)
# Now use altered columns
new_cols = list(six.itervalues(table.columns))
# link information about the columns to the writer object (i.e. self)
self.header.cols = new_cols
self.data.cols = new_cols
# Write header and data to lines list
lines = []
# Write meta information
if 'comments' in table.meta:
for comment in table.meta['comments']:
if len(str(comment)) > 78:
warn('Comment string > 78 characters was automatically wrapped.',
AstropyUserWarning)
for line in wrap(str(comment), 80, initial_indent='\\ ', subsequent_indent='\\ '):
lines.append(line)
if 'keywords' in table.meta:
keydict = table.meta['keywords']
for keyword in keydict:
try:
val = keydict[keyword]['value']
lines.append('\\{0}={1!r}'.format(keyword.strip(), val))
# meta is not standardized: Catch some common Errors.
except TypeError:
warn("Table metadata keyword {0} has been skipped. "
"IPAC metadata must be in the form {{'keywords':"
"{{'keyword': {{'value': value}} }}".format(keyword),
AstropyUserWarning)
ignored_keys = [key for key in table.meta if key not in ('keywords', 'comments')]
if any(ignored_keys):
warn("Table metadata keyword(s) {0} were not written. "
"IPAC metadata must be in the form {{'keywords':"
"{{'keyword': {{'value': value}} }}".format(ignored_keys),
AstropyUserWarning
)
# Usually, this is done in data.write, but since the header is written
# first, we need that here.
self.data._set_fill_values(self.data.cols)
# get header and data as strings to find width of each column
for i, col in enumerate(table.columns.values()):
col.headwidth = max([len(vals[i]) for vals in self.header.str_vals()])
# keep data_str_vals because they take some time to make
data_str_vals = []
col_str_iters = self.data.str_vals()
for vals in zip(*col_str_iters):
data_str_vals.append(vals)
for i, col in enumerate(table.columns.values()):
# FIXME: In Python 3.4, use max([], default=0).
# See: https://docs.python.org/3/library/functions.html#max
if data_str_vals:
col.width = max([len(vals[i]) for vals in data_str_vals])
else:
col.width = 0
widths = [max(col.width, col.headwidth) for col in table.columns.values()]
# then write table
self.header.write(lines, widths)
self.data.write(lines, widths, data_str_vals)
return lines
|
MonitorOnlineTeam/PollutantSource | src/pages/EmergencyTodoList/index.js | // import React, { Component } from 'react';
// import PointList from '../../components/PointList/PointsList';
// import {Button, Table, Select, Card, Form, Row, Col, Icon, message} from 'antd';
// import EmergencyDataList from '../../mockdata/EmergencyTodoList/EmergencyDataList.json';
// import moment from 'moment';
// import { connect } from 'dva';
// import RangePicker_ from '../../components/PointDetail/RangePicker_';
// import PageHeaderLayout from '../../layouts/PageHeaderLayout';
// import styless from '../ReplacementPartAdd/index.less';
// import {routerRedux} from 'dva/router';
// const FormItem = Form.Item;
// @Form.create()
// @connect()
// export default class EmergencyTodoList extends Component {
// constructor(props) {
// super(props);
// this.state = {
// EmergencyData: EmergencyDataList.EDataList.filter((item) => {
// return item.CheckState !== '审核通过';
// }),
// RangeDate: [moment().subtract(7, 'days'), moment()],
// TargetStatus: '',
// OpeartionPerson: '',
// DGIMNS: [],
// selectid: ''
// };
// }
// SearchEmergencyDataList = (value) => {
// this.setState({
// EmergencyData: [],
// DGIMNS: value
// });
// let dataList = [];
// EmergencyDataList.EDataList.map((item, _key) => {
// let isexist = false;
// if (item.CheckState !== '审核通过' && value.indexOf(item.DGIMN) > -1) {
// isexist = true;
// }
// if (isexist) { dataList.push(item); }
// });
// this.setState({
// EmergencyData: dataList,
// });
// };
// // 时间范围
// _handleDateChange=(_date, dateString) => {
// this.state.RangeDate = dateString;
// };
// // 任务状态
// _handleTargetChange=(value) => {
// this.setState({
// TargetStatus: value
// });
// };
// // 运维人
// _handleOperationChange=(value) => {
// this.setState({
// OpeartionPerson: value
// });
// };
// toggleForm = () => {
// this.setState({
// expandForm: !this.state.expandForm,
// });
// };
// SearchInfo=() => {
// }
// handleFormReset = () => {
// const { form } = this.props;
// form.resetFields();
// this.setState({
// formValues: {},
// });
// };
// renderSimpleForm() {
// const { getFieldDecorator } = this.props.form;
// return (
// <Form layout="inline">
// <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
// <Col md={9} sm={24}>
// <FormItem label="开始时间">
// {getFieldDecorator(`MaterialName`)(
// <RangePicker_ dateValue={this.state.RangeDate} format="YYYY-MM-DD" onChange={this._handleDateChange} style={{ width: '100%' }} />
// )}
// </FormItem>
// </Col>
// <Col md={5} sm={24}>
// <FormItem label="任务状态">
// {getFieldDecorator('Brand')(
// <Select placeholder="请选择"
// onChange={this._handleTargetChange} style={{ width: '100%' }}>
// <Option value="">全部</Option>
// <Option value="处理中">处理中</Option>
// <Option value="未审核">未审核</Option>
// <Option value="正在审核">正在审核</Option>
// <Option value="未通过">未通过</Option>
// <Option value="审核通过">审核通过</Option>
// </Select>
// )}
// </FormItem>
// </Col>
// <Col md={5} sm={24}>
// <FormItem label="处理人">
// {getFieldDecorator(`Specifications`)(
// <Select placeholder="请选择"
// onChange={this._handleOperationChange}
// style={{ width: '100%' }}>
// <Option value="">全部</Option>
// <Option value="小李">小李</Option>
// <Option value="小王">小王</Option>
// </Select>
// ) }
// </FormItem>
// </Col>
// <Col md={5} sm={24}>
// <Button type="primary" htmlType="submit" onClick={this.SearchInfo}>
// 查询 </Button>
// <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
// 重置
// </Button>
// </Col>
// </Row>
// </Form>
// );
// }
// renderForm() {
// return this.renderSimpleForm();
// }
// render() {
// const SCREEN_HEIGHT = document.querySelector('body').offsetHeight;
// const SCREEN_WIDTH = document.querySelector('body').offsetWidth;
// const thata = this;
// const EColumn = [
// {
// title: '故障类型',
// width: '15%',
// dataIndex: 'ExceptionType',
// align: 'center'
// }, {
// title: '处理人',
// width: '15%',
// dataIndex: 'User_Name',
// align: 'center'
// }, {
// title: '开始时间',
// width: '20%',
// dataIndex: 'BeginHandleTime',
// align: 'center'
// }, {
// title: '结束时间',
// width: '20%',
// dataIndex: 'EndHandleTime',
// align: 'center'
// }, {
// title: '签到',
// width: '20%',
// dataIndex: 'SignFlag',
// align: 'center'
// }, {
// title: '任务状态',
// width: '10%',
// dataIndex: 'CheckState',
// align: 'center'
// }
// ];
// const rowSelection = {
// onChange: (selectedRowKeys, selectedRows) => {
// let keys = [];
// selectedRowKeys.map(t => {
// if (Array.isArray(t)) {
// t.map(a => {
// if (a !== '') { keys.push(a); }
// });
// } else {
// if (t !== '') { keys.push(t); }
// }
// });
// },
// getCheckboxProps: record => ({
// disabled: record.name === 'Disabled User', // Column configuration not to be checked
// name: record.name,
// }),
// selectedRowKeys: [this.state.selectid]
// };
// return (
// <PointList handleChange={this.SearchEmergencyDataList}>
// <PageHeaderLayout title="待办列表">
// <Card bordered={false} >
// <div>
// <div className={styless.tableListForm}>{this.renderForm()}</div>
// <Button style={{marginLeft: 10, marginBottom: 10}} onClick={() => {
// if (this.state.selectid === '') {
// message.info('请选择应急任务!');
// } else {
// this.props.dispatch(routerRedux.push(`/emergency/emergencydetailinfolayout/${this.state.selectid}`));
// }
// }}> 查看 </Button>
// <Table
// columns={EColumn}
// dataSource={this.state.EmergencyData}
// rowKey="ExceptionHandleId"
// pagination={{
// showSizeChanger: true,
// showQuickJumper: true,
// 'total': this.state.EmergencyData.length,
// 'pageSize': 20,
// 'current': 1
// }}
// rowSelection={rowSelection}
// scroll={
// {
// y: 'calc(100vh - 458px)'
// }
// }
// onRow={(record, index) => {
// return {
// onClick: (a, b, c) => {
// this.setState({selectid: record.ExceptionHandleId});
// }, // 点击行
// onMouseEnter: () => {}, // 鼠标移入行
// };
// }}
// />
// </div></Card>
// </PageHeaderLayout>
// </PointList>
// );
// }
// }
|
Dr-Turtle/DRG_ModPresetManager | Source/FSD/Public/EItemNotificationType.h | #pragma once
#include "CoreMinimal.h"
#include "EItemNotificationType.generated.h"
UENUM()
enum class EItemNotificationType {
NewOverclock,
};
|
GameDevery/TweedeFrameworkRedux | Source/Framework/Core/Physics/TeBoxCollider.cpp | <gh_stars>10-100
#include "Physics/TeBoxCollider.h"
#include "Physics/TePhysics.h"
namespace te
{
BoxCollider::BoxCollider()
: Collider(TypeID_Core::TID_BoxCollider)
{ }
SPtr<BoxCollider> BoxCollider::Create(PhysicsScene& scene, const Vector3& extents,
const Vector3& position, const Quaternion& rotation)
{
return scene.CreateBoxCollider(extents, position, rotation);
}
}
|
shiyuting79118/- | web/common/dojo-release-1.12.2/dojox/grid/nls/DataGrid_ca.js | <gh_stars>1-10
//>>built
define("dojox/grid/nls/DataGrid_ca",{"dijit/nls/loading":{loadingState:"S'est\u00e0 carregant...",errorState:"Ens sap greu. S'ha produ\u00eft un error.",_localized:{}}});
//# sourceMappingURL=DataGrid_ca.js.map |
remcohh/monaca-test | src/config/settings.js | export default require(`./settings.${process.env.NODE_ENV}.json`);
|
Dipalikambale/dipalikambale.github.io | app/workers/open_api_trace_calls_count_worker.rb | <gh_stars>0
class OpenAPITraceCallsCountWorker < ActiveJob::Base
include Sidekiq::Worker
sidekiq_options queue: 'default', retry: true
def perform
OpenAPI::Client.find_each do |client|
OpenAPI::CallsCountTracing.create!(client: client, calls_count: client.calls_count, at: DateTime.now)
end
end
end
|
zoffixznet/project-euler | project-euler/551/euler_551_v2.cpp | <filename>project-euler/551/euler_551_v2.cpp
// The Expat License
//
// Copyright (c) 2017, <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
typedef unsigned long long ull;
const ull BASE = 10000;
ull lookup[BASE];
#define NUM_DIGITS 10000
ull digits = 1;
ull idx = 1;
static inline void print_n()
{
printf("a[%lld] = %lld\n", idx, digits);
fflush(stdout);
}
int main()
{
// Initialize the lookup.
for (int i = 0 ; i < BASE; i++)
{
int sum = 0;
int ii = i;
while (ii)
{
sum += ii % 10;
ii /= 10;
}
lookup[i] = sum;
}
#if 0
const long long LIM = 1000000;
#else
const long long LIM = 1000000000000000;
#endif
const long long STEP = 1000000000;
long long checkpoint = STEP;
for (;idx < LIM;idx++)
{
if (idx == checkpoint)
{
print_n();
checkpoint += STEP;
}
ull copy = digits;
while (copy)
{
digits += lookup[ copy % BASE];
copy /= BASE;
}
}
print_n();
return 0;
}
|
tuhongwei/python-exercise | awesome-python3-webapp/www/test.py | <filename>awesome-python3-webapp/www/test.py
import orm,asyncio
from models import User,Blog,Comment
async def test(loop):
await orm.create_pool(loop,user='root',password='<PASSWORD>',db='awesome')
u1 = User(name='Test',email='<EMAIL>',passwd='<PASSWORD>',image='about:blank')
u2 = User(name='Administrator',email='<EMAIL>',passwd='<PASSWORD>',image='about:blank')
await u1.save()
await u2.save()
await orm.destroy_pool()
loop = asyncio.get_event_loop()
loop.run_until_complete(test(loop))
loop.close() |
acabra85/bec-techacademy | 007-learn-apache-kafka/producer/src/main/java/dk/bec/gradprogram/kafka/KafkaProducerHelloWorld.java | <gh_stars>1-10
package dk.bec.gradprogram.kafka;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.time.LocalDateTime;
public class KafkaProducerHelloWorld {
public static final String HELLO_WORLD = "Hello world ";
private final KafkaProducer<String, String> producer;
public KafkaProducerHelloWorld(KafkaProducer<String, String> producer) {
this.producer = producer;
}
public void sendData(String topic) {
for (int i = 0; i < 10; i++) {
String value = HELLO_WORLD + LocalDateTime.now();
ProducerRecord<String, String> record = new ProducerRecord<>(topic, value);
producer.send(record);
}
producer.flush();
producer.close();
}
public void sendDataWithCallback(String topic, Callback callback) {
for (int i = 0; i < 10; i++) {
String value = HELLO_WORLD + LocalDateTime.now();
ProducerRecord<String, String> record = new ProducerRecord<>(topic, value);
producer.send(record, callback);
}
producer.flush();
producer.close();
}
public void sendDataWithKey(String topic) {
for (int i = 0; i < 10; i++) {
String value = HELLO_WORLD + LocalDateTime.now();
String key = "id_key_"+i;
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
producer.send(record);
}
producer.flush();
producer.close();
}
}
|
DrChainsaw/AmpControl | src/main/java/ampcontrol/model/training/model/vertex/ChannelMultVertex.java | package ampcontrol.model.training.model.vertex;
import org.deeplearning4j.nn.conf.graph.GraphVertex;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.inputs.InvalidInputTypeException;
import org.deeplearning4j.nn.conf.memory.LayerMemoryReport;
import org.deeplearning4j.nn.conf.memory.MemoryReport;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.nd4j.linalg.api.ndarray.INDArray;
/**
* {@link GraphVertex} which multiplies each channel in a convolutional activation of size [b,c,h,w] with a scalar of
* size (b,c) where b is the batch size, c is the number of channels, h is the height and w is the width. Used in
* squeeze-exitation networks: https://arxiv.org/abs/1709.01507
*
* @author <NAME>
*/
public class ChannelMultVertex extends GraphVertex {
@Override
public ChannelMultVertex clone() {
return new ChannelMultVertex();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ChannelMultVertex))
return false;
return true; //??
}
@Override
public int hashCode() {
return ChannelMultVertex.class.hashCode();
}
@Override
public long numParams(boolean backprop) {
return 0;
}
@Override
public int minVertexInputs() {
return 2;
}
@Override
public int maxVertexInputs() {
return 2;
}
@Override
public org.deeplearning4j.nn.graph.vertex.GraphVertex instantiate(ComputationGraph graph, String name, int idx,
INDArray paramsView, boolean initializeParams) {
return new ChannelMultVertexImpl(graph, name, idx);
}
@Override
public InputType getOutputType(int layerIndex, InputType... vertexInputs) throws InvalidInputTypeException {
InputType first = vertexInputs[0];
long numChannels = 0;
if (first instanceof InputType.InputTypeConvolutional) {
numChannels = ((InputType.InputTypeConvolutional) first).getChannels();
} else if (first instanceof InputType.InputTypeConvolutionalFlat) {
numChannels = ((InputType.InputTypeConvolutionalFlat) first).getDepth();
}
boolean ok = false;
InputType second = vertexInputs[1];
if (second instanceof InputType.InputTypeFeedForward) {
ok = ((InputType.InputTypeFeedForward) second).getSize() == numChannels;
}
if (!ok) {
throw new InvalidInputTypeException(
"Invalid input: Channel mult vertex " + this.toString() + "size mismatch! "
+ "Depth of first type (" + first + ") must be equal to size of second type ("
+ second + ")!");
}
return first;
}
@Override
public MemoryReport getMemoryReport(InputType... inputTypes) {
//No working memory in addition to output activations
return new LayerMemoryReport.Builder(null, ChannelMultVertex.class, inputTypes[0], inputTypes[1])
.standardMemory(0, 0).workingMemory(0, 0, 0, 0).cacheMemory(0, 0).build();
}
}
|
J-Sarkcess/vue-awesome | src/icons/heartbeat.js | <filename>src/icons/heartbeat.js
import Icon from '../components/Icon.vue'
Icon.register({
heartbeat: {
width: 512,
height: 512,
paths: [
{
d: 'M320.2 243.8L270.5 343.2C264.5 355.3 247.1 354.9 241.6 342.6L184.7 216.3 154.7 288H60.6L243.1 474.5C250.2 481.8 261.7 481.8 268.8 474.5L451.4 288H342.3L320.2 243.8zM473.7 73.9L471.3 71.4C419.8 18.8 335.5 18.8 283.9 71.4L256 100 228.1 71.5C176.6 18.8 92.2 18.8 40.7 71.5L38.3 73.9C-10.4 123.7-12.5 203 31 256H133.4L169.3 169.8C174.7 156.9 192.9 156.6 198.7 169.4L256.9 298.7 305.9 200.8C311.8 189 328.6 189 334.5 200.8L362.1 256H481C524.5 203 522.4 123.7 473.7 73.9z'
}
]
}
})
|
mdzyuba/popmov2 | app/src/main/java/com/mdzyuba/popularmovies/model/Video.java | package com.mdzyuba.popularmovies.model;
public class Video {
public final String id;
public final String iso_639_1;
public final String iso_3166_1;
public final String key;
public final String name;
public final String site;
public final int size;
public final String type;
public Video(String id, String iso_639_1, String iso_3166_1, String key, String name,
String site, int size, String type) {
this.id = id;
this.iso_639_1 = iso_639_1;
this.iso_3166_1 = iso_3166_1;
this.key = key;
this.name = name;
this.site = site;
this.size = size;
this.type = type;
}
}
|
mfkugergvh/domain-driven-tools | domain-driven-tools/src/main/java/io/ddd/core/event/invoke/annotation/OnInvoke.java | package io.ddd.core.event.invoke.annotation;
import java.lang.annotation.*;
/**
* {@link javax.annotation.concurrent.ThreadSafe} Annotated Method Must be Thread Safe
*/
@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OnInvoke {
int position() default 1;
Class<?> value();
boolean allowGeneric() default true;
String methodName() default "*";
}
|
hleuwer/cd | src/direct2d/cd_d2d_draw.c | #include <math.h>
#include "cd_d2d.h"
#include "cd.h"
#define checkSwapCoord(_c1, _c2) { if (_c1 > _c2) { float t = _c2; _c2 = _c1; _c1 = t; } } /* make sure _c1 is smaller than _c2 */
void d2dInitColor(dummy_D2D1_COLOR_F* c, long color)
{
unsigned char red, green, blue, alpha;
cdDecodeColorAlpha(color, &red, &green, &blue, &alpha);
c->r = red / 255.0f;
c->g = green / 255.0f;
c->b = blue / 255.0f;
c->a = alpha / 255.0f;
}
dummy_ID2D1PathGeometry* d2dCreateBoxGeometry(double xmin, double xmax, double ymin, double ymax)
{
HRESULT hr;
dummy_ID2D1GeometrySink *sink;
dummy_D2D1_POINT_2F pt;
dummy_ID2D1PathGeometry* g;
hr = dummy_ID2D1Factory_CreatePathGeometry(d2d_cd_factory, &g);
if (FAILED(hr)) {
return NULL;
}
dummy_ID2D1PathGeometry_Open(g, &sink);
pt.x = type2float(xmin);
pt.y = type2float(ymin);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, dummy_D2D1_FIGURE_BEGIN_FILLED);
pt.x = type2float(xmax);
pt.y = type2float(ymin);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
pt.x = type2float(xmax);
pt.y = type2float(ymax);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
pt.x = type2float(xmin);
pt.y = type2float(ymax);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
return g;
}
dummy_ID2D1PathGeometry* d2dCreateArcGeometry(float cx, float cy, float rx, float ry, float base_angle, float sweep_angle, int pie)
{
dummy_ID2D1PathGeometry* g = NULL;
dummy_ID2D1GeometrySink* s;
HRESULT hr;
float base_rads = base_angle * (PI / 180.0f);
dummy_D2D1_POINT_2F pt;
dummy_D2D1_ARC_SEGMENT arc_seg;
hr = dummy_ID2D1Factory_CreatePathGeometry(d2d_cd_factory, &g);
if (FAILED(hr)) {
return NULL;
}
dummy_ID2D1PathGeometry_Open(g, &s);
pt.x = cx + rx * cosf(base_rads);
pt.y = cy + ry * sinf(base_rads);
dummy_ID2D1GeometrySink_BeginFigure(s, pt, dummy_D2D1_FIGURE_BEGIN_FILLED);
if (sweep_angle == 360.0f)
{
d2dInitArcSegment(&arc_seg, cx, cy, rx, ry, base_angle, 180.0f);
dummy_ID2D1GeometrySink_AddArc(s, &arc_seg);
d2dInitArcSegment(&arc_seg, cx, cy, rx, ry, base_angle + 180.0f, 180.0f);
dummy_ID2D1GeometrySink_AddArc(s, &arc_seg);
}
else
{
d2dInitArcSegment(&arc_seg, cx, cy, rx, ry, base_angle, sweep_angle);
dummy_ID2D1GeometrySink_AddArc(s, &arc_seg);
}
if (pie == 2)
dummy_ID2D1GeometrySink_EndFigure(s, dummy_D2D1_FIGURE_END_CLOSED);
else if (pie == 1)
{
pt.x = cx;
pt.y = cy;
dummy_ID2D1GeometrySink_AddLine(s, pt);
dummy_ID2D1GeometrySink_EndFigure(s, dummy_D2D1_FIGURE_END_CLOSED);
}
else
dummy_ID2D1GeometrySink_EndFigure(s, dummy_D2D1_FIGURE_END_OPEN);
dummy_ID2D1GeometrySink_Close(s);
dummy_ID2D1GeometrySink_Release(s);
return g;
}
static dummy_ID2D1StrokeStyle* createStrokeStyleDashed(const float* dashes, UINT dashesCount, UINT lineCap, UINT lineJoin)
{
HRESULT hr;
dummy_D2D1_STROKE_STYLE_PROPERTIES p;
dummy_ID2D1StrokeStyle *s;
p.startCap = (dummy_D2D1_CAP_STYLE)0;
p.endCap = (dummy_D2D1_CAP_STYLE)lineCap;
p.dashCap = (dummy_D2D1_CAP_STYLE)lineCap;
p.lineJoin = (dummy_D2D1_LINE_JOIN)lineJoin;
p.miterLimit = 1.0f;
p.dashStyle = dummy_D2D1_DASH_STYLE_CUSTOM;
p.dashOffset = 0.0f;
hr = dummy_ID2D1Factory_CreateStrokeStyle(d2d_cd_factory, &p, dashes, dashesCount, &s);
if (FAILED(hr)) {
return NULL;
}
return s;
}
static dummy_ID2D1StrokeStyle* createStrokeStyle(UINT lineCap, UINT lineJoin)
{
HRESULT hr;
dummy_D2D1_STROKE_STYLE_PROPERTIES p;
dummy_ID2D1StrokeStyle *s;
p.startCap = (dummy_D2D1_CAP_STYLE)0;
p.endCap = (dummy_D2D1_CAP_STYLE)lineCap;
p.dashCap = (dummy_D2D1_CAP_STYLE)lineCap;
p.lineJoin = (dummy_D2D1_LINE_JOIN)lineJoin;
p.miterLimit = 1.0f;
p.dashStyle = dummy_D2D1_DASH_STYLE_SOLID;
p.dashOffset = 0.0f;
hr = dummy_ID2D1Factory_CreateStrokeStyle(d2d_cd_factory, &p, NULL, 0, &s);
if (FAILED(hr)) {
return NULL;
}
return s;
}
dummy_ID2D1StrokeStyle *d2dSetLineStyle(int line_style, int line_cap, int line_join)
{
if (line_style == CD_DASHED)
{
float dashes[2] = { 9.0f, 3.0f };
return createStrokeStyleDashed(dashes, 2, line_cap, line_join); /* CD and D2D line cap and line join use the same definitions */
}
else if (line_style == CD_DOTTED)
{
float dashes[2] = { 1.0f, 2.0f };
return createStrokeStyleDashed(dashes, 2, line_cap, line_join);
}
else if (line_style == CD_DASH_DOT)
{
float dashes[4] = { 7.0f, 3.0f, 1.0f, 3.0f };
return createStrokeStyleDashed(dashes, 4, line_cap, line_join);
}
else if (line_style == CD_DASH_DOT_DOT)
{
float dashes[6] = { 7.0f, 3.0f, 1.0f, 3.0f, 1.0f, 3.0f };
return createStrokeStyleDashed(dashes, 6, line_cap, line_join);
}
else if (line_cap != CD_CAPFLAT || line_join != CD_MITER)
return createStrokeStyle(line_cap, line_join);
return NULL;
}
dummy_ID2D1StrokeStyle *d2dSetCustomLineStyle(int *dashes, int dashes_count, float line_width, int line_cap, int line_join)
{
int i;
float *fdashes = (float *)malloc(dashes_count*sizeof(float));
for (i = 0; i < dashes_count; i++)
fdashes[i] = (float)dashes[i] / line_width;
return createStrokeStyleDashed(fdashes, dashes_count, line_cap, line_join);
}
dummy_ID2D1Brush* d2dCreateSolidBrush(dummy_ID2D1RenderTarget *target, long color)
{
dummy_ID2D1SolidColorBrush* brush;
dummy_D2D1_COLOR_F clr;
HRESULT hr;
d2dInitColor(&clr, color);
hr = dummy_ID2D1RenderTarget_CreateSolidColorBrush(target, &clr, NULL, &brush);
if (FAILED(hr)) {
return NULL;
}
return (dummy_ID2D1Brush*)brush;
}
dummy_ID2D1Brush* d2dCreateImageBrush(dummy_ID2D1RenderTarget *target, IWICBitmap* wic_bitmap)
{
dummy_ID2D1Bitmap *bitmap;
dummy_ID2D1BitmapBrush* brush;
dummy_D2D1_BITMAP_BRUSH_PROPERTIES props;
HRESULT hr;
hr = dummy_ID2D1RenderTarget_CreateBitmapFromWicBitmap(target, (IWICBitmapSource*)wic_bitmap, NULL, &bitmap);
if (FAILED(hr))
return NULL;
props.extendModeX = dummy_D2D1_EXTEND_MODE_WRAP;
props.extendModeY = dummy_D2D1_EXTEND_MODE_WRAP;
props.interpolationMode = dummy_D2D1_BITMAP_INTERPOLATION_MODE_LINEAR;
hr = dummy_ID2D1RenderTarget_CreateBitmapBrush(target, bitmap, &props, NULL, &brush);
dummy_ID2D1Bitmap_Release(bitmap);
if (FAILED(hr))
return NULL;
return (dummy_ID2D1Brush*)brush;
}
dummy_ID2D1Brush* d2dCreateLinearGradientBrush(dummy_ID2D1RenderTarget *target, FLOAT x1, FLOAT y1, FLOAT x2, FLOAT y2, long foreground, long background)
{
dummy_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props;
dummy_D2D1_GRADIENT_STOP stop[2];
dummy_ID2D1GradientStopCollection *stops;
dummy_ID2D1LinearGradientBrush *brush;
dummy_D2D1_COLOR_F color;
HRESULT hr;
props.startPoint.x = x1;
props.startPoint.y = y1;
props.endPoint.x = x2;
props.endPoint.y = y2;
d2dInitColor(&color, foreground);
stop[0].color = color;
stop[0].position = 0.0f;
d2dInitColor(&color, background);
stop[1].color = color;
stop[1].position = 1.0f;
hr = dummy_ID2D1RenderTarget_CreateGradientStopCollection(target, stop, 2, dummy_D2D1_GAMMA_2_2, dummy_D2D1_EXTEND_MODE_WRAP, &stops);
if (FAILED(hr)) {
return NULL;
}
hr = dummy_ID2D1RenderTarget_CreateLinearGradientBrush(target, &props, NULL, stops, &brush);
if (FAILED(hr)) {
dummy_ID2D1GradientStopCollection_Release(stops);
return NULL;
}
dummy_ID2D1GradientStopCollection_Release(stops);
return (dummy_ID2D1Brush*)brush;
}
dummy_ID2D1Brush* d2dCreateRadialGradientBrush(dummy_ID2D1RenderTarget *target, FLOAT cx, FLOAT cy, FLOAT ox, FLOAT oy, FLOAT rx, FLOAT ry, long foreground, long background)
{
dummy_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props;
dummy_D2D1_GRADIENT_STOP stop[2];
dummy_ID2D1GradientStopCollection *stops;
dummy_ID2D1RadialGradientBrush *brush;
dummy_D2D1_COLOR_F color;
HRESULT hr;
props.center.x = cx;
props.center.y = cy;
props.gradientOriginOffset.x = ox;
props.gradientOriginOffset.y = oy;
props.radiusX = rx;
props.radiusY = ry;
d2dInitColor(&color, foreground);
stop[0].color = color;
stop[0].position = 0.0f;
d2dInitColor(&color, background);
stop[1].color = color;
stop[1].position = 1.0f;
hr = dummy_ID2D1RenderTarget_CreateGradientStopCollection(target, stop, 2, dummy_D2D1_GAMMA_2_2, dummy_D2D1_EXTEND_MODE_WRAP, &stops);
if (FAILED(hr)) {
return NULL;
}
hr = dummy_ID2D1RenderTarget_CreateRadialGradientBrush(target, &props, NULL, stops, &brush);
if (FAILED(hr)) {
dummy_ID2D1GradientStopCollection_Release(stops);
return NULL;
}
dummy_ID2D1GradientStopCollection_Release(stops);
return (dummy_ID2D1Brush*)brush;
}
static void d2dFillEllipse(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float cx, float cy, float rx, float ry)
{
dummy_D2D1_ELLIPSE e;
e.point.x = cx;
e.point.y = cy;
e.radiusX = rx;
e.radiusY = ry;
dummy_ID2D1RenderTarget_FillEllipse(target, &e, brush);
}
static void d2dFillEllipsePie(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float cx, float cy, float rx, float ry,
float fBaseAngle, float fSweepAngle)
{
dummy_ID2D1PathGeometry* g = d2dCreateArcGeometry(cx, cy, rx, ry, fBaseAngle, fSweepAngle, 1);
if (g == NULL)
return;
dummy_ID2D1RenderTarget_FillGeometry(target, (dummy_ID2D1Geometry*)g, brush, NULL);
dummy_ID2D1PathGeometry_Release(g);
}
static void d2dFillEllipseChord(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float cx, float cy, float rx, float ry,
float fBaseAngle, float fSweepAngle)
{
dummy_ID2D1PathGeometry* g = d2dCreateArcGeometry(cx, cy, rx, ry, fBaseAngle, fSweepAngle, 2);
if (g == NULL)
return;
dummy_ID2D1RenderTarget_FillGeometry(target, (dummy_ID2D1Geometry*)g, brush, NULL);
dummy_ID2D1PathGeometry_Release(g);
}
static void d2dDrawEllipse(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float cx, float cy, float rx, float ry,
float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_D2D1_ELLIPSE e;
e.point.x = cx;
e.point.y = cy;
e.radiusX = rx;
e.radiusY = ry;
dummy_ID2D1RenderTarget_DrawEllipse(target, &e, brush, fStrokeWidth, hStrokeStyle);
}
static void d2dDrawEllipseArc(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float cx, float cy, float rx, float ry,
float fBaseAngle, float fSweepAngle, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_ID2D1PathGeometry* g = d2dCreateArcGeometry(cx, cy, rx, ry, fBaseAngle, fSweepAngle, 0);
if (g == NULL)
return;
dummy_ID2D1RenderTarget_DrawGeometry(target, (dummy_ID2D1Geometry*)g, brush, fStrokeWidth, hStrokeStyle);
dummy_ID2D1PathGeometry_Release(g);
}
void d2dFillRect(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float x0, float y0, float x1, float y1)
{
dummy_D2D1_RECT_F r;
r.left = x0;
r.top = y0;
r.right = x1;
r.bottom = y1;
dummy_ID2D1RenderTarget_FillRectangle(target, &r, brush);
}
void d2dDrawRect(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float x0, float y0, float x1, float y1, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_D2D1_RECT_F r;
r.left = x0;
r.top = y0;
r.right = x1;
r.bottom = y1;
dummy_ID2D1RenderTarget_DrawRectangle(target, &r, brush, fStrokeWidth, hStrokeStyle);
}
void d2dDrawLine(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float x0, float y0, float x1, float y1, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_D2D1_POINT_2F pt0;
dummy_D2D1_POINT_2F pt1;
pt0.x = x0;
pt0.y = y0;
pt1.x = x1;
pt1.y = y1;
dummy_ID2D1RenderTarget_DrawLine(target, pt0, pt1, brush, fStrokeWidth, hStrokeStyle);
}
void d2dDrawArc(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float xc, float yc, float w, float h, double a1, double a2, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
float baseAngle = (float)(360.0 - a2);
float sweepAngle = (float)(a2 - a1);
if (sweepAngle == 360.0f)
d2dDrawEllipse(target, brush, xc, yc, w / 2.0f, h / 2.0f, fStrokeWidth, hStrokeStyle);
else
d2dDrawEllipseArc(target, brush, xc, yc, w / 2.0f, h / 2.0f, baseAngle, sweepAngle, fStrokeWidth, hStrokeStyle);
}
void d2dFillArc(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, float xc, float yc, float w, float h, double a1, double a2, int pie)
{
float baseAngle = (float)(360.0 - a2);
float sweepAngle = (float)(a2 - a1);
if (sweepAngle == 360.0f)
d2dFillEllipse(target, brush, xc, yc, w / 2.0f, h / 2.0f);
else if (pie)
d2dFillEllipsePie(target, brush, xc, yc, w / 2.0f, h / 2.0f, baseAngle, sweepAngle);
else
d2dFillEllipseChord(target, brush, xc, yc, w / 2.0f, h / 2.0f, baseAngle, sweepAngle);
}
static dummy_ID2D1PathGeometry* createPolyGeometry(dummy_ID2D1GeometrySink* *sink, int fill_mode)
{
dummy_ID2D1PathGeometry* g;
HRESULT hr = dummy_ID2D1Factory_CreatePathGeometry(d2d_cd_factory, &g);
if (FAILED(hr))
return NULL;
dummy_ID2D1PathGeometry_Open(g, sink);
dummy_ID2D1GeometrySink_SetFillMode(*sink, fill_mode == CD_EVENODD ? dummy_D2D1_FILL_MODE_ALTERNATE : dummy_D2D1_FILL_MODE_WINDING);
return g;
}
dummy_ID2D1PathGeometry* d2dCreatePolygonGeometry(int* points, int count, int mode, int fill_mode)
{
dummy_ID2D1PathGeometry* g;
dummy_ID2D1GeometrySink* sink;
dummy_D2D1_POINT_2F pt;
int i;
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return NULL;
pt.x = type2float(points[0]);
pt.y = type2float(points[1]);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, dummy_D2D1_FIGURE_BEGIN_FILLED);
if (mode == CD_BEZIER)
{
for (i = 2; i < count * 2; i = i + 6)
{
dummy_D2D1_BEZIER_SEGMENT segment;
segment.point1.x = type2float(points[i]);
segment.point1.y = type2float(points[i + 1]);
segment.point2.x = type2float(points[i + 2]);
segment.point2.y = type2float(points[i + 3]);
segment.point3.x = type2float(points[i + 4]);
segment.point3.y = type2float(points[i + 5]);
dummy_ID2D1GeometrySink_AddBezier(sink, &segment);
}
}
else
{
for (i = 2; i < count * 2; i = i + 2)
{
pt.x = type2float(points[i]);
pt.y = type2float(points[i + 1]);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
}
}
if (mode == CD_CLOSED_LINES || mode == CD_FILL)
{
pt.x = type2float(points[0]);
pt.y = type2float(points[1]);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
}
dummy_ID2D1GeometrySink_EndFigure(sink, (0 ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN));
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
return g;
}
dummy_ID2D1PathGeometry* d2dCreatePolygonGeometryF(double* points, int count, int mode, int fill_mode)
{
dummy_ID2D1PathGeometry* g;
dummy_ID2D1GeometrySink* sink;
dummy_D2D1_POINT_2F pt;
int i;
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return NULL;
pt.x = type2float(points[0]);
pt.y = type2float(points[1]);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, dummy_D2D1_FIGURE_BEGIN_FILLED);
if (mode == CD_BEZIER)
{
for (i = 2; i < count * 2; i = i + 6)
{
dummy_D2D1_BEZIER_SEGMENT segment;
segment.point1.x = type2float(points[i]);
segment.point1.y = type2float(points[i + 1]);
segment.point2.x = type2float(points[i + 2]);
segment.point2.y = type2float(points[i + 3]);
segment.point3.x = type2float(points[i + 4]);
segment.point3.y = type2float(points[i + 5]);
dummy_ID2D1GeometrySink_AddBezier(sink, &segment);
}
}
else
{
for (i = 2; i < count * 2; i = i + 2)
{
pt.x = type2float(points[i]);
pt.y = type2float(points[i + 1]);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
}
}
if (mode == CD_CLOSED_LINES || mode == CD_FILL)
{
pt.x = type2float(points[0]);
pt.y = type2float(points[1]);
dummy_ID2D1GeometrySink_AddLine(sink, pt);
}
dummy_ID2D1GeometrySink_EndFigure(sink, (0 ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN));
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
return g;
}
static dummy_D2D1_FIGURE_BEGIN getFigureBegin(int *path, int path_n, int current_p)
{
int p;
for (p = current_p + 1; p < path_n; p++)
{
if (path[p] == CD_PATH_NEW || path[p] == CD_PATH_STROKE)
break;
if (path[p] == CD_PATH_CLOSE || path[p] == CD_PATH_FILL || path[p] == CD_PATH_FILLSTROKE || path[p] == CD_PATH_CLIP)
return dummy_D2D1_FIGURE_BEGIN_FILLED;
}
return dummy_D2D1_FIGURE_BEGIN_HOLLOW;
}
void d2dDrawGeometry(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, dummy_ID2D1PathGeometry* g, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_ID2D1RenderTarget_DrawGeometry(target, (dummy_ID2D1Geometry*)g, brush, fStrokeWidth, hStrokeStyle);
}
void d2dFillGeometry(dummy_ID2D1RenderTarget *target, dummy_ID2D1Brush *brush, dummy_ID2D1PathGeometry* g)
{
dummy_ID2D1RenderTarget_FillGeometry(target, (dummy_ID2D1Geometry*)g, brush, NULL);
}
int d2dPolyPath(d2dCanvas *canvas, dummy_ID2D1Brush *drawBrush, dummy_ID2D1Brush *fillBrush, int* points, int points_n, int* path, int path_n, int invert_yaxis, int fill_mode, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_ID2D1PathGeometry* g;
dummy_ID2D1GeometrySink* sink;
dummy_D2D1_POINT_2F pt;
dummy_D2D1_FIGURE_BEGIN figureBegin = dummy_D2D1_FIGURE_BEGIN_HOLLOW;
dummy_D2D1_ARC_SEGMENT arc_seg;
dummy_D2D1_BEZIER_SEGMENT segment;
float cx, cy, w, h, a1, a2;
float baseAngle, sweepAngle, base_rads;
int i, begin_picture = 0, p, n = 2 * points_n, ret = 0;
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
i = 0;
for (p = 0; p<path_n; p++)
{
switch (path[p])
{
case CD_PATH_NEW:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
if (g)
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_MOVETO:
if (i + 1*2 > n) return ret;
pt.x = type2float(points[i++]);
pt.y = type2float(points[i++]);
/* if BeginFigure called, then call EndFigure */
if (begin_picture)
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
/* there is no MoveTo, so BeginFigure acts as one */
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
break;
case CD_PATH_LINETO:
if (i + 1*2 > n) return ret;
pt.x = type2float(points[i++]);
pt.y = type2float(points[i++]);
if (begin_picture)
dummy_ID2D1GeometrySink_AddLine(sink, pt);
else
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
}
break;
case CD_PATH_ARC:
if (i + 3*2 > n) return ret;
/* same as cdGetArcPath (notice the interger fix by 1000) */
cx = type2float(points[i++]);
cy = type2float(points[i++]);
w = type2float(points[i++]);
h = type2float(points[i++]);
a1 = type2float(points[i++] / 1000.);
a2 = type2float(points[i++] / 1000.);
if (invert_yaxis)
{
a1 *= -1;
a2 *= -1;
}
baseAngle = (float)(a1);
sweepAngle = (float)(a2 - a1);
base_rads = baseAngle * (PI / 180.0f);
/* arc start point */
pt.x = cx + (w / 2.f) * cosf(base_rads);
pt.y = cy + (h / 2.f) * sinf(base_rads);
if (begin_picture)
dummy_ID2D1GeometrySink_AddLine(sink, pt);
else
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
}
if (sweepAngle == 360.0f)
{
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle, 180.0f);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle + 180.0f, 180.0f);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
}
else
{
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle, sweepAngle);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
}
break;
case CD_PATH_CURVETO:
if (i + 3*2 > n) return ret;
segment.point1.x = type2float(points[i++]);
segment.point1.y = type2float(points[i++]);
if (!begin_picture)
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, segment.point1, figureBegin);
begin_picture = 1;
}
segment.point2.x = type2float(points[i++]);
segment.point2.y = type2float(points[i++]);
segment.point3.x = type2float(points[i++]);
segment.point3.y = type2float(points[i++]);
dummy_ID2D1GeometrySink_AddBezier(sink, &segment);
break;
case CD_PATH_CLOSE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
break;
case CD_PATH_CLIP:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dSetClipGeometry(canvas, g);
ret = 1; /* clipping was set */
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_FILL:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dFillGeometry(canvas->target, fillBrush, g);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_FILLSTROKE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dFillGeometry(canvas->target, fillBrush, g);
d2dDrawGeometry(canvas->target, drawBrush, g, fStrokeWidth, hStrokeStyle);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_STROKE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dDrawGeometry(canvas->target, drawBrush, g, fStrokeWidth, hStrokeStyle);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
}
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
}
if (g)
dummy_ID2D1PathGeometry_Release(g);
return ret;
}
int d2dPolyPathF(d2dCanvas *canvas, dummy_ID2D1Brush *drawBrush, dummy_ID2D1Brush *fillBrush, double* points, int points_n, int* path, int path_n, int invert_yaxis, int fill_mode, float fStrokeWidth, dummy_ID2D1StrokeStyle *hStrokeStyle)
{
dummy_ID2D1PathGeometry* g;
dummy_ID2D1GeometrySink* sink;
dummy_D2D1_POINT_2F pt;
dummy_D2D1_FIGURE_BEGIN figureBegin = dummy_D2D1_FIGURE_BEGIN_HOLLOW;
dummy_D2D1_ARC_SEGMENT arc_seg;
dummy_D2D1_BEZIER_SEGMENT segment;
float cx, cy, w, h, a1, a2;
float baseAngle, sweepAngle, base_rads;
int i, begin_picture = 0, p, n = 2 * points_n, ret = 0;
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
i = 0;
for (p = 0; p<path_n; p++)
{
switch (path[p])
{
case CD_PATH_NEW:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
if (g)
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_MOVETO:
if (i + 1 * 2 > n) return ret;
pt.x = type2float(points[i++]);
pt.y = type2float(points[i++]);
/* if BeginFigure called, then call EndFigure */
if (begin_picture)
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
/* there is no MoveTo, so BeginFigure acts as one */
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
break;
case CD_PATH_LINETO:
if (i + 1 * 2 > n) return ret;
pt.x = type2float(points[i++]);
pt.y = type2float(points[i++]);
if (begin_picture)
dummy_ID2D1GeometrySink_AddLine(sink, pt);
else
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
}
break;
case CD_PATH_ARC:
if (i + 3 * 2 > n) return ret;
/* same as cdfGetArcPath (no integer fix here) */
cx = type2float(points[i++]);
cy = type2float(points[i++]);
w = type2float(points[i++]);
h = type2float(points[i++]);
a1 = type2float(points[i++]);
a2 = type2float(points[i++]);
if (invert_yaxis)
{
a1 *= -1;
a2 *= -1;
}
baseAngle = (float)(a1);
sweepAngle = (float)(a2 - a1);
base_rads = baseAngle * (PI / 180.0f);
/* arc start point */
pt.x = cx + (w / 2.f) * cosf(base_rads);
pt.y = cy + (h / 2.f) * sinf(base_rads);
if (begin_picture)
dummy_ID2D1GeometrySink_AddLine(sink, pt);
else
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, pt, figureBegin);
begin_picture = 1;
}
if (sweepAngle == 360.0f)
{
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle, 180.0f);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle + 180.0f, 180.0f);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
}
else
{
d2dInitArcSegment(&arc_seg, cx, cy, w / 2.f, h / 2.f, baseAngle, sweepAngle);
dummy_ID2D1GeometrySink_AddArc(sink, &arc_seg);
}
break;
case CD_PATH_CURVETO:
if (i + 3 * 2 > n) return ret;
segment.point1.x = type2float(points[i++]);
segment.point1.y = type2float(points[i++]);
if (!begin_picture)
{
figureBegin = getFigureBegin(path, path_n, p);
dummy_ID2D1GeometrySink_BeginFigure(sink, segment.point1, figureBegin);
begin_picture = 1;
}
segment.point2.x = type2float(points[i++]);
segment.point2.y = type2float(points[i++]);
segment.point3.x = type2float(points[i++]);
segment.point3.y = type2float(points[i++]);
dummy_ID2D1GeometrySink_AddBezier(sink, &segment);
break;
case CD_PATH_CLOSE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
break;
case CD_PATH_CLIP:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dSetClipGeometry(canvas, g);
ret = 1; /* clipping was set */
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_FILL:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dFillGeometry(canvas->target, fillBrush, g);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_FILLSTROKE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, dummy_D2D1_FIGURE_END_CLOSED);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dFillGeometry(canvas->target, fillBrush, g);
d2dDrawGeometry(canvas->target, drawBrush, g, fStrokeWidth, hStrokeStyle);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
case CD_PATH_STROKE:
if (begin_picture)
{
begin_picture = 0;
dummy_ID2D1GeometrySink_EndFigure(sink, figureBegin == dummy_D2D1_FIGURE_BEGIN_FILLED ? dummy_D2D1_FIGURE_END_CLOSED : dummy_D2D1_FIGURE_END_OPEN);
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
sink = NULL;
}
d2dDrawGeometry(canvas->target, drawBrush, g, fStrokeWidth, hStrokeStyle);
/* reset the geometry */
dummy_ID2D1PathGeometry_Release(g);
g = createPolyGeometry(&sink, fill_mode);
if (!g)
return ret;
break;
}
}
if (sink)
{
dummy_ID2D1GeometrySink_Close(sink);
dummy_ID2D1GeometrySink_Release(sink);
}
if (g)
dummy_ID2D1PathGeometry_Release(g);
return ret;
}
|
safaladhikari1/Binary-Tree-Data-Structure | Hashing/PriorityQueueAndHeap/HeapSortMain.java | <filename>Hashing/PriorityQueueAndHeap/HeapSortMain.java
// This client program uses a HeapPriority queue to perform
// a version of the "heap sort" sorting algorithm.
/*
HeapSort Algorithm:
If you add all elements of an array to a priority queue and them remove them,
they will come out in ascending (sorted) order.
heapSort(A):
H = create new heap.
for each element n in A:
add n to H.
while(H not empty):
remove element from H.
add element back into A.
while sorting an array of N elements,
heap sort performs N add and N remove operations on a heap
Each add or remove has a O(log N) complexity, so the
overall heap sort algorithm has O(N log N) complexity.
Heap sort is a fairly efficient algorithm, certainly much faster than
selection sort and with comparable performance to merge sort.
One drawback of the heap sort algorithm as shown is the memory required.
To sort the array, we must create another large data structure (the priority queue, and the array heap inside it)
to temporarily store the data. For very large data sets this can be undesirable.
*/
import java.util.Arrays;
public class HeapSortMain
{
public static void main(String[] args)
{
int[] a = {0, 65, 50, 20, 90, 44, 60, 80, 70, 99, 10};
heapSort(a);
System.out.println(Arrays.toString(a));
}
public static void heapSort(int[] a)
{
// If we have import java.util.*;
// Queue<Integer> pq = new PriorityQueue<Integer>();
HeapPriorityQueue<Integer> pq = new HeapPriorityQueue<Integer>();
for(int n: a)
{
pq.add(n);
}
for(int i=0; i<a.length; i++)
{
a[i] = pq.remove();
}
}
} |
Fuge2008/HJ | app/src/main/java/com/haoji/haoji/util/MyComparator.java | <reponame>Fuge2008/HJ<filename>app/src/main/java/com/haoji/haoji/util/MyComparator.java
package com.haoji.haoji.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
/**
* Created by Administrator on 2017/4/7.
*/
public class MyComparator implements Comparator<HashMap> {
@Override
public int compare(HashMap lhs, HashMap rhs) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = dateFormat.parse(lhs.get("updatetime").toString());
date2 = dateFormat.parse(rhs.get("updatetime").toString());
} catch (ParseException e) {
e.printStackTrace();
}
//反向排序
if (date1.getTime()>date2.getTime()){
return -1;
}else if (date1.getTime()<date2.getTime()){
return 1;
}else {
return 0;
}
}
}
|
shaikatz/tweek | services/gateway/security/authorization_test.go | <gh_stars>100-1000
package security
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func noopHandler(rw http.ResponseWriter, r *http.Request) {}
type emptyAuditor struct{}
func (a *emptyAuditor) Allowed(subject, object, action string) {
}
func (a *emptyAuditor) Denied(subject, object, action string) {
}
func (a *emptyAuditor) AuthorizerError(subject, object, action string, err error) {
}
func (a *emptyAuditor) TokenError(err error) {
}
func TestAuthorizationMiddleware(t *testing.T) {
authorization, err := ioutil.ReadFile("../authorization.rego")
if err != nil {
t.Fatal("Could not load rego file")
}
policy, err := ioutil.ReadFile("./testdata/policy.json")
if err != nil {
t.Fatal("Could not load policy file")
}
authorizer := NewDefaultAuthorizer(string(authorization), string(policy), "authorization", "authorize")
server := AuthorizationMiddleware(authorizer, &emptyAuditor{})
type args struct {
method, path, user, group string
}
tests := []struct {
name string
args args
want int
}{
{
name: "Allow by user",
args: args{method: "GET", path: "/api/v2/values/key1", user: "<EMAIL>", group: "default"},
want: http.StatusOK,
},
{
name: "Deny by user",
args: args{method: "GET", path: "/api/v2/values/key1", user: "<EMAIL>", group: "default"},
want: http.StatusForbidden,
},
{
name: "Allow calculating values with specific context",
args: args{method: "GET", path: "/api/v2/values/key2?user=<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusOK,
},
{
name: "Allow reading context for self",
args: args{method: "GET", path: "/api/v2/context/user/<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusOK,
},
{
name: "Allow writing context for self",
args: args{method: "POST", path: "/api/v2/context/user/<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusOK,
},
{
name: "Deny writing context for someone else",
args: args{method: "POST", path: "/api/v2/context/user/<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusForbidden,
},
{
name: "Deny deleting context for someone else",
args: args{method: "DELETE", path: "/api/v2/context/user/<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusForbidden,
},
{
name: "Allow deleting context for self",
args: args{method: "DELETE", path: "/api/v2/context/user/<EMAIL>", user: "<EMAIL>", group: "default"},
want: http.StatusOK,
},
{
name: "Deny deleting context property for someone else",
args: args{method: "DELETE", path: "/api/v2/context/user/<EMAIL>/prop", user: "<EMAIL>", group: "default"},
want: http.StatusForbidden,
},
{
name: "Deny deleting context property for self",
args: args{method: "DELETE", path: "/api/v2/context/user/<EMAIL>@<EMAIL>.<EMAIL>/prop", user: "<EMAIL>", group: "default"},
want: http.StatusForbidden,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
next := noopHandler
request := createRequest(tt.args.method, tt.args.path, tt.args.user, tt.args.group)
server.ServeHTTP(recorder, request, next)
if code := recorder.Result().StatusCode; code != tt.want {
t.Errorf("AuthorizationMiddleware() = %v, want %v", code, tt.want)
}
})
}
}
func createRequest(method, target, user, group string) *http.Request {
info := &userInfo{
sub: &Subject{User: user, Group: group},
}
r := httptest.NewRequest(method, target, nil)
ctx := context.WithValue(r.Context(), UserInfoKey, info)
return r.WithContext(ctx)
}
|
shuigedeng/taotao-cloud-paren | taotao-cloud-java/taotao-cloud-javase/src/main/java/com/taotao/cloud/java/javase/day14/chatper14_4/BankCard.java | package com.taotao.cloud.java.javase.day14.chatper14_4;
public class BankCard {
private double money;
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
|
Robert-Ciborowski/Iron-Bears-2018 | src/org/usfirst/frc/team854/robot/command/LinearTimedMotionCommand.java | /*
* Name: AngularMotion
* Author: <NAME>, <NAME>, <NAME>
* Date: 08/02/2018
* Description: A command for moving along a line.
*/
package org.usfirst.frc.team854.robot.command;
import org.usfirst.frc.team854.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
public class LinearTimedMotionCommand extends Command {
private double angle, time;
public LinearTimedMotionCommand(double time) {
requires(Robot.chassisSubsystem);
this.time = time;
}
double cTime = 0, sTime = 0;
@Override
public void initialize() {
System.out.println("Lineari.");
// Robot.chassisSubsystem.resetTargetAngle();
angle = Robot.chassisSubsystem.getTargetAngle();
Robot.chassisSubsystem.setAutonomousTarget(angle, 999999);
Robot.chassisSubsystem.enableAllPIDs();
sTime = System.currentTimeMillis();
}
@Override
protected boolean isFinished() {
// return Robot.chassisSubsystem.isAutonomousOnTarget();
return cTime > time;
}
@Override
protected void execute() {
cTime = System.currentTimeMillis() - sTime;
}
@Override
protected void end() {
Robot.chassisSubsystem.disableAllComponents();
System.out.println("ENDED");
}
}
|
marcocarvalho/technical_analysis | lib/technical_analysis/data/helpers/price_randomizer.rb | module TechnicalAnalysis::Data
module Helpers
def price_between(v1, v2)
seed = SecureRandom.random_number
((v2 - v1) * seed) + v1
end
def price_near(candle, candle_notation_price, opts = { })
opts = { price_tolerance: 0.1 }.merge opts
price = candle.send(candle_notation_price)
tolerance = price * opts[:price_tolerance]
seed = SecureRandom.random_number
(((tolerance * 2) * seed) + (price - tolerance)).round(2)
end
def price_above(candle, candle_notation_price, opts = {})
raise ArgumentError.new 'high cannot be used in this method' if candle_notation_price == :high
high = candle.high
price_at = candle.send(candle_notation_price)
((high - price_at) * SecureRandom.random_number) + price_at
end
def price_below(candle, candle_notation_price, opts = {})
raise ArgumentError.new 'low cannot be used in this method' if candle_notation_price == :low
low = candle.low
price_at = candle.send(candle_notation_price)
((price_at - low) * SecureRandom.random_number) + low
end
end
end |
vernonet/stm32F4_prj | STM32F4_USB_MP3_armcc_V12/inc/stm32f4xx_it.h | /**
******************************************************************************
* @file Audio_playback_and_record/inc/stm32f4xx_it.h
* @author MCD Application Team
* @version V1.1.0
* @date 26-June-2014
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_IT_H
#define __STM32F4xx_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
/* Exported types ------------------------------------------------------------*/
/** @defgroup EXTI_Lines
* @{
*/
#define EXTI_Line0 ((uint32_t)0x00001) /*!< External interrupt line 0 */
#define EXTI_Line1 ((uint32_t)0x00002) /*!< External interrupt line 1 */
#define EXTI_Line2 ((uint32_t)0x00004) /*!< External interrupt line 2 */
#define EXTI_Line3 ((uint32_t)0x00008) /*!< External interrupt line 3 */
#define EXTI_Line4 ((uint32_t)0x00010) /*!< External interrupt line 4 */
#define EXTI_Line5 ((uint32_t)0x00020) /*!< External interrupt line 5 */
#define EXTI_Line6 ((uint32_t)0x00040) /*!< External interrupt line 6 */
#define EXTI_Line7 ((uint32_t)0x00080) /*!< External interrupt line 7 */
#define EXTI_Line8 ((uint32_t)0x00100) /*!< External interrupt line 8 */
#define EXTI_Line9 ((uint32_t)0x00200) /*!< External interrupt line 9 */
#define EXTI_Line10 ((uint32_t)0x00400) /*!< External interrupt line 10 */
#define EXTI_Line11 ((uint32_t)0x00800) /*!< External interrupt line 11 */
#define EXTI_Line12 ((uint32_t)0x01000) /*!< External interrupt line 12 */
#define EXTI_Line13 ((uint32_t)0x02000) /*!< External interrupt line 13 */
#define EXTI_Line14 ((uint32_t)0x04000) /*!< External interrupt line 14 */
#define EXTI_Line15 ((uint32_t)0x08000) /*!< External interrupt line 15 */
#define EXTI_Line16 ((uint32_t)0x10000) /*!< External interrupt line 16 Connected to the PVD Output */
#define EXTI_Line17 ((uint32_t)0x20000) /*!< External interrupt line 17 Connected to the RTC Alarm event */
#define EXTI_Line18 ((uint32_t)0x40000) /*!< External interrupt line 18 Connected to the USB OTG FS Wakeup from suspend event */
#define EXTI_Line19 ((uint32_t)0x80000) /*!< External interrupt line 19 Connected to the Ethernet Wakeup event */
#define EXTI_Line20 ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the USB OTG HS (configured in FS) Wakeup event */
#define EXTI_Line21 ((uint32_t)0x00200000) /*!< External interrupt line 21 Connected to the RTC Tamper and Time Stamp events */
#define EXTI_Line22 ((uint32_t)0x00400000) /*!< External interrupt line 22 Connected to the RTC Wakeup event */
#define IS_EXTI_LINE(LINE) ((((LINE) & (uint32_t)0xFF800000) == 0x00) && ((LINE) != (uint16_t)0x00))
#define IS_GET_EXTI_LINE(LINE) (((LINE) == EXTI_Line0) || ((LINE) == EXTI_Line1) || \
((LINE) == EXTI_Line2) || ((LINE) == EXTI_Line3) || \
((LINE) == EXTI_Line4) || ((LINE) == EXTI_Line5) || \
((LINE) == EXTI_Line6) || ((LINE) == EXTI_Line7) || \
((LINE) == EXTI_Line8) || ((LINE) == EXTI_Line9) || \
((LINE) == EXTI_Line10) || ((LINE) == EXTI_Line11) || \
((LINE) == EXTI_Line12) || ((LINE) == EXTI_Line13) || \
((LINE) == EXTI_Line14) || ((LINE) == EXTI_Line15) || \
((LINE) == EXTI_Line16) || ((LINE) == EXTI_Line17) || \
((LINE) == EXTI_Line18) || ((LINE) == EXTI_Line19) || \
((LINE) == EXTI_Line20) || ((LINE) == EXTI_Line21) ||\
((LINE) == EXTI_Line22))
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
void EXTI0_IRQHandler(void);
void EXTI1_IRQHandler(void);
void OTG_FS_IRQHandler(void);
void I2S2_IRQHandler(void);
void I2S3_IRQHandler(void);
void TIM4_IRQHandler(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4xx_IT_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
googleinterns/step132-2020 | src/test/java/com/google/sps/ProfileTest.java | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 com.google.sps;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.sps.data.SampleData;
import com.google.sps.data.Student;
import com.google.sps.data.Tutor;
import com.google.sps.servlets.ProfileServlet;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.Mockito.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RunWith(JUnit4.class)
public final class ProfileTest {
private final String USER_EMAIL = "<EMAIL>";
private final String USER_ID = "id123";
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalUserServiceTestConfig(), new LocalDatastoreServiceTestConfig())
.setEnvEmail(USER_EMAIL)
.setEnvAuthDomain("gmail.com")
.setEnvIsLoggedIn(true)
.setEnvAttributes(
new HashMap(
ImmutableMap.of(
"com.google.appengine.api.users.UserService.user_id_key", USER_ID)));
private HttpServletRequest request;
private HttpServletResponse response;
private ProfileServlet servlet;
private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
private SampleData sample = new SampleData();
@Before
public void setUp() {
helper.setUp();
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
servlet = new ProfileServlet();
servlet.init();
sample.addTutorsToDatastore();
sample.addStudentsToDatastore();
}
@After
public void tearDown() {
helper.tearDown();
}
@Test
public void doGetReturnsCorrectResponseForStudent() throws Exception {
// Add student user entity to the local datastore so there is data to query in the function
Entity userEntity = new Entity("User");
userEntity.setProperty("role", "student");
userEntity.setProperty("userId", "1");
datastore.put(userEntity);
when(request.getParameter("userId")).thenReturn("1");
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
servlet.doGet(request, response);
Student expectedStudent = sample.getStudentByEmail("<EMAIL>");
String expected = new Gson().toJson(expectedStudent);
Assert.assertTrue(stringWriter.toString().contains(expected));
}
@Test
public void doGetReturnsCorrectResponseForTutor() throws Exception {
// Add tutor user entity to the local datastore so there is data to query in the function
Entity userEntity = new Entity("User");
userEntity.setProperty("role", "tutor");
userEntity.setProperty("userId", "0");
datastore.put(userEntity);
when(request.getParameter("userId")).thenReturn("0");
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
servlet.doGet(request, response);
Tutor expectedTutor = sample.getTutorByEmail("<EMAIL>");
String expected = new Gson().toJson(expectedTutor);
Assert.assertTrue(stringWriter.toString().contains(expected));
}
@Test
public void doPostCancelsFormSubmit() throws Exception {
when(request.getParameter("submit")).thenReturn("Cancel");
servlet.doPost(request, response);
ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class);
verify(response).sendRedirect(url.capture());
List<String> expected = Arrays.asList("/profile.html?userID="+USER_ID);
// Response redirected to correct URL
Assert.assertEquals(expected, url.getAllValues());
}
@Test
public void doPostCorrectlyUpdatesEntities() throws Exception {
Entity studentEntity = new Entity("Student");
studentEntity.setProperty("bio", "blah");
studentEntity.setProperty("learning", new ArrayList<String> (Arrays.asList("Math", "History")));
studentEntity.setProperty("userId", USER_ID);
datastore.put(studentEntity);
String newBio = "Updated bio";
ArrayList<String> newTopics = new ArrayList<String> (Arrays.asList("Orthodontics", "Fortune Telling"));
servlet.updateStudentEntityAndPutInDatastore(datastore, studentEntity, USER_ID, newBio, newTopics);
Query query = new Query("Student").setFilter(new Query.FilterPredicate("userId", Query.FilterOperator.EQUAL, USER_ID));
PreparedQuery results = datastore.prepare(query);
Entity actual = results.asSingleEntity();
Assert.assertEquals(newBio, (String) actual.getProperty("bio"));
Assert.assertEquals(newTopics, (ArrayList) actual.getProperty("learning"));
}
}
|
VHAINNOVATIONS/InfoButtons | oib-request/oib-request-service/src/main/java/org/openinfobutton/service/matching/PerformerMatcher.java | <gh_stars>10-100
/**
* -----------------------------------------------------------------------------------
* (c) 2010-2014 OpenInfobutton Project, Biomedical Informatics, University of Utah
* Contact: {@code <<EMAIL>>}
* Biomedical Informatics
* 421 Wakara Way, Ste 140
* Salt Lake City, UT 84108-3514
* Day Phone: 1-801-581-4080
* -----------------------------------------------------------------------------------
*
* @author <NAME> {@code <<EMAIL>>}
* @version Jul 15, 2014
*/
package org.openinfobutton.service.matching;
import java.util.List;
import org.openinfobutton.schema.KnowledgeRequest;
import org.openinfobutton.schema.Performer;
import org.openinfobutton.schemas.kb.CodedContextElement;
// TODO: Auto-generated Javadoc
/**
* The Class PerformerMatcher.
*/
public class PerformerMatcher
extends ContextMatcher
{
/** The performer. */
public Performer performer;
/** The performer language. */
public CodedContextElement performerLanguage;
/** The performer discipline. */
public CodedContextElement performerDiscipline;
/** The performer knowledge user type. */
public CodedContextElement performerKnowledgeUserType;
/** The supported code systems. */
List<String> supportedCodeSystems;
/** The request. */
KnowledgeRequest request;
/**
* Instantiates a new performer matcher.
*
* @param performerLanguage the performer language
* @param performerDiscipline the performer discipline
* @param performerKnowledgeUserType the performer knowledge user type
* @param request the request
* @param supportedCodeSystems the supported code systems
*/
public PerformerMatcher( CodedContextElement performerLanguage, CodedContextElement performerDiscipline,
CodedContextElement performerKnowledgeUserType, KnowledgeRequest request,
List<String> supportedCodeSystems )
{
this.performerLanguage = performerLanguage;
this.performerDiscipline = performerDiscipline;
this.performerKnowledgeUserType = performerKnowledgeUserType;
this.performer = request.getPerformer();
this.supportedCodeSystems = supportedCodeSystems;
this.request = request;
}
/*
* (non-Javadoc)
* @see org.openinfobutton.service.matching.ContextMatcher#MatchContext()
*/
@Override
public Boolean MatchContext()
{
if ( !CodeMatch( performer.getProviderOrPatient(), performerKnowledgeUserType, supportedCodeSystems, false,
request ) )
{
return false;
}
if ( !CodeMatch( performer.getLanguage(), performerLanguage, supportedCodeSystems, false, request ) )
{
return false;
}
if ( !CodeMatch( performer.getHealthCareProvider(), performerDiscipline, supportedCodeSystems, false, request ) )
{
return false;
}
return true;
}
}
|
Acidburn0zzz/cds | cli/cds/environment/update.go | package environment
import (
"fmt"
"github.com/spf13/cobra"
"github.com/ovh/cds/sdk"
)
func environmentUpdateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "update",
Short: "cds environment update <projectKey> <oldEnvironmentName> <newEnvironmentName>",
Long: ``,
Run: updateEnvironment,
}
return cmd
}
func updateEnvironment(cmd *cobra.Command, args []string) {
if len(args) != 3 {
sdk.Exit("Wrong usage: see %s\n", cmd.Short)
}
projectKey := args[0]
oldName := args[1]
newName := args[2]
err := sdk.UpdateEnvironment(projectKey, oldName, newName)
if err != nil {
sdk.Exit("Error: %s\n", err)
}
fmt.Printf("Environment %s updated.\n", newName)
}
|
PolyphasicDevTeam/NMO | src/nmo/integration/discord/IntegrationDiscord.java | package nmo.integration.discord;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import net.dv8tion.jda.client.entities.Group;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.PrivateChannel;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import nmo.Action;
import nmo.CommonUtils;
import nmo.Integration;
import nmo.MainDialog;
import nmo.config.NMOConfiguration;
public class IntegrationDiscord extends Integration
{
public static final IntegrationDiscord INSTANCE = new IntegrationDiscord();
static JDA jda = null;
static String lastMessage = "";
public IntegrationDiscord()
{
super("discord");
}
@Override
public boolean isEnabled()
{
return NMOConfiguration.INSTANCE.integrations.discord.enabled;
}
@Override
public void init() throws Exception
{
if (CommonUtils.isNullOrEmpty(NMOConfiguration.INSTANCE.integrations.discord.authToken))
{
throw new Exception("You need to specify discord authToken in the configuration file in order for discord integration to work");
}
jda = new JDABuilder(AccountType.CLIENT).setToken(NMOConfiguration.INSTANCE.integrations.discord.authToken).buildBlocking();
jda.getPresence().setGame(Game.of("NMO"));
for (int i = 0; i < NMOConfiguration.INSTANCE.integrations.discord.messages.length; i++)
{
final SendableMessage message = NMOConfiguration.INSTANCE.integrations.discord.messages[i];
this.actions.put("/discord/" + i, new Action()
{
@Override
public void onAction(Map<String, String[]> parameters) throws Exception
{
IntegrationDiscord.this.send(message, parameters);
}
@Override
public String getName()
{
return "SEND " + message.name;
}
@Override
public String getDescription()
{
return message.description;
}
@Override
public boolean isHiddenFromFrontend()
{
return false;
}
@Override
public boolean isHiddenFromWebUI()
{
return true;
}
@Override
public boolean isBlockedFromWebUI()
{
return true;
}
});
}
}
@Override
public void update() throws Exception
{
if (!lastMessage.equals(MainDialog.scheduleStatusShort))
{
lastMessage = MainDialog.scheduleStatusShort;
jda.getPresence().setGame(Game.of(MainDialog.scheduleStatusShort));
}
}
@Override
public void shutdown() throws Exception
{
if (jda != null)
{
jda.shutdown();
}
}
public void send(SendableMessage message, Map<String, String[]> parameters)
{
if (jda != null)
{
String actualMessage = "`NMO` <:nmo:341127544113987585> " + message.message;
// replace context
String[] context = parameters == null ? null : parameters.get("context");
if (context != null)
{
actualMessage = actualMessage.replaceAll("\\Q{context}\\E", StringUtils.join(context, " "));
}
switch (message.targetType)
{
case SERVER:
TextChannel channel = jda.getTextChannelById(message.targetID);
if (channel != null)
{
channel.sendMessage(actualMessage).complete();
}
break;
case GROUP:
Group group = jda.asClient().getGroupById(message.targetID);
if (group != null)
{
group.sendMessage(actualMessage).complete();
}
break;
case USER:
User user = jda.getUserById(message.targetID);
if (user != null)
{
PrivateChannel pchannel = user.openPrivateChannel().complete();
pchannel.sendMessage(actualMessage).complete();
}
break;
}
}
}
}
|
manos-mark/restful-prototype-asset-management | backend/src/main/java/com/manos/prototype/entity/Project.java | package com.manos.prototype.entity;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Store;
@Entity
@Table(name = "project")
@Indexed
@Analyzer(definition = "customanalyzer")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
@Column(name = "project_name")
@Analyzer(definition = "customanalyzer")
private String projectName;
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
@Column(name = "company_name")
@Analyzer(definition = "customanalyzer")
private String companyName;
@Column(name = "creation_date")
private LocalDateTime createdAt;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "status_id")
private Status status;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "project_manager_id")
@IndexedEmbedded
private ProjectManager projectManager;
@OneToMany(mappedBy = "project")
private List<Product> products = new ArrayList<>();
public Project(int id) {
this.id = id;
}
public Project() {
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public ProjectManager getProjectManager() {
return projectManager;
}
public void setProjectManager(ProjectManager projectManager) {
this.projectManager = projectManager;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
|
rueyaa332266/testcafe | test/functional/fixtures/regression/gh-1140/testcafe-fixtures/index.test.js | fixture `gh-1140`
.page('http://localhost:3000/fixtures/regression/gh-1140/pages/index.html');
test('Perform an action after iframe reloaded', async t => {
await t
.switchToIframe('#iframe')
.click('#target')
.switchToMainWindow()
.click('#target');
});
|
c4dt/stainless | frontends/benchmarks/extraction/invalid/TraitVar1.scala | <gh_stars>100-1000
import stainless.lang._
object TraitVar1 {
sealed trait Foo {
var prop: BigInt
def doStuff(x: BigInt) = {
prop = x
}
}
case class Bar(var stuff: BigInt) extends Foo {
def prop: BigInt = stuff + 1
def prop_=(y: BigInt): Unit = {
stuff = y * 2
}
}
def theorem(foo: Foo) = {
require(foo.isInstanceOf[Bar])
foo.doStuff(2)
foo.prop == 5
}.holds
}
|
qinFamily/freeVM | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jpda/jdwp/scenario/EVENT007/EventTest007.java | <reponame>qinFamily/freeVM
/*
* 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.
*/
/**
* @author <NAME>
* @version $Revision: 1.2 $
*/
/**
* Created on 14.10.2005
*/
package org.apache.harmony.test.stress.jpda.jdwp.scenario.EVENT007;
import java.util.Date;
import org.apache.harmony.test.stress.jpda.jdwp.scenario.share.StressTestCase;
import org.apache.harmony.share.Result;
import org.apache.harmony.share.framework.jpda.jdwp.CommandPacket;
import org.apache.harmony.share.framework.jpda.jdwp.JDWPCommands;
import org.apache.harmony.share.framework.jpda.jdwp.JDWPConstants;
import org.apache.harmony.share.framework.jpda.jdwp.ParsedEvent;
import org.apache.harmony.share.framework.jpda.jdwp.ParsedEvent.*;
import org.apache.harmony.share.framework.jpda.jdwp.ReplyPacket;
import org.apache.harmony.share.framework.jpda.jdwp.Location;
/**
* This test case exercises the JDWP agent when only two event
* requests are sent with suspendPolicy = NONE, which cause
* very big number of asynchronous events in many threads in debuggee.
* Before each thread enters in test method to cause expected events
* the debuggee creates memory stress until OutOfMemory happens.
* The tests expects that at once all expected 'METHOD_ENTRY' events
* and all expected 'METHOD_EXIT' events are received.
*/
public class EventTest007 extends StressTestCase {
public final static String DEBUGGEE_CLASS_NAME =
"org.apache.harmony.test.stress.jpda.jdwp.scenario.EVENT007.EventDebuggee007";
public final static String DEBUGGEE_SIGNATURE =
"L" + DEBUGGEE_CLASS_NAME.replace('.','/') + ";";
public final static String THREAD_CLASS_SIGNATURE =
"Lorg/apache/harmony/test/stress/jpda/jdwp/scenario/EVENT007/EventDebuggee007_Thread;";
protected String getDebuggeeClassName() {
return DEBUGGEE_CLASS_NAME;
}
/**
* This test case exercises the JDWP agent when only two event
* requests are sent with suspendPolicy = NONE, which cause
* very big number of asynchronous events in many threads in debuggee.
* Before each thread enters in test method to cause expected events
* the debuggee creates memory stress until OutOfMemory happens.
* The tests expects that at once all expected 'METHOD_ENTRY' events
* and all expected 'METHOD_EXIT' events are received.
*/
public Result testEvent007() {
logWriter.println("==> testEvent007: START (" + new Date() + ")...");
if ( waitForDebuggeeClassLoad(DEBUGGEE_CLASS_NAME) == FAILURE ) {
return failed("## FAILURE while DebuggeeClassLoad.");
}
if ( setupSignalWithWait() == FAILURE ) {
terminateDebuggee(FAILURE, "MARKER_01");
return failed("## FAILURE while setupSignalWithWait.");
}
if ( setupThreadSignalWithWait() == FAILURE ) {
terminateDebuggee(FAILURE, "MARKER_02");
return failed("## FAILURE while setupThreadSignalWithWait.");
}
resumeDebuggee("#1");
try {
logWriter.println("==> Wait for debuggee to start big number of treads ('SIGNAL_READY_01')...");
String debuggeeSignal = receiveSignalWithWait(currentTimeout());
if ( ! SIGNAL_READY_01.equals(debuggeeSignal) ) {
terminateDebuggee(FAILURE, "MARKER_03");
return failed
("## FAILURE while receiving 'SIGNAL_READY_01' Signal from debuggee");
}
printlnForDebug("received debuggee Signal = " + debuggeeSignal);
logWriter.println("\n");
logWriter.println
("==> Send VirtualMachine.AllThreads after big number of threads started in debuggee...");
CommandPacket packet = new CommandPacket(
JDWPCommands.VirtualMachineCommandSet.CommandSetID,
JDWPCommands.VirtualMachineCommandSet.AllThreadsCommand);
long measurableCodeStartTimeMlsec = System.currentTimeMillis();
ReplyPacket reply = debuggeeWrapper.vmMirror.performCommand(packet);
long measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Command running time(mlsecs) = " + measurableCodeRunningTimeMlsec);
int[] expectedErrors = {JDWPConstants.Error.NONE, JDWPConstants.Error.OUT_OF_MEMORY};
if ( checkReplyForError(reply, expectedErrors,
"VirtualMachine.AllThreads command") ) {
terminateDebuggee(FAILURE, "MARKER_04");
return failed
("## FAILURE while running VirtualMachine.AllThreads command");
}
if ( printExpectedError(reply, JDWPConstants.Error.OUT_OF_MEMORY,
"VirtualMachine.AllThreads command") ) {
terminateDebuggee(SUCCESS, "MARKER_05");
return passed
("==> OutOfMemory while running VirtualMachine.AllThreads command - Expected result!");
}
logWriter.println("\n");
logWriter.println
("==> Prepare and send requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events...");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
logWriter.println("==> Get debuggeeRefTypeID...");
long debuggeeRefTypeID = debuggeeWrapper.vmMirror.getClassID(DEBUGGEE_SIGNATURE);
if ( debuggeeRefTypeID == -1 ) {
logWriter.println("## FAILURE: Can NOT get debuggeeRefTypeID");
terminateDebuggee(FAILURE, "MARKER_06");
return failed("## Can NOT get debuggeeRefTypeID!");
}
logWriter.println("==> debuggeeRefTypeID = " + debuggeeRefTypeID);
logWriter.println("==> Get threadRefTypeID...");
long threadRefTypeID = debuggeeWrapper.vmMirror.getClassID(THREAD_CLASS_SIGNATURE);
if ( threadRefTypeID == -1 ) {
logWriter.println("## FAILURE: Can NOT get threadRefTypeID");
terminateDebuggee(FAILURE, "MARKER_07");
return failed("## Can NOT get threadRefTypeID!");
}
logWriter.println("==> threadRefTypeID = " + threadRefTypeID);
logWriter.println("==> Get startedThreadsNumber value from debuggee...");
int startedThreadsNumber =
getIntValueForStaticField(debuggeeRefTypeID, "startedThreadsNumber");
if ( startedThreadsNumber == BAD_INT_VALUE ) {
logWriter.println("## FAILURE: Can NOT get startedThreadsNumber");
terminateDebuggee(FAILURE, "MARKER_08");
return failed("## Can NOT get startedThreadsNumber");
}
logWriter.println("==> startedThreadsNumber = " + startedThreadsNumber);
String[] startedThreadsNames = new String[startedThreadsNumber];
long[] startedThreadsIDs = new long[startedThreadsNumber];
int methodEntryRequestID = NO_REQUEST_ID;
int methodExitRequestID = NO_REQUEST_ID;
for (int i=0; i < startedThreadsNumber; i++) {
startedThreadsNames[i] = EventDebuggee007.THREAD_NAME_PATTERN + i;
startedThreadsIDs[i] = NO_THREAD_ID;
}
int allThreads = reply.getNextValueAsInt();
int testCaseStatus = SUCCESS;
for (int i=0; i < allThreads; i++) {
long threadID = reply.getNextValueAsThreadID();
String threadName = null;
try {
threadName = debuggeeWrapper.vmMirror.getThreadName(threadID);
} catch (Throwable thrown ) {
// ignore
continue;
}
int threadIndex = 0;
for (; threadIndex < startedThreadsNumber; threadIndex++) {
if ( startedThreadsNames[threadIndex].equals(threadName) ) {
startedThreadsIDs[threadIndex] = threadID;
break;
}
}
}
logWriter.println
("==> Send requests for 'METHOD_ENTRY' event...");
ReplyPacket setEventReply = null;
setEventReply = setEventRequest(JDWPConstants.EventKind.METHOD_ENTRY,
JDWPConstants.SuspendPolicy.NONE, ANY_THREAD, threadRefTypeID, 0);
if ( setEventReply == null ) {
logWriter.println("## FAILURE: Can NOT set event request:");
logWriter.println("## Event kind = " + JDWPConstants.EventKind.METHOD_ENTRY +
"(" + JDWPConstants.EventKind.getName(JDWPConstants.EventKind.METHOD_ENTRY));
testCaseStatus = FAILURE;
} else {
if ( checkReplyForError(setEventReply, JDWPConstants.Error.NONE,
"EventRequest.set command for METHOD_ENTRY") ) {
testCaseStatus = FAILURE;
} else {
methodEntryRequestID = setEventReply.getNextValueAsInt();
}
}
logWriter.println
("==> Send requests for 'METHOD_EXIT' event...");
setEventReply = setEventRequest(JDWPConstants.EventKind.METHOD_EXIT,
JDWPConstants.SuspendPolicy.NONE, ANY_THREAD, threadRefTypeID, 0);
if ( setEventReply == null ) {
logWriter.println("## FAILURE: Can NOT set event request:");
logWriter.println("## Event kind = " + JDWPConstants.EventKind.METHOD_EXIT +
"(" + JDWPConstants.EventKind.getName(JDWPConstants.EventKind.METHOD_EXIT));
testCaseStatus = FAILURE;
} else {
if ( checkReplyForError(setEventReply, JDWPConstants.Error.NONE,
"EventRequest.set command for METHOD_EXIT") ) {
testCaseStatus = FAILURE;
} else {
methodExitRequestID = setEventReply.getNextValueAsInt();
}
}
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time (mlsecs) of preparing requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events " +
"= " + measurableCodeRunningTimeMlsec);
if ( testCaseStatus == FAILURE ) {
logWriter.println("## FAILURE: Can NOT set requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events!");
terminateDebuggee(FAILURE, "MARKER_09");
return failed
("## FAILURE while sending requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events");
}
logWriter.println("==> Resume debuggee and wait for creating memory stress in debuggee...");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
resumeDebuggee("#1.1");
debuggeeSignal = receiveSignalWithWait(currentTimeout());
if ( ! SIGNAL_READY_02.equals(debuggeeSignal) ) {
terminateDebuggee(FAILURE, "MARKER_09.5");
return failed
("## FAILURE while receiving 'SIGNAL_READY_02' Signal from debuggee");
}
printlnForDebug("received debuggee Signal = " + debuggeeSignal);
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time(mlsecs) of waiting for creating memory stress in debuggee = " +
measurableCodeRunningTimeMlsec);
logWriter.println("\n");
logWriter.println
("==> Resume debuggee to allow all threads to enter in test method and cause events...");
resumeDebuggee("#2");
logWriter.println("\n");
logWriter.println("==> Wait for all debuggee's threads exit from test method...");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
debuggeeSignal = receiveSignalWithWait(currentTimeout());
if ( ! SIGNAL_READY_03.equals(debuggeeSignal) ) {
terminateDebuggee(FAILURE, "MARKER_10");
return failed
("## FAILURE while receiving 'SIGNAL_READY_03' Signal from debuggee");
}
printlnForDebug("received debuggee Signal = " + debuggeeSignal);
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time (mlsecs) of waiting for all debuggee's threads exit from test method = " +
measurableCodeRunningTimeMlsec);
logWriter.println("\n");
logWriter.println
("==> Check that all expected 'METHOD_ENTRY' and 'METHOD_EXIT' events are generated...");
int receivingEventsStatus = SUCCESS;
int receivedMethodEntryEvents = 0;
int receivedMethodExitEvents = 0;
String expectedMethodName = "testMethod";
measurableCodeStartTimeMlsec = System.currentTimeMillis();
limitedPrintlnInit(20);
boolean toBreak = false;
for (int i=0; i < startedThreadsNumber; i++) {
while ( methodEntryRequestID != NO_REQUEST_ID ) {
ParsedEvent event = receiveEvent(NO_REQUEST_ID, JDWPConstants.EventKind.METHOD_ENTRY,
startedThreadsIDs[i], currentTimeout());
if ( event == null ) {
receivingEventsStatus = FAILURE;
logWriter.println
("## FAILURE: Can NOT receive expected 'METHOD_ENTRY' event for thread name = " +
startedThreadsNames[i]);
logWriter.println("## Event index = " + i);
toBreak = true;
break;
}
int requestID = event.getRequestID();
if ( requestID != methodEntryRequestID ) {
boolean toPrn = limitedPrintln
("## FAILURE: Unexpected requestID for received event for thread name = " +
startedThreadsNames[i]);
if ( toPrn ) {
logWriter.println("## Received requestID = " + requestID);
logWriter.println("## Expected requestID = " + methodEntryRequestID);
}
receivingEventsStatus = FAILURE;
break;
}
byte eventKind = event.getEventKind();
if ( eventKind != JDWPConstants.EventKind.METHOD_ENTRY ) {
boolean toPrn = limitedPrintln("## FAILURE: Unexpected event for thread name = " +
startedThreadsNames[i]);
if ( toPrn ) {
logWriter.println("## Received event kind = " + eventKind +
"(" + JDWPConstants.EventKind.getName(eventKind));
logWriter.println("## Expected event kind = " + JDWPConstants.EventKind.METHOD_ENTRY +
"(" + JDWPConstants.EventKind.getName(JDWPConstants.EventKind.METHOD_ENTRY));
}
receivingEventsStatus = FAILURE;
break;
}
Location location = ((Event_METHOD_ENTRY)event).getLocation();
long methodID = location.methodID;
String methodName = debuggeeWrapper.vmMirror.getMethodName(threadRefTypeID, methodID);
if ( ! expectedMethodName.equals(methodName) ) {
boolean toPrn = limitedPrintln("## FAILURE: Unexpected method name for 'METHOD_ENTRY' event");
if ( toPrn ) {
logWriter.println("## Received method name = " + methodName);
logWriter.println("## Expected method name = " + expectedMethodName);
}
receivingEventsStatus = FAILURE;
break;
}
receivedMethodEntryEvents++;
break;
}
if ( toBreak ) {
break;
}
if ( methodExitRequestID != NO_REQUEST_ID ) {
ParsedEvent event = receiveEvent(NO_REQUEST_ID, JDWPConstants.EventKind.METHOD_EXIT,
startedThreadsIDs[i], currentTimeout());
if ( event == null ) {
receivingEventsStatus = FAILURE;
logWriter.println
("## FAILURE: Can NOT receive expected 'METHOD_EXIT' event for thread name = " +
startedThreadsNames[i]);
logWriter.println("## Event index = " + i);
break;
}
int requestID = event.getRequestID();
if ( requestID != methodExitRequestID ) {
boolean toPrn = limitedPrintln
("## FAILURE: Unexpected requestID for received event for thread name = " +
startedThreadsNames[i]);
if ( toPrn ) {
logWriter.println("## Received requestID = " + requestID);
logWriter.println("## Expected requestID = " + methodExitRequestID);
}
receivingEventsStatus = FAILURE;
continue;
}
byte eventKind = event.getEventKind();
if ( eventKind != JDWPConstants.EventKind.METHOD_EXIT ) {
boolean toPrn = limitedPrintln("## FAILURE: Unexpected event for thread name = " +
startedThreadsNames[i]);
if ( toPrn ) {
logWriter.println("## Received event kind = " + eventKind +
"(" + JDWPConstants.EventKind.getName(eventKind));
logWriter.println(
"## Expected event kind = " + JDWPConstants.EventKind.METHOD_EXIT +
"(" + JDWPConstants.EventKind.getName(JDWPConstants.EventKind.METHOD_EXIT));
}
receivingEventsStatus = FAILURE;
continue;
}
Location location = ((Event_METHOD_EXIT)event).getLocation();
long methodID = location.methodID;
String methodName = debuggeeWrapper.vmMirror.getMethodName(threadRefTypeID, methodID);
if ( ! expectedMethodName.equals(methodName) ) {
boolean toPrn = limitedPrintln("## FAILURE: Unexpected method name for 'METHOD_EXIT' event");
if ( toPrn ) {
logWriter.println("## Received method name = " + methodName);
logWriter.println("## Expected method name = " + expectedMethodName);
}
receivingEventsStatus = FAILURE;
continue;
}
receivedMethodExitEvents++;
}
}
logWriter.println
("==> Number of received 'METHOD_ENTRY' events = " + receivedMethodEntryEvents );
logWriter.println
("==> Number of received 'METHOD_EXIT' events = " + receivedMethodExitEvents );
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time(mlsecs) of receiving all expected 'METHOD_ENTRY' and 'METHOD_EXIT' events = " +
measurableCodeRunningTimeMlsec);
if ( receivingEventsStatus == FAILURE ) {
logWriter.println
("## FAILURE while receiving 'METHOD_ENTRY' and 'METHOD_EXIT' events!");
terminateDebuggee(FAILURE, "MARKER_10.1");
return failed("## FAILURE while receiving 'METHOD_ENTRY' and 'METHOD_EXIT' events! ");
} else {
logWriter.println
("==> OK - all expected 'METHOD_ENTRY' and 'METHOD_EXIT' events are received!");
}
int clearingRequestsStatus = SUCCESS;
logWriter.println("\n");
logWriter.println
("==> Clear requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events...");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
if ( methodEntryRequestID != NO_REQUEST_ID ) {
reply = clearEventRequest
(JDWPConstants.EventKind.METHOD_ENTRY, methodEntryRequestID);
if ( checkReplyForError
(reply, JDWPConstants.Error.NONE,
"EventRequest.Clear command") ) {
logWriter.println("\n");
logWriter.println
("## FAILURE: Can NOT clear event request for 'METHOD_ENTRY' event");
clearingRequestsStatus = FAILURE;
}
}
if ( methodExitRequestID != NO_REQUEST_ID ) {
reply = clearEventRequest
(JDWPConstants.EventKind.METHOD_EXIT, methodExitRequestID);
if ( checkReplyForError
(reply, JDWPConstants.Error.NONE,
"EventRequest.Clear command") ) {
logWriter.println("\n");
logWriter.println
("## FAILURE: Can NOT clear event request for 'METHOD_EXIT' event");
clearingRequestsStatus = FAILURE;
}
}
if ( clearingRequestsStatus == FAILURE ) {
testCaseStatus = FAILURE;
} else {
logWriter.println
("==> OK - requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events are cleared!");
}
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time(mlsecs) of clearing all requests for 'METHOD_ENTRY' and 'METHOD_EXIT' events = " +
measurableCodeRunningTimeMlsec);
logWriter.println("\n");
logWriter.println("==> Resume debuggee to allow all threads to finish...");
resumeDebuggee("#3");
logWriter.println("\n");
logWriter.println("==> Wait for all threads finish in debuggee...");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
printlnForDebug("receiving 'SIGNAL_READY_04' Thread Signal from debuggee...");
debuggeeSignal = receiveThreadSignalWithWait();
if ( ! SIGNAL_READY_04.equals(debuggeeSignal) ) {
terminateDebuggee(FAILURE, "MARKER_11");
return failed
("## FAILURE while receiving 'SIGNAL_READY_04' Thread Signal from debuggee");
}
printlnForDebug("received debuggee Thread Signal = " + debuggeeSignal);
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time(mlsecs) of waiting for all threads finish in debuggee = " + measurableCodeRunningTimeMlsec);
logWriter.println("\n");
logWriter.println("==> Resume debuggee to allow it to finish...");
resumeDebuggee("#4");
logWriter.println("\n");
logWriter.println("==> Wait for VM_DEATH event ... ");
measurableCodeStartTimeMlsec = System.currentTimeMillis();
ParsedEvent event = receiveEvent(
NO_REQUEST_ID, NO_EVENT_KIND, ANY_THREAD, currentTimeout());
byte eventKind = event.getEventKind();
if ( eventKind != JDWPConstants.EventKind.VM_DEATH ) {
logWriter.println("## FAILURE: Unexpected event is received:");
logWriter.println("## Received event kind = " + eventKind +
"(" + JDWPConstants.EventKind.getName(eventKind));
logWriter.println
("## Expected event kind = " + JDWPConstants.EventKind.VM_DEATH +
"(" + JDWPConstants.EventKind.getName(JDWPConstants.EventKind.VM_DEATH));
testCaseStatus = FAILURE;
} else {
logWriter.println("==> OK - VM_DEATH event is received!");
}
measurableCodeRunningTimeMlsec = System.currentTimeMillis() - measurableCodeStartTimeMlsec;
logWriter.println
("==> Time(mlsecs) of waiting for VM_DEATH event = " + measurableCodeRunningTimeMlsec);
logWriter.println("\n");
long testRunTimeMlsec = System.currentTimeMillis() - testStartTimeMlsec;
logWriter.println("==> testEvent007: running time(mlsecs) = " + testRunTimeMlsec);
if ( testCaseStatus == FAILURE ) {
logWriter.println("==> testEvent007: FAILED");
return failed("testEvent007:");
} else {
logWriter.println("==> testEvent007: OK");
return passed("testEvent007: OK");
}
} catch (Throwable thrown) {
logWriter.println("## FAILURE: Unexpected Exception:");
printStackTraceToLogWriter(thrown);
terminateDebuggee(FAILURE, "MARKER_999");
logWriter.println("==> testEvent007: FAILED");
return failed("==> testEvent007: Unexpected Exception! ");
}
}
public static void main(String[] args) {
System.exit(new EventTest007().test(args));
}
}
|
cicsdev/cics-java-jcics-samples | projects/com.ibm.cicsdev.vsam/src/com/ibm/cicsdev/vsam/esds/EsdsExample3.java | <reponame>cicsdev/cics-java-jcics-samples<filename>projects/com.ibm.cicsdev.vsam/src/com/ibm/cicsdev/vsam/esds/EsdsExample3.java
/* Licensed Materials - Property of IBM */
/* */
/* SAMPLE */
/* */
/* (c) Copyright IBM Corp. 2017 All Rights Reserved */
/* */
/* US Government Users Restricted Rights - Use, duplication or disclosure */
/* restricted by GSA ADP Schedule Contract with IBM Corp */
/* */
package com.ibm.cicsdev.vsam.esds;
import com.ibm.cics.server.Task;
import com.ibm.cicsdev.bean.StockPart;
import com.ibm.cicsdev.vsam.StockPartHelper;
/**
* Simple example to demonstrate updating a record in a VSAM ESDS file using JCICS.
*
* This class is just the driver of the test. The main JCICS work is done in the
* common class {@link EsdsExampleCommon}.
*/
public class EsdsExample3
{
/**
* Main entry point to a CICS OSGi program.
*
* The FQ name of this class should be added to the CICS-MainClass entry in
* the parent OSGi bundle's manifest.
*/
public static void main(String[] args)
{
// Get details about our current CICS task
Task task = Task.getTask();
task.out.println(" - Starting EsdsExample3");
task.out.println("VSAM ESDS record update example");
// Create a new instance of the common ESDS class
EsdsExampleCommon ex = new EsdsExampleCommon();
/*
* Create a record in the file so we have something to work with.
*/
// Keep track of the RBA of the new record
long rba;
// Scoping of local variables
{
// Add a new record to the file
StockPart sp = StockPartHelper.generate();
rba = ex.addRecord(sp);
// Commit the unit of work
ex.commitUnitOfWork();
// Write out the RBA and description
String strMsg = "Wrote to RBA 0x%016X with description %s";
task.out.println( String.format(strMsg, rba, sp.getDescription().trim()) );
}
/*
* Now update this known record with a new description.
*/
// Scoping of local variables
{
// Generate a new part description
String strDesc = StockPartHelper.generateDescription();
// Update the known record with a specified description
StockPart sp = ex.updateRecord(rba, strDesc);
// Display the updated description
String strMsg = "Updated record with description %s";
task.out.println( String.format(strMsg, sp.getDescription().trim()) );
}
// Unit of work containing the update will be committed at normal end of task
// Completion message
task.out.println("Completed EsdsExample3");
}
}
|
QizaiMing/ergo-project-manager | issues/admin.py | from django.contrib import admin
from .models import Issue, Comment, Attachment, Link
# Register your models here.
admin.site.register(Issue)
admin.site.register(Comment)
admin.site.register(Attachment)
admin.site.register(Link) |
hdbeukel/genestacker | Genestacker/Genestacker-lib/src/main/java/org/ugent/caagt/genestacker/search/SelfingNode.java | // Copyright 2012 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.ugent.caagt.genestacker.search;
import java.util.Map;
import org.ugent.caagt.genestacker.exceptions.CrossingSchemeException;
import org.ugent.caagt.genestacker.exceptions.ImpossibleCrossingException;
/**
* Special extension of a crossing node to model selfings.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class SelfingNode extends CrossingNode {
/**
* Creates a new selfing node with automatically assigned ID.
* The number of performed duplicates is set to 1 and the selfing
* is automatically registered with its parent plant node.
*
* @param parent parent of the selfing
* @throws ImpossibleCrossingException should not be thrown for
* a selfing, parent is always compatible with itself
*/
public SelfingNode(PlantNode parent) throws ImpossibleCrossingException{
super(parent, parent);
}
/**
* Creates a new selfing node with given ID and number of performed duplicates.
* The selfing is automatically registered with its parent plant node.
*
* @param ID given ID
* @param numDuplicates number of performed duplicates (to generate sufficient seeds)
* @param parent parent of the selfing
* @throws ImpossibleCrossingException should not be thrown for
* a selfing, parent is always compatible with itself
*/
public SelfingNode(long ID, int numDuplicates, PlantNode parent) throws ImpossibleCrossingException{
super(ID, numDuplicates, parent, parent);
}
/**
* Override to register as selfing instead of plain crossing with parent plant.
*/
@Override
protected void registerWithParents(){
parent1.addSelfing(this);
}
@Override
public boolean isSelfing(){
return true;
}
public PlantNode getParent(){
return parent1;
}
/**
* Set the parent of this selfing.
*
* @param parent parent plant node
*/
public void setParent(PlantNode parent){
parent1 = parent;
parent2 = parent;
}
/**
* Overrides this method to ensure that both parents always refer to the same plant.
*
* @param parent parent plant node
*/
@Override
public void setParent1(PlantNode parent){
setParent(parent);
}
/**
* Overrides this method to ensure that both parents always refer to the same plant.
*
* @param parent parent plant node
*/
@Override
public void setParent2(PlantNode parent){
setParent(parent);
}
/**
* Create a deep copy of this selfing node node and its ancestor structure.
*
* @param shiftGen if <code>true</code> all generations are shifted (+1)
* @param curCopiedSeedLots currently already copied seed lot nodes
* @param curCopiedPlants currently already copied plant nodes
* @return deep copy of this selfing node and its ancestor structure, possibly with shifted generations (+1)
* @throws CrossingSchemeException if anything goes wrong while copying this or related nodes
*/
@Override
public CrossingNode deepUpwardsCopy(boolean shiftGen, Map<String, SeedLotNode> curCopiedSeedLots,
Map<String, PlantNode> curCopiedPlants)
throws CrossingSchemeException {
// copy parent
PlantNode parentCopy;
// check if parent plant was already copied (in case of multiple crossings with same plant)
if(curCopiedPlants.containsKey(getParent().getUniqueID())){
// take present copy
parentCopy = curCopiedPlants.get(getParent().getUniqueID());
} else {
// create new copy
parentCopy = getParent().deepUpwardsCopy(shiftGen, curCopiedSeedLots, curCopiedPlants);
curCopiedPlants.put(getParent().getUniqueID(), parentCopy);
}
// copy crossing node
SelfingNode copy = new SelfingNode(getID(), getNumDuplicates(), parentCopy);
return copy;
}
}
|
jurisz/adm-seed | core/api/src/main/java/org/juz/seed/api/security/RoleBean.java | <reponame>jurisz/adm-seed<filename>core/api/src/main/java/org/juz/seed/api/security/RoleBean.java<gh_stars>0
package org.juz.seed.api.security;
import java.util.Set;
public class RoleBean {
private Long id;
private String name;
private Set<String> permissions;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getPermissions() {
return permissions;
}
public void setPermissions(Set<String> permissions) {
this.permissions = permissions;
}
}
|
EmirWeb/liaison-loaders | loaders/src/main/java/mobi/liaison/loaders/Path.java | package mobi.liaison.loaders;
import android.net.Uri;
import android.text.TextUtils;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Created by <NAME> on 17/05/14.
*/
public class Path {
private static final String NUMERIC_EXCEPTION = "Expecting numeric value, cannot insert %s into '#'.";
private static final String MATCH_COUNT_MESSAGE = "Incoming values does not match number of bindings.";
private final String mPath;
private final List<String> mPathSegments;
public Path(final String path) {
mPath = path;
mPathSegments = new ArrayList<String>();
final StringTokenizer stringTokenizer = new StringTokenizer(path, "/");
while(stringTokenizer.hasMoreTokens()){
final String pathSegment = stringTokenizer.nextToken();
mPathSegments.add(pathSegment);
}
}
public Path(final String... pathSegments) {
mPath = TextUtils.join("/", pathSegments);
mPathSegments = Lists.newArrayList(pathSegments);
}
public int getPathSegmentCount(){
return mPathSegments.size();
}
public String getMatcherPath() {
return mPath;
}
public List<String> getPathSegments(final Object... objects) {
final List<String> pathSegments = new ArrayList<String>();
int objectIndex = 0;
for (int pathSegmentIndex = 0; pathSegmentIndex < mPathSegments.size(); pathSegmentIndex++){
final String pathSegment = mPathSegments.get(pathSegmentIndex);
final boolean isNumericSegmentPath = pathSegment.equals("#");
final boolean isStar = pathSegment.equals("*");
if (isNumericSegmentPath){
final Object object = objects[objectIndex++];
final boolean isObjectNumeric = object instanceof Number;
if (isObjectNumeric){
final Number number = (Number) object;
pathSegments.add(number.toString());
} else {
final String message = String.format(NUMERIC_EXCEPTION, object);
throw new IllegalArgumentException(message);
}
} else if (isStar) {
; final Object object = objects[objectIndex++];
pathSegments.add(object.toString());
} else {
pathSegments.add(pathSegment);
}
}
if (objectIndex != objects.length){
throw new IllegalArgumentException(MATCH_COUNT_MESSAGE);
}
return pathSegments;
}
public String getPath(final Object... objects){
final List<String> pathSegments = getPathSegments(objects);
return TextUtils.join("/", pathSegments);
}
@Override
public boolean equals(final Object object) {
if (object == null || !(object instanceof Path)){
return false;
}
final Path path = (Path) object;
if (!mPath.equals(path.mPath)){
return false;
}
if (mPathSegments.size() != path.mPathSegments.size()){
return false;
}
for (int index = 0; index < mPathSegments.size(); index++){
if (!mPathSegments.get(index).equals(path.mPathSegments.get(index))){
return false;
}
}
return true;
}
public boolean matches(final Uri uri) {
if (uri == null){
return false;
}
final List<String> pathSegments = uri.getPathSegments();
if (mPathSegments.size() != pathSegments.size()){
return false;
}
for (int index = 0; index < mPathSegments.size(); index++){
final String incomingPathSegment = pathSegments.get(index);
final String internalPathSegment = mPathSegments.get(index);
if (internalPathSegment.equals("#")) {
if (!isNumeric(incomingPathSegment)) {
return false;
}
} else if (!internalPathSegment.equals("*") && !internalPathSegment.equals(incomingPathSegment)){
return false;
}
}
return true;
}
private boolean isNumeric(final String string){
try{
Double.parseDouble(string);
return true;
} catch (final NumberFormatException numberFormatException) {
return false;
}
}
}
|
tanyutao544/digitalace-backend | core/tests/test_products_api.py | from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
# from company.serializers import ProductSerializer
from core.models import Company
PRODUCT_URL = reverse("company:product-list")
class PublicProductApiTest(TestCase):
"""Test the publicly available product API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""Test that login is required for retreiving products"""
res = self.client.get(PRODUCT_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateProductApiTest(TestCase):
"""Test authorized user product API"""
def setUp(self):
self.company = Company.objects.create(name="testcompany")
self.user = get_user_model().objects.create_user(
"<EMAIL>",
"<PASSWORD>",
is_staff=True,
company=self.company,
)
self.client = APIClient()
self.client.force_authenticate(self.user)
# TODO: exclude image/thumbnail from res.data
# def test_retreive_product(self):
# """Test retreiving product"""
# supplier = Supplier.objects.create(
# company=self.company, name="testsupplier"
# )
# testproductcategory = ProductCategory.objects.create(
# company=self.company, name="testproductname"
# )
# Product.objects.create(
# category=testproductcategory,
# supplier=supplier,
# name="testproduct",
# unit="0",
# cost="0",
# unit_price="0",
# )
# Product.objects.create(
# category=testproductcategory,
# supplier=supplier,
# name="testproduct2",
# unit="0",
# cost="0",
# unit_price="0",
# )
# res = self.client.get(PRODUCT_URL)
# products = Product.objects.all().order_by("-id")
# serializer = ProductSerializer(products, many=True)
# self.assertEqual(res.status_code, status.HTTP_200_OK)
# self.assertEqual(res.data.get("results", None), serializer.data)
# Deprecated: since user can only view products owned by their company
# def test_product_not_limited(self):
# """Test that product returned are visible by every user"""
# testuser = get_user_model().objects.create_user(
# "<EMAIL>" "<PASSWORD>"
# )
# testcompany = Company.objects.create(name="testcompany")
# supplier = Supplier.objects.create(
# company=testcompany, name='supplier'
# )
# testproductcategory = ProductCategory.objects.create(
# company=testcompany, name='testproductname'
# )
# Product.objects.create(
# category=testproductcategory,
# supplier=supplier,
# name='testproduct',
# unit='0',
# cost='0',
# unit_price='0',
# )
# Product.objects.create(
# category=testproductcategory,
# supplier=supplier,
# name='testproduct2',
# unit='0',
# cost='0',
# unit_price='0',
# )
# res = self.client.get(PRODUCT_URL)
# self.assertEqual(res.status_code, status.HTTP_200_OK)
# self.assertEqual(len(res.data), 2)
# self.user = testuser
# self.client.force_authenticate(self.user)
# res = self.client.get(PRODUCT_URL)
# self.assertEqual(res.status_code, status.HTTP_200_OK)
# self.assertEqual(len(res.data), 2)
|
rajesh1702/gulliver | frontend/mobile/android/src/com/lonelyplanet/trippy/android/AndroidProxy.java | <reponame>rajesh1702/gulliver
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lonelyplanet.trippy.android;
import android.os.Handler;
/**
* Class that is injected into the JavaScript namespace and allows advanced features.
* Runs in separate thread from main TrippyActivity thread.
*/
public class AndroidProxy {
public AndroidProxy(TrippyActivity trippyActivity, Handler handler, TripItemsDB tripItems,
boolean canNavigate, boolean canTakePicture) {
this.trippyActivity = trippyActivity;
this.handler = handler;
this.tripItems = tripItems;
this.canNavigate = canNavigate;
this.canTakePicture = canTakePicture;
}
///////////////////////////////////////////////
// Android -> Webapp
///////////////////////////////////////////////
/**
* Returns whether this device has navigation capability.
* Always true/false for a session
* @return true if this device has navigation capability.
*/
public boolean canNavigate() {
return canNavigate;
}
/**
* Returns whether this device has camera capability.
* Always true/false for a session
* @return true if this device has camera capability.
*/
public boolean canTakePicture() {
return canTakePicture;
}
/**
* Returns whether photos are associated with given trip item.
* @param tripItemId Id of trip item.
* @return true if photos are associated with given trip item.
*/
public boolean hasPictures(String tripItemId) {
// TODO: Implement for Trippy 2.0
return false;
}
///////////////////////////////////////////////
// Webapp -> Android
///////////////////////////////////////////////
/**
* Launch GPS Navigation app.
* Triggered from Navigate icon in Trippy web application.
* @param name Name of destination.
* @param address Address to navigate to.
* @param latLong Latitude and longitude to navigate to.
*/
public void doNavigate(final String name, final String address, final String latLong) {
handler.post(new Runnable() {
public void run() {
trippyActivity.navigate(name, address, latLong);
}
});
}
/**
* Take a picture and associate with a Trip Item.
* Triggered from Camera icon in Trippy web application.
* @param tripItemId Id of trip item to associate photos to.
*/
public void doTakePicture(String tripItemId) {
// TODO: Implement for Trippy 2.0
}
/**
* View pictures, starting with giben Trip Item.
* Triggered from Photo icon in Trippy web application.
* @param tripItemId
*/
public void doViewGallery(String tripItemId) {
// TODO: Implement for Trippy 2.0
}
///////////////////////////////////////////////
// Android access to trip items for Gallery.
///////////////////////////////////////////////
/**
* Called on loading a trip, adding/editing trip item, responding to getTripItems.
* Items for a trip are ordered by date and position.
* @param date e.g. "Day <integer>". 0 for unscheduled day.
* @param tripId
* @param tripItemId
* @param name
* @param location
* @param position position in the day for the trip item.
*/
@Deprecated
public void addTripItem(String date, String tripId, String tripItemId, String name,
String location, int position) {
tripItems.addTripItem(date, tripId, tripItemId, name, location, "", position);
}
/**
* Called on loading a trip, adding/editing trip item, responding to getTripItems.
* Items for a trip are ordered by date and position.
* @param date e.g. "Day <integer>". 0 for unscheduled day.
* @param tripId
* @param tripItemId
* @param name
* @param location e.g. "1020 North Rengstorff Avenue"
* @param latLong e.g. "37.420072,-122.095973"
* @param position position in the day for the trip item.
*/
public void addTripItem(String date, String tripId, String tripItemId, String name,
String location, String latLong, int position) {
tripItems.addTripItem(date, tripId, tripItemId, name, location, latLong, position);
}
/**
* Called on finish loading trip items, responding to getTripItems
*/
public void setFinishLoad() {
}
/**
* Called on delete trip item.
* @param tripItemId
*/
public void remTripItem(String tripItemId) {
tripItems.remTripItem(tripItemId);
}
/**
* Clear trip items
*/
public void clear() {
tripItems.clear();
}
/////////////
// Fields
/////////////
private boolean canNavigate;
private boolean canTakePicture;
// All operations on trippyActivity must be wrapped in handler
// for thread safety.
private Handler handler;
private TrippyActivity trippyActivity;
private TripItemsDB tripItems;
}
|
rswalia/open-source-contribution-for-beginners | MLSA Event-101/Data structure/Python/queue.py | <reponame>rswalia/open-source-contribution-for-beginners
from typing import Any
class Queue:
def __init__(self) -> None:
"""creates a queue data structure using linear array
Methods: enqueue, dequeue, isEmpty
"""
self.q = []
def __str__(self) -> str:
"""Used for printing the entire queue.
Returns:
str: Entire Queue as string to be printed out
"""
return str(self.q)
def enqueue(self, element: Any) -> None:
"""Add an object at the end of the Queue
Args:
element (<Any>): Object to be added to the Queue
"""
self.q.append(element)
def dequeue(self) -> Any:
"""Remove and return an element from the front of the Queue
Raises:
Exception: Queue Underflow: Raised if the Queue is empty and nothing to return
Returns:
Any: Object at the front of the Queue
"""
if not self.isEmpty():
front = self.q[0]
self.q = self.q[1:]
return front
else:
raise Exception("Queue Underflow")
def isEmpty(self) ->bool:
"""Check if the Queue is Empty
Returns:
bool: True if Empty, False otherwise.
"""
return True if self.q == [] else False
def reverse(self) -> None:
self.q.reverse()
def search(self, value: Any) -> int:
i = 0
for i in range(len(self.q)):
if self.q[i] == value:
return i |
jnthn/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/notAKeywords/Test.java | <filename>java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/notAKeywords/Test.java<gh_stars>1-10
import pkg.Bar;
import pkg.enum.Foo;
class Test {
void m() {
Bar b = new Bar();
b.doSomething(Foo.FOO); // with language level JDK 1.4 'enum' shouldn't be a keyword (see IDEA-67556)
}
} |
reels-research/iOS-Private-Frameworks | NanoTimeKitCompanion.framework/NTKWhistlerDigitalFaceView.h | <gh_stars>1-10
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/NanoTimeKitCompanion.framework/NanoTimeKitCompanion
*/
@interface NTKWhistlerDigitalFaceView : NTKFaceView {
bool _is24HourMode;
NTKLayoutRule * _timeLayoutRuleEditing;
NTKLayoutRule * _timeLayoutRuleNormal;
NTKTimeModuleView * _timeModuleView;
}
- (void).cxx_destruct;
- (void)_cleanupAfterZoom;
- (void)_configureComplicationView:(id)arg1 forSlot:(id)arg2;
- (void)_configureForTransitionFraction:(double)arg1 fromEditMode:(long long)arg2 toEditMode:(long long)arg3;
- (double)_keylineCornerRadiusForComplicationSlot:(id)arg1;
- (unsigned long long)_keylineLabelAlignmentForComplicationSlot:(id)arg1;
- (long long)_keylineStyleForComplicationSlot:(id)arg1;
- (void)_layoutForegroundContainerView;
- (void)_loadLayoutRules;
- (void)_loadLayoutRulesForState:(long long)arg1 withTopGap:(double)arg2 largeModuleHeight:(double)arg3;
- (void)_loadSnapshotContentViews;
- (double)_minimumBreathingScaleForComplicationSlot:(id)arg1;
- (bool)_needsForegroundContainerView;
- (id)_newLegacyViewForComplication:(id)arg1 family:(long long)arg2 slot:(id)arg3;
- (void)_prepareToZoomWithIconView:(id)arg1 minDiameter:(double)arg2 maxDiameter:(double)arg3;
- (void)_scrubToDate:(id)arg1 animated:(bool)arg2;
- (bool)_supportsTimeScrubbing;
- (void)_unloadSnapshotContentViews;
- (void)_updateLocale;
- (bool)complicationDisplayWrapperView:(id)arg1 shouldStartCustomDataAnimationFromEarlierView:(id)arg2 laterView:(id)arg3 isForward:(bool)arg4;
- (void)complicationDisplayWrapperView:(id)arg1 startCustomDataAnimationFromEarlierView:(id)arg2 laterView:(id)arg3 isForward:(bool)arg4 completionBlock:(id /* block */)arg5;
- (long long)complicationFamilyForSlot:(id)arg1;
- (void)dealloc;
@end
|
3dhater/Racer | src/libs/qlib/qblitq.cpp | <gh_stars>0
/*
* QBlitQ - a queue for multiple blits; optimizing blits
* 19-04-97: Created!
* (C) MarketGraph/RVG
*/
#include <qlib/canvas.h>
#include <qlib/blitq.h>
#include <stdio.h>
#include <stdlib.h>
#include <qlib/debug.h>
DEBUG_ENABLE
#define QUEUESIZE 500
QBlitQueue::QBlitQueue(QCanvas *icv)
{ cv=icv;
queueSize=QUEUESIZE;
q=(QBBlit*)qcalloc(queueSize*sizeof(QBBlit));
count=0;
}
QBlitQueue::~QBlitQueue()
{
if(q)qfree((void*)q);
}
bool QBlitQueue::AddBlit(QBitMap *sbm,int sx,int sy,int wid,int hgt,
int dx,int dy,int flags)
// Adds a blit to the queue
// Never fails (queue is flushed in case of overflow)
{ QBBlit *b;
// In case of overflow, execute the current list, so it is empty again
// (not that this is good optimizing this way!)
if(count>=queueSize)
{ qwarn("QBlitQueue: overflow; executing current list");
Execute();
}
b=&q[count];
b->sbm=sbm;
b->sx=sx; b->sy=sy;
b->wid=wid; b->hgt=hgt;
b->dx=dx; b->dy=dy;
b->flags=flags;
count++;
return TRUE;
}
void QBlitQueue::SetGC(QCanvas *ncv)
{
cv=ncv;
}
QBBlit *QBlitQueue::GetQBlit(int n)
// Used by QCanvas to optimized blitting a queue internally
{ if(n<0||n>=count)return 0;
return &q[n];
}
static void OutQBB(QBBlit *b)
{
qdbg(" sbm=%8p, src %3d,%3d size %3dx%3d, dst %3d,%3d, flags=%d\n",
b->sbm,b->sx,b->sy,b->wid,b->hgt,b->dx,b->dy,b->flags);
}
int QBlitQueue::DebugOut()
{ int i;
int area=0;
//qdbg("QBlitQueue (%p)\n",this);
for(i=0;i<count;i++)
{ if(q[i].flags&QBBF_OBSOLETE)continue;
//qdbg("%4d: ",i); OutQBB(&q[i]);
area+=q[i].wid*q[i].hgt;
}
//qdbg("---------- total area size: %7ld\n",area);
return area;
}
void QBlitQueue::Optimize()
// Try to optimize the blits by reasoning out obsolete ones, merging
// attached blits, and merging large and small overlapping blits, etc.
{ QBBlit *b,*bEarlier;
int i,j,diff;
#ifdef ND_TEMP
if(count<=1)return;
b=&q[count-1];
// Work through the blits in the order later to earlier.
// This way, a single blit may in 1 pass rule out several earlier blits.
// This looks faster than checking blits from earlier to later.
for(i=0;i<count;i++,b--)
{ // Don't check when the blit was already obsolete
// or the blit uses alpha (in which case it always needs something
// behind it).
if(b->flags&(QBBF_OBSOLETE|QBBF_BLEND))continue;
//qdbg("Compare "); OutQBB(b);
bEarlier=q;
for(j=i;j<count-1;j++,bEarlier++)
{ if(bEarlier->flags&QBBF_OBSOLETE)continue;
//qdbg("to "); OutQBB(bEarlier);
// Check overlapping destination
if(b->dx==bEarlier->dx&&b->dy==bEarlier->dy)
{ if(b->wid>=bEarlier->wid)
{ if(b->hgt>=bEarlier->hgt)
{ // We can rule out the earlier blit entirely
bEarlier->flags|=QBBF_OBSOLETE;
//qdbg("(earlier blit is obsolete; same dst & size overlap)\n");
} else
{ // We can strip some height of the earlier blit
diff=bEarlier->hgt-b->hgt;
//qdbg("(strip height of earlier blit; %d pixels)\n",diff);
bEarlier->sy+=b->hgt;
bEarlier->dy+=b->hgt;
bEarlier->hgt=diff;
}
}
#ifdef NOTDEF_BUGGY
else if(b->sbm==bEarlier->sbm&&
b->sx==bEarlier->sx&&b->sy==bEarlier->sy)
{ // The same image will be plotted, albeit not as big as the earlier
// blit; rule OURSELVES out.
printf("(done as part of earlier blit)\n");
b->flags|=QBBF_OBSOLETE;
// Do not continue?
break;
}
#endif
}
}
}
#endif
}
void QBlitQueue::Execute()
{ //QBBlit *b;
//int i;
//int aBefore,aAfter; // Area optimization
if(!count)return;
if(cv)cv->BlitQueue(this);
#ifdef OBSOLETE
//qdbg("QBlitQ: Execute\n");
aBefore=DebugOut();
Optimize();
aAfter=DebugOut();
qdbg(" Optimized from %ld to %ld pixels =%ld%%\n",aBefore,aAfter,
(aBefore-aAfter)*100/aBefore);
// Execute each blit
cv->Disable(QCANVASF_OPTBLIT); // Really blit now
for(i=0;i<count;i++)
{ b=&q[i];
if(b->flags&QBBF_OBSOLETE)continue;
if(b->flags&QBBF_BLEND)cv->Enable(QCANVASF_BLEND);
else cv->Disable(QCANVASF_BLEND);
cv->Blit(b->sbm,b->dx,b->dy,b->wid,b->hgt,b->sx,b->sy);
}
count=0;
#endif
}
//#define TEST
#ifdef TEST
void main()
{ QBlitQueue *bq;
QBitMap *bm[4];
int i;
for(i=0;i<4;i++)bm[i]=(QBitMap*)(i+1);
bq=new QBlitQueue();
#ifdef NOTDEF
// Lingo situation
bq->AddBlit(bm[0],250,500,51,52,250,500,0); // Rest bgr
bq->AddBlit(bm[1],50,60,51,52,250,500,0); // Board
bq->AddBlit(bm[2],0,0,51,52,250,460,1); // New letter position
#endif
//#ifdef NOTDEF
// Situation (Lingo) where lots of letters/hilites are suddenly used
// and get restored at their previous location, which is at first (0,0)
bq->AddBlit(bm[0],0,0,51,52,0,0);
bq->AddBlit(bm[0],0,0,51,52,0,0);
bq->AddBlit(bm[0],0,0,51,52,0,0);
bq->AddBlit(bm[0],0,0,51,52,0,0);
bq->AddBlit(bm[0],0,0,38,42,0,0); // Restore other sized thing
bq->AddBlit(bm[0],0,0,38,42,0,0);
//bq->AddBlit(bm[0],0,0,51,52,0,0); // Overrule last 2
bq->AddBlit(bm[2],0,0,51,52,200,400); // Hilite under letter
bq->AddBlit(bm[1],0,0,51,52,200,400,1); // New letters
bq->AddBlit(bm[1],0,0,51,52,251,400,1);
//#endif
#ifdef NOTDEF
// A letter half on the background, half on the board
bq->AddBlit(bm[0],250,400,38,42,250,400); // Bgr restore
bq->AddBlit(bm[1],50,100,38,20,250,400); // Board restore part
bq->AddBlit(bm[2],0,0,250,400,38,42,1); // Letter
#endif
bq->Execute();
}
#endif
|